通过CommandBuilder对DataSet数据进行添加、修改、删除

通过CommandBuilder对DataSet数据进行添加、修改、删除

        private void UpdateDataTable()
        {
            SqlDataAdapter da = new SqlDataAdapter();
            SqlConnection conn = new SqlConnection("User ID=sa;Password=sa;DataBase=mydatabase;Data Source=localhost");
            DataSet ds = new DataSet();
            //通过select语句新建Command对象,通过select可以了解表的结构及属性
            //所选的数据库表必须要设置主键
            SqlCommand sqlcommand = new SqlCommand("select * from table1",conn);
            da.SelectCommand = sqlcommand;
           
            da.Fill(ds);

            //修改数据
            ds.Tables[0].Rows[0][1] = "update data item";

            //添加数据
            DataRow datarow = ds.Tables[0].NewRow();
            datarow[0] = "add new item";
            ds.Tables[0].Rows.Add(datarow);
           
            //删除数据
            ds.Tables[0].Rows[1].Delete();

            //新建sqlcommandbuilder
            SqlCommandBuilder sqlcommandbuilder = new SqlCommandBuilder(da);
            da.Update(ds);
           
        }
posted @ 2006-01-11 12:37  torome  阅读(389)  评论(0编辑  收藏  举报