c# DataGridView实时刷新
using System;using System.Data;using System.Windows.Forms;namespace AhDung.Demos{ public partial class Form1 : Form { DataTable _table; public Form1() { InitializeComponent(); _table = new DataTable(); _table.Columns.Add("Col1", typeof(string)); _table.Columns.Add("Col2", typeof(string), "Col1 '_Modified'");//计算列 _table.Rows.Add("aaa"); _table.Rows.Add("bbb"); //指定哪些列使用自定的单元格类 dataGridView1.Columns["Column1"].CellTemplate = new DataGridViewTextBoxUnSelectableCell(); dataGridView1.AutoGenerateColumns = false; dataGridView1.DataSource = _table; } //单元格键入时实时提交 private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e) { if (dataGridView1.IsCurrentCellDirty) { dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit); (dataGridView1.CurrentRow.DataBoundItem as DataRowView).EndEdit();//连带数据源一起提交 } } } //定义一个单元格承载控件 public class TextBoxUnSelectableEditingControl : DataGridViewTextBoxEditingControl { protected override void WndProc(ref Message m) { if (m.Msg == 0xb1)//忽略EM_SETSEL消息 { return; } base.WndProc(ref m); } } //定义一个单元格类,重写此类的承载控件类型 public class DataGridViewTextBoxUnSelectableCell : DataGridViewTextBoxCell { public override Type EditType { get { return typeof(TextBoxUnSelectableEditingControl); } } }}
评论