初学C#和SQL,数据已经绑定到datagrid中,想通过按一个"添加"按钮后,就会在datagrid控件中的最后一行后自动添加一个新行,要求新行的“序号”(数据库中的主键,Varchar)是原datagrid中最后一条记录的“序号”加1,新行的“时间”是系统当前时间,新行的其他键值和原最后一条记录的值相同。
    卡在这里好久了,还望高人指点,不胜感激!!!

解决方案 »

  1.   

    步骤如下:
    1、取出DataGrid的DataSource并将其放到一个DataTable中。
    2、给DataTable加一个新行,并按照你的需求给新行每列赋值。
    完工!
      

  2.   

    实现代码如下:
    DataTable dt = (DataTable)dtGrid.DataSource;
    DataRow dr  = dt.NewRow();dr["ID"] = Convert.ToInt32(dt.Rows[dt.Rows.Count-1]["ID"])+1;
    dr["Date"] = DateTime.Now;
    dr["Other"] = dt.Rows[dt.Rows.Count-1]["Other"];
    dt.Rows.Add(dr);
      

  3.   

    给绑定到DG控件的数据源增加一列.然后刷新DG控件..
      

  4.   

    楼主,给你个详细的代码:
    SqlConnection Myconn = new SqlConnection("Data Source=(local);Integrated Security=SSPI;"+"Initial Catalog=sellmanager");
    Myconn.Open();
    SqlDataAdapter MyAdapter=new SqlDataAdapter("select * from sellerinfo ",Myconn);
    SqlCommandBuilder MyBuilder=new SqlCommandBuilder(MyAdapter);
    DataSet MyDataSet=new DataSet();
    MyAdapter.Fill(MyDataSet,"sellerinfo");
    DataRow MyRow=MyDataSet.Tables["sellerinfo"].NewRow();
    MyRow["sellId"]=this.txt1.Text;
    MyRow["psd"]=DataProdected.Encrypt(this.txt5.Text ,"licesoft");
    MyRow["name"]=this.txt2.Text;
    MyRow["sex"]=this.comboBox1.Text;
    MyRow["phone"]=this.txt3.Text;
    MyRow["cellphone"]=this.txt4.Text;
    MyDataSet.Tables["sellerinfo"].Rows.Add(MyRow);
    MyAdapter.Update(MyDataSet,"sellerinfo");
    MessageBox.Show("添加成功!","信息",MessageBoxButtons.OK,MessageBoxIcon.Information);
    Myconn.Close();
    this.dataGrid1.SetDataBinding(MyDataSet,"sellerinfo");
      

  5.   

    楼主要注意LionWangCity的方法还没有去更新资料库呦, zhangci226(三只熊熊) 已经给出了更新数据库德代码了。