我想做一个排序的 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
}
}