难度:3
需要基础: 对数组有一定了解。
1.设置DataTable的主键
//Set up keys object for defining primary key
DataColumn[]keys = new DataColumn[1];
keys[0]=thisDataSet.Tables["Customers"].Columns["CustomerID"];
thisDataSet.Tables["Customers"].PrimaryKey = keys;
DataColumn[]keys = new DataColumn[1];
keys[0]=thisDataSet.Tables["Customers"].Columns["CustomerID"];
thisDataSet.Tables["Customers"].PrimaryKey = keys;
注:主键可由表的一列或多列(多主键,参照数据库相关书籍)构成,包含可以在表中唯一标示行的值或值集合。
如果希望在连接数据库,Fill数据表时,就自动对应数据库中表单的主键,复制过来。默认设置无法完成,需明确告诉DataAdapter。
thisAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
thisAdapter.Fill(thisDataSet, "Customers");2.查找表中是否存在主键值为XX的数据行
DataRow findRow = thisDataSet.Tables["Customers"].Rows.Find("XX");
该行代码是在上面代码的基础上运行的。
findRow为Null,表示不存在;否则指向该行。
3.删除数据表中的某一行
thisRow = thisDataSet.Tables["Cutomers"].Rows[3]; //指向某一行,也可以指向Find的某一行
thisRow.Delete();
thisRow.Delete();
实际上Delete()方法并不执行删除操作,只是将这行的RowState设置为Deleted,在Update()操作执行时,才集中删除和改动受影响的行和数据。
未完待续...
本文介绍了如何在C#中使用DataTable对象进行主键设置、查找特定主键值的记录及删除记录的方法。通过示例代码展示了如何定义主键、在填充数据表时指定主键并实现对数据的操作。
1363

被折叠的 条评论
为什么被折叠?



