学习Datatable增删改

1.创建表

DataSet ds=new DataSet();

DataTable dt=new DataTable("表名");

ds.Add(dt);

dt.Columns.Add("列名1",typeof(数据类型名1));

dt.Columns.Add("列名2",typeof(数据类型名2));

dt.Columns.Add("列名3",typeof(数据类型名3));

2.往表中添加数据

DataRow dr=dt.NewRow();

dr[0]="列值1";

dr[1]="列值2";

dr[2]="列值3";

dt.Rows.Add(dr);

Object[] ob=new object [3];//定义一个对象数组
for (int i = 0; i < ob.Length; i++)
{
   stu[i] = 1;
}

dt.Rows.Add(ob);//把数组的数据也添加到表中

3.修改数据

           dataGridView1.DataSource = ds.Tables[0];
            DataTable dt = ds.Tables["表名"];
            int i = dataGridView1.CurrentRow.Index;
            DataRow dr = dt.Rows[i];
            dr.BeginEdit();
            dr[0] = this.textBox1.Text;
            dr[1] = this.textBox2.Text;
            dr[2] = this.textBox3.Text;
            dr.EndEdit();

4.删除数据

            dataGridView1.DataSource = ds.Tables[0];
            DataTable dt = ds.Tables["Student"];
            int i = dataGridView1.CurrentRow.Index;//获取当前行
            DataRow dr = dt.Rows[i];
            //dt.Rows.Remove(dr);//第二种删除操作用法
            dr.Delete();

 

posted @ 2008-10-19 01:49  ly712  阅读(3893)  评论(0编辑  收藏  举报