DataGridView绑定DataTable的正确姿势
Posted ccjungle
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DataGridView绑定DataTable的正确姿势相关的知识,希望对你有一定的参考价值。
1. 将DataTable 绑定到BindingSource
2. 将BindingSource绑定到DataGridView
3. DataGridView修改完要从Datatable取值时,同步过去时,BindingSource和DataGridView两个都要执行EndEdit()
例程:
public partial class Form1 : Form DataTable mTable = new DataTable(); BindingSource mbs = new BindingSource(); public Form1() InitializeComponent(); private void Form1_Load(object sender, EventArgs e) mTable.Columns.Add("Name",typeof(string)); mTable.Columns.Add("Age", typeof(float)); mTable.Columns.Add("Dept", typeof(string)); mTable.Columns.Add("IsDeleted", typeof(bool)); mTable.Rows.Add("Jack", 21, "C1", false); mTable.Rows.Add("Rose", 21, "C2", false); mTable.Rows.Add("Tom", 21, "C1", false); mTable.Rows.Add("Micky", 21, "C1", false); mTable.Rows.Add("Steven Chou", 21, "C1", false); mbs.DataSource = mTable; grd.DataSource = mbs; private void BtnDel_Click(object sender, EventArgs e) mTable.Rows.Remove(mTable.Rows[grd.CurrentRow.Index]); private void BtnSave_Click(object sender, EventArgs e) grd.EndEdit(); mbs.EndEdit(); int N = mTable.Rows.Count;
以上是关于DataGridView绑定DataTable的正确姿势的主要内容,如果未能解决你的问题,请参考以下文章
绑定到 DataTable 的 DataGridView 未显示
DataGridView绑定DataTable动态生成列 并且将列名中文显示
将 DataTable 绑定到已定义列的 Datagridview