关于table.LoadDataRow修改datable某一行的值

这篇博客探讨了如何利用table.LoadDataRow方法来修改DataTable中的行数据。当DataTable无主键时,此方法会插入新行;若有主键,则会更新对应行。通过示例展示了如何更新goo3字段,并讨论了如果更改为主键不存在的字段,将被视为新行。此外,还介绍了删除DataRow的两种方式:通过行实例和指定行号。最后,展示了如何对DataTable进行降序排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于table.LoadDataRow (obj,null)的解释是:

当table中没有主键时就插入该新行,有主键时就更新对应行

DataTable table = new DataTable();
            DataColumn col1 = new DataColumn("id", typeof(string));
            DataColumn col2 = new DataColumn("name", typeof(string));
            DataColumn col3 = new DataColumn("age", typeof(int));
            table.Columns.Add(col1);
            table.Columns.Add(col2);
            table.Columns.Add(col3);
            //给datatable设置主键
            DataColumn[] key = new DataColumn[1];
            key[0] = col1;
            table.PrimaryKey = key;
            //table.PrimaryKey = new DataColumn[] { table.Columns["id"] };

            DataRow row = table.NewRow();
            row[col1] = "G001";
            row[col2] = "yanxiangliang";
            row[col3] = "31";
            table.Rows.Add(row);

            row = table.NewRow();
            row[col1] = "G002";
            row[col2] = "zhangzhiguo";
            row[col3] = "32";
            table.Rows.Add(row);

            row = table.NewRow();
            row[col1] = "G003";
            row[col2] = "ls";
            row[col3] = "30";
            table.Rows.Add(row);

            Object[] find = new Object[3];
            find[0] = "G003";
            find[1] = "teswt";
            find[2] = 45;
            table.BeginLoadData();
            table.LoadDataRow(find, LoadOption.OverwriteChanges);
            table.EndLoadData();

可看到 更新了goo3那一行的数据,若改为goo4则会为新增行

其他应用:

删除datarow

            table.Rows.Remove(row4);删除航实例
            table.Rows.RemoveAt(3);//删除指定行


//对datatable排序
            DataView dv = table.DefaultView;
            dv.Sort = "age DESC";
            DataTable dt2 = dv.ToTable();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值