要实现在 datagridview 中动态的增删改查,目前能用的比较友好的方案似乎只有 datatable,网上有人说用 BindingList 的,我替你们试过了,无法筛选,坑很多
public partial class Form1 : Form { private DataTable dataTable = new DataTable(); private BindingSource bindingSource; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { dataTable.Columns.Add("Id", typeof(int)); dataTable.Columns.Add("Name", typeof(string)); dataTable.Columns.Add("Age", typeof(int)); for (var i = 0; i < 10; i++) { var row = dataTable.NewRow(); row["Id"] = i + 1; row["Name"] = "Name" + (i + 1).ToString(); row["Age"] = i + 20; dataTable.Rows.Add(row); } bindingSource = new BindingSource(); bindingSource.DataSource = new DataView(dataTable); dataGridView1.DataSource = bindingSource; } private void button1_Click(object sender, EventArgs e) { try { // 设置筛选条件 bindingSource.Filter = "Age > 25"; } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void button2_Click(object sender, EventArgs e) { var i = dataTable.Rows.Count ; var row = dataTable.NewRow(); row["Id"] = i + 1; row["Name"] = "Name" + (i + 1).ToString(); row["Age"] = i + 20; dataTable.Rows.Add(row); } private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { var column = dataGridView1.Columns[e.ColumnIndex]; if (column.HeaderCell.Tag == null) { column.HeaderCell.Tag = 1; column.HeaderCell.SortGlyphDirection = SortOrder.Ascending; } else { column.HeaderCell.Tag = null; column.HeaderCell.SortGlyphDirection = SortOrder.Descending; } // 执行排序 var direction = column.HeaderCell.SortGlyphDirection == SortOrder.Ascending ? ListSortDirection.Ascending : ListSortDirection.Descending; dataGridView1.Sort(column, direction); } }
标签:column,private,datagridview,HeaderCell,刷新,var,winform,dataTable,row From: https://www.cnblogs.com/nanfei/p/18312978