C#中/winform中,给已经绑定数据的datagridview后台动态添加新行

说明:因为没有找到相关资料博客,所以暂定为原创,如果已经有了,请告知,并非刻意


在datagridview中,添加行有两种形式(我知道的)

第一种:修改datasource,直接修改绑定的datatable数据源,然后重新绑定到datagridview中。我们在添加行时,更新datatable即可,这一种很简单,不做太多描述,网上资料很多,请自行查阅

第二种:即我们在添加数据时,需要在后台动态的给datagridview添加一行或者多行数据,并添加到指定index中,或者添加到最后。下面是源代码:

        DataTable dtData = new DataTable();//绑定到datagridview的数据源

         DataRow drw = dtData.NewRow();//定义一行
            //以下为datagridview中有三列数据,需对应添加

            drw["ID"] = "1111";
            drw["Name"] = "测试";
            drw["Sex"] = "女";
           // dtData.Rows.Add(drw);//追加到datatable最后一行

            dtData.Rows.InsertAt(drw, 2);//添加到指定索引位置,“2”为索引。”e.RowIndex“为获取当前点击行的索引

            var newdt = dtData;//此为测试代码,查看添加新行后,绑定到datagridview的数据源(添加新行后,原绑定的datatable也会跟着添加此数据,可以获取所有的数据)


以上只作为自己总结所用,如有表达错误,请自行更正



  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
WinForm ,可以通过双向数据来实现 DataGridView 控件与数据源之间的数据同步。当数据源的值发生改变时,DataGridView 控件会自动刷显示;当用户在 DataGridView 修改了数据时,数据源的值也会自动更。 以下是实现双向数据的步骤: 1. 义一个实体类,来表示要数据对象,该实体类的属性应该和 DataGridView 的列一一对应。 ```C# public class Person { public string Name { get; set; } public int Age { get; set; } public string Gender { get; set; } } ``` 2. 在 Form 创建 DataGridView 控件,并设置其 DataSource 属性为 BindingSource 的实例。 ```C# BindingSource personSource = new BindingSource(); personSource.DataSource = typeof(Person); dataGridView1.DataSource = personSource; ``` 3. 创建一个 Person 对象的实例,并将其到 BindingSource 。 ```C# Person person = new Person() { Name = "Tom", Age = 20, Gender = "Male" }; personSource.Add(person); ``` 4. 在需要进双向数据DataGridView 列上,设置其 DataPropertyName 属性为 Person 对象的属性名。 ```C# dataGridView1.Columns["Name"].DataPropertyName = "Name"; dataGridView1.Columns["Age"].DataPropertyName = "Age"; dataGridView1.Columns["Gender"].DataPropertyName = "Gender"; ``` 5. 如果需要在 DataGridView 修改数据,可以通过 DataGridView 的 CurrentCellDirtyStateChanged 事件和 CellValueChanged 事件来实现数据源的更。 ```C# private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e) { if (dataGridView1.IsCurrentCellDirty) { dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit); } } private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0 && e.ColumnIndex >= 0) { Person person = personSource.Current as Person; personSource.EndEdit(); } } ``` 以上就是在 WinForm 实现双向数据的基本步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值