DataTable的使用

267 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第18天,点击查看活动详情 >>

DataTable

  • Find方法筛选针对主键字段
dt.PrimaryKey = new DataColumn[] {dt.Columns["BookId"]};
  • Find方法查找
DataRow dr = ds.Tables["Student"].Rows.Find(txtQuerySNO.Text.Trim());

Trim()方法是删除字符串的头尾空白符方法

  • 设置唯一键及不可以为空
dc.Unique = true;
dc.AllowDBNull = false;

修改

直接修改

ds.Table["Student"].Rows[0][1] = "Alice" //通过索引值的方式修改
ds.Table["Student"].Rows[0]["Name"] = "Alice"  //通过字段名的方式修改

检索后修改

  • 使用find命令查出某行
  • 开始修改
DataRow dr = ds.Tables["Book"].Rows.Find(39001);
if(dr!=null)
{
dr.BeginEdit();
dr["Price"] = 88.88;
dr[StorageIn] = 88;
dr.EndEdit();
}

删除

方法1:Remove 和RemoveAt

DataRow dr = ds.Table["Student"].Rows.Find(txtSNO.Text.Trim());
if(dr !=nul){
    ds.Tables["Student"].Rows.Remove(dr);
}
return;
for (int i=0;i<ds.Tables["Student"].Rows.Count;i++)
{
    if ds.Tables["Student"].Rows [i]["SNO"].ToString()==txtSNO.Text.Trim())
    {
        ds.Tables ["Student"].Rows.RemoveAt(i);
        MessageBox.Show("删除成功!");
        break;
    }
}

方法2 :Delete

ds.Tables["Book"].Rows[0].Delete();//删除
ds.Tables["Book"].AcceptChanges();//提交
ds.Tables["Book"].RejectChanges()//回滚

两个方法的区别

Remove 和RemoveAt方法是直接删除

Delete方法是标记删除,实际还存在,可以使用RejectChanges方法进行回滚操作

注意 : 如果删除DataTable中的多行数据,应当采用倒序循环DataTable.Rows ,而且不能使用foreach进行循环删除,因为正序删除时索引会发生变化程序会引发异常

查找

SELECT方法

//使用DataRov数组接收返回值
Datow[]drArr ds.Tables["Student"].Select("Mobile Like '"txtQueryMobile.Text.Trim()+"%'");
//按照原表格式实例化一个DataTable
DataTable dte1 ds.Tables["Student"].Clone();
for (int i 0;i<drArr.Length;i++)
{//把结果插入到DataTable中
dt01.ImportRow(drArr[i]);
}
//绑定DataTable到DataGridview
dataGridview1.DataSource=dt01;

注意返回结果是一个数组,需要重新赋值后才可以绑定数据

RowFilter方法

//实例M化Dataview
Dataview dv = ds.Tables["Student"].Defaultview;
//把结果赋值给DataView
dv.RowFilter="SName Like '%"+txtQueryName.Text.Trim()+"%'";
//把结果绑定到DataGridView
dataGridview1.DataSource=dv;

返回的就是一个table,可以直接绑定数据’

其他操作

//复制表--表结构和数据
DataTable dtNew=new DataTable();
dtNew=ds.Tables["Student"].Copy();
//复制表--仅结构
DataTable dtNew01 = new DataTable();
dtNew01 = ds.Tables["Student"].clone();
//清空数据
dtNew.Clear();
//插入第一行数据
dtNew01.ImportRow(ds.Tables ["Student"].Rows [])
//排序
ds.Tables["Student"].Defaultview.Sort = "Age,Gender";
DataTable dt01 = ds.Tables["Student"].Defaultview.ToTable();

\