c# DataGridView做了分页以后不能即时刷新

qq_33678130 2016-01-08 05:58:53
现在winform上有一个datagridview,我绑定了一个sql表。但是在自己写了分页以后对这张表的记录增删改以后不能立马显示,要重新生成才显示的了。我用了adapter.update,然并卵。下面贴代码。
//update函数通过一个按钮调用,可以修改datagridview记录
public void update(string aid,string aname,string atel, string add,string time_)
{
//检查变量省略

//定义主键 表名 Users 字段userid
DataColumn[] keys = new DataColumn[1];
keys[0] = ds.Tables["Users"].Columns["userid"];

//查询给定的id
ds.Tables["Users"].PrimaryKey = keys;
DataRow myrow = ds.Tables["Users"].Rows.Find(aid);

//更新记录
myrow["username"] = aname;
myrow["telphone"] = atel;
myrow["address"] = add;
myrow["createtime"] = today;

//更新表单和datasource
Adapter.Update(ds, "Users");
//Adapter.Fill(ds, "new_table");
this.show(CurrentPageNum, PageCount);//用于显示分页的函数,如下
this.dataGridView1.DataSource = ds.Tables[1];
}

//用于显示分页的函数
private void show(int start, int end)
{

DataTable dt = ds.Tables["Users"];

//这一段处理要复制的记录--可以忽略掉
int start_index = (start - 1) * PageSize;
int end_index = 0;
if (start_index + PageSize > TotalPage)
{
int remain = TotalPage - (start - 1) * PageSize;
end_index = start_index + remain - 1;
}
else
{
end_index = start_index + PageSize - 1;
}

//这里尝试复制Datatable dt的一部分记录到新的datatable new_table
//new_table定义了私有变量

for (int i = start_index; i <= end_index; ++i)
{
try
{

DataRow dr = new_table.NewRow();
dr.ItemArray = ds.Tables[0].Rows[i].ItemArray;
new_table.Rows.Add(dr);
}
catch (Exception ex)
{
}
}
//改变datagridview1的数据源 ---在这里更新了 但是new_table增改删后没有变化
Adapter.Update(ds, "new_table");
this.dataGridView1.DataSource = new_table;
}

求c#大神 感激不尽


...全文
562 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
sxl_88 2018-01-20
  • 打赏
  • 举报
回复
更改数据源后,重新绑定一下
思远笃行 2018-01-20
  • 打赏
  • 举报
回复
this.dataGridView1.DataSource = new_table; 前面加一行this.dataGridView1.DataSource=NULL;试试
ztsjznc 2018-01-17
  • 打赏
  • 举报
回复
重新绑定会跑位置的,你必须记录当前的分页数和当前记录数,实现修改后定位。
啊拉丁的鱼 2016-01-10
  • 打赏
  • 举报
回复
更改数据源后,重新绑定一下,还需要注意跨线程调用的问题。
Justin-Liu 2016-01-09
  • 打赏
  • 举报
回复
重新绑定一下

110,475

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧