c# - 自定义 Datagridview 分页
问题描述
我正在尝试进行 Datagridview 分页,我已经执行了分页并且工作正常,问题是当我尝试从数据库中搜索记录时,问题是 Datagridview 没有改变并且从数据库返回的数据没有显示并且每次搜索的页数不断增加。
请观看此视频: https ://www.youtube.com/watch?v=Ina0OlZagSo&ab_channel=RabeeQabaha
这是我的自定义 Datagridview 类:
class GV_Paging : Guna.UI2.WinForms.Guna2DataGridView
{
public int PageSize
{
get
{
return _pageSize;
}
set
{
_pageSize = value;
}
}
public int _pageSize = 10;
BindingSource bs = new BindingSource();
BindingList<DataTable> tables = new BindingList<DataTable>();
public void SetPagedDataSource(DataTable dataTable, BindingNavigator bnav)
{
DataTable dt = null;
int counter = 1;
foreach (DataRow dr in dataTable.Rows)
{
if (counter == 1)
{
dt = dataTable.Clone();
tables.Add(dt);
}
dt.Rows.Add(dr.ItemArray);
if (PageSize < ++counter)
{
counter = 1;
}
}
bnav.BindingSource = bs;
bs.DataSource = tables;
bs.PositionChanged += Bs_PositionChanged;
Bs_PositionChanged(bs, EventArgs.Empty);
}
void Bs_PositionChanged(object sender, EventArgs e)
{
this.DataSource = tables[bs.Position];
}
}
这就是我将数据填充到 Datagridview 的方式:
GV.PageSize = Convert.ToInt32(Math.Floor(Convert.ToDecimal(GV.Height / GV.RowTemplate.Height))) - 1;
DT = DBConn.ExecuteDataTable("select_all_materials", CommandType.StoredProcedure);
GV.SetPagedDataSource(DT, bindingNavigator1);
这是从数据库中搜索数据的代码(处理文本框文本更改):
GV.PageSize = Convert.ToInt32(Math.Floor(Convert.ToDecimal(GV.Height / GV.RowTemplate.Height))) - 1;
DT = DBConn.ExecuteDataTable("search_materials_by_name", CommandType.StoredProcedure, new
SqlParameter[] { new SqlParameter("@name", Material_name_txt.Text.Trim()) });
GV.SetPagedDataSource(DT, bindingNavigator1);
解决方案
经过努力,我能够解决问题,这里是工人阶级:
public int PageSize
{
get
{
return _pageSize;
}
set
{
_pageSize = value;
}
}
public int _pageSize = 10;
BindingSource bs;//= new BindingSource();
BindingList<DataTable> tables;// = new BindingList<DataTable>();
public void SetPagedDataSource(DataTable dataTable, BindingNavigator bnav)
{
if (dataTable == null || bnav == null)
{
return;
}
DataTable dt = null;
bs = new BindingSource();
tables = new BindingList<DataTable>();
int counter = 1;
foreach (DataRow dr in dataTable.Rows)
{
if (counter == 1)
{
dt = dataTable.Clone();
tables.Add(dt);
}
dt.Rows.Add(dr.ItemArray);
if (PageSize < ++counter)
{
counter = 1;
}
}
bnav.BindingSource = bs;
bs.DataSource = tables;
bs.PositionChanged += Bs_PositionChanged;
Bs_PositionChanged(bs, EventArgs.Empty);
}
void Bs_PositionChanged(object sender, EventArgs e)
{
try
{
this.DataSource = tables[bs.Position];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
推荐阅读
- powershell - 通过确认按钮提取组合框文本
- python - 如何 JSON 序列化 Python 类对象?
- r - 在 JSON 生成的嵌套数据框中取消嵌套列
- java - 关于 BFS 算法的困惑
- jdbc - 如何在 H2 控制台中安装 MYSQL 驱动程序
- microsoft-graph-api - 是否可以使用应用程序令牌凭据来使用搜索 API?
- javascript - 检索最近打开的文件
- angular - 为什么我在 dom 中收到“错误错误:选择器“ng-component”不匹配任何元素”?
- reactjs - 如何解决 React Redux 有效负载未传递给状态对象
- python - 具有全息视图和“散景”的 3d 曲面图