C# 如何强制刷新 DataGridView 的内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1365617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to force refresh the DataGridView's content?
提问by Hao
I want to make a sorted datagridview input. The following code snippet doesn't quite cut it; even if i put a grd.Refresh, the datagridview doesn't show its updated values. If i press arrow down key and go up again, the grid is refreshing. Is there any other way i can force refresh to datagridview's content?
我想进行排序的 datagridview 输入。下面的代码片段并没有完全削减它;即使我放了一个 grd.Refresh,datagridview 也不会显示其更新的值。如果我按下箭头键并再次向上,网格会刷新。有没有其他方法可以强制刷新 datagridview 的内容?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace TestSortedInput
{
public partial class Form1 : Form
{
DataTable _dt = new DataTable();
public Form1()
{
InitializeComponent();
grd.AllowUserToAddRows = false;
_dt.Columns.Add("sort", typeof(int));
_dt.Columns.Add("product", typeof(string));
_dt.DefaultView.Sort = "sort";
grd.DataSource = _dt;
}
private void dataGridView1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Insert)
{
if (e.Modifiers == 0)
{
var r = _dt.NewRow();
r["sort"] = _dt.DefaultView.Count + 1;
r["product"] = "";
_dt.Rows.Add(r);
}
else if (e.Alt)
{
var drv = this.BindingContext[_dt].Current as DataRowView;
int sort = (int)drv["sort"];
for (int i = _dt.DefaultView.Count - 1; i >= (int)drv["sort"] - 1; --i)
{
_dt.DefaultView[i]["sort"] = (int) _dt.DefaultView[i]["sort"] + 1;
}
var r = _dt.NewRow();
r["sort"] = sort;
_dt.Rows.Add(r);
grd.Refresh();
}
}
}//void
}
}
采纳答案by manji
replace
代替
grd.Refresh();
by
经过
drv.EndEdit();
the selected row is in edit mode, you have to end it for the sorting to take place.
所选行处于编辑模式,您必须结束它才能进行排序。
回答by MartW
Have you tried using a BindingSource with the source as the datatable, and then calling the BindingSource's ResetBindings method?
您是否尝试过将 BindingSource 与源作为数据表一起使用,然后调用 BindingSource 的 ResetBindings 方法?