none
DataGridView控件绑定List<T>泛型数据源后,如何能像Excel那样,实现数量的批量修改与保存? RRS feed

  • 问题

  • C# DataGridView控件绑定List<T>泛型数据源,对数据的修改与保存操作我一直是双击某记录,弹出一个窗口,修改完成后,将该记录写回数据库,然后重新刷新DataGridView显示的数据。这对于有批量修改需求的情况而言,操作起来显然太过繁琐,请问要怎么做才能像Excel那样,实现数量的批量修改与保存?

    2011年3月15日 2:58

答案

  • 试试这段代码

    public partial class frmMain : Form
      {
        string strCon = "Server=(local); Database=Test; uid=sa; password=abc";
        SqlConnection con;
        SqlCommand com;
        DataSet ds;
        SqlDataAdapter da;
        int SelectedIndex;
        bool bMode;
        public frmMain()
        {
          InitializeComponent();
          SelectedIndex = -1;
          bMode = true;
        }
        private void frmMain_Load(object sender, EventArgs e)
        {
          RefreshData();
        }
        private void RefreshData()
        {
          con = new SqlConnection(strCon);
          com = new SqlCommand("Select * from mstTest", con);
          da = new SqlDataAdapter(com);
          try
          {
            con.Open();
            ds = new DataSet();
            da.Fill(ds, "mstTest");
            dgv.DataSource = ds.Tables["mstTest"];
          }
          catch (Exception ex)
          {
            MessageBox.Show(ex.ToString());
          }
          finally
          {
            con.Close();
          }
        }
        private void bttnAdd_Click(object sender, EventArgs e)
        {
          DataRow row;
          if (bMode == true)
            row = ds.Tables["mstTest"].NewRow();
          else
            row = ds.Tables["mstTest"].Rows[SelectedIndex];
            
          row[0] = txtEmpNo.Text;
          row[1] = txtName.Text;
          row[2] = DateTime.Parse(meDOB.Text).ToString("d");
          row[3] = DateTime.Parse(meDOJ.Text).ToString("d");
          if (rdoMale.Checked == true)
            row[4] = "Male";
          else
            row[4] = "Female";
          row[5] = decimal.Parse(txtSalary.Text);
          if (bMode == true)
            ds.Tables["mstTest"].Rows.Add(row);
          else
            bMode = true;
            txtEmpNo.ReadOnly = false;
          txtEmpNo.Text = "";
          txtName.Text = "";
          txtSalary.Text = "";
          meDOB.Text = "";
          meDOJ.Text = "";
          rdoMale.Checked = false;
          rdoFemale.Checked = false;
          bttnAdd.Text = "Add";
          txtEmpNo.Focus();
        }
        private void bttnSave_Click(object sender, EventArgs e)
        {
          con.Open();
          SqlCommand insertCommand = new SqlCommand("Insert into mstTest(EmpNo, EmpName, DOB, DOJ, Sex, Salary) Values(@EmpNo, @EmpName, @DOB, @DOJ, @Sex, @Salary)",con);
          SqlCommand updateCommand=new SqlCommand("Update mstTest set EmpName=@EmpName, DOB=@DOB, DOJ=@DOJ, Sex=@Sex, Salary=@Salary where EmpNo=@EmpNo", con);
          SqlParameterCollection iParam;
          iParam = insertCommand.Parameters;
          iParam.Add("@EmpNo", SqlDbType.VarChar, 50, "EmpNo");
          iParam.Add("@EmpName", SqlDbType.VarChar, 100, "EmpName");
          iParam.Add("@DOB", SqlDbType.DateTime, 0, "DOB");
          iParam.Add("@DOJ", SqlDbType.DateTime, 0, "DOJ");
          iParam.Add("@Sex", SqlDbType.VarChar, 10, "Sex");
          iParam.Add("@Salary", SqlDbType.Money, 0, "Salary");
          SqlParameterCollection uParam;
          uParam = updateCommand.Parameters;
          uParam.Add("@EmpNo", SqlDbType.VarChar, 50, "EmpNo");
          uParam.Add("@EmpName", SqlDbType.VarChar, 100, "EmpName");
          uParam.Add("@DOB", SqlDbType.DateTime, 0, "DOB");
          uParam.Add("@DOJ", SqlDbType.DateTime, 0, "DOJ");
          uParam.Add("@Sex", SqlDbType.VarChar, 10, "Sex");
          uParam.Add("@Salary", SqlDbType.Money, 0, "Salary");
          da.InsertCommand = insertCommand;
          da.UpdateCommand = updateCommand;
          da.Update(ds, "mstTest");
          con.Close();
          MessageBox.Show("Successfully Saved", "Saved", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        private void dgv_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
          if (e.RowIndex >= 0)
            SelectedIndex = e.RowIndex;
          txtEmpNo.Text = dgv.Rows[SelectedIndex].Cells[0].Value.ToString();
          txtEmpNo.ReadOnly = true;
          txtName.Text = dgv.Rows[SelectedIndex].Cells[1].Value.ToString();
          meDOB.Text = DateTime.Parse(dgv.Rows[SelectedIndex].Cells[2].Value.ToString()).ToString("d");
          meDOJ.Text = DateTime.Parse(dgv.Rows[SelectedIndex].Cells[3].Value.ToString()).ToString("d");
          if (dgv.Rows[SelectedIndex].Cells[4].Value.ToString() == "Male")
            rdoMale.Checked = true;
          else
            rdoFemale.Checked = true;
          txtSalary.Text = dgv.Rows[SelectedIndex].Cells[5].Value.ToString();
          bMode = false;
          bttnAdd.Text = "Update";
        }
      }
    

    效果:

     


    Cookie Luo[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    2011年3月16日 9:06

全部回复

  • 你可以直接在DataGridView上面修改,然后保存到数据库,

    1.可以遍历每行进行保存

    2.也可以使用SqlCommandBuilder

    参照:http://www.cnblogs.com/herbert/archive/2010/08/31/1813824.html


    http://blog.csdn.net/zx13525079024
    2011年3月15日 5:19
  • LIST<T>转化为DATATABLE 并且在每一行上加DataRowState 供底层决定调用增,删,改   ,然后用COMMANDBUILD生成COMMAND,最后用ADAPTER的UPDATE方法更新
    yulai
    2011年3月15日 6:44
  • 试试这段代码

    public partial class frmMain : Form
      {
        string strCon = "Server=(local); Database=Test; uid=sa; password=abc";
        SqlConnection con;
        SqlCommand com;
        DataSet ds;
        SqlDataAdapter da;
        int SelectedIndex;
        bool bMode;
        public frmMain()
        {
          InitializeComponent();
          SelectedIndex = -1;
          bMode = true;
        }
        private void frmMain_Load(object sender, EventArgs e)
        {
          RefreshData();
        }
        private void RefreshData()
        {
          con = new SqlConnection(strCon);
          com = new SqlCommand("Select * from mstTest", con);
          da = new SqlDataAdapter(com);
          try
          {
            con.Open();
            ds = new DataSet();
            da.Fill(ds, "mstTest");
            dgv.DataSource = ds.Tables["mstTest"];
          }
          catch (Exception ex)
          {
            MessageBox.Show(ex.ToString());
          }
          finally
          {
            con.Close();
          }
        }
        private void bttnAdd_Click(object sender, EventArgs e)
        {
          DataRow row;
          if (bMode == true)
            row = ds.Tables["mstTest"].NewRow();
          else
            row = ds.Tables["mstTest"].Rows[SelectedIndex];
            
          row[0] = txtEmpNo.Text;
          row[1] = txtName.Text;
          row[2] = DateTime.Parse(meDOB.Text).ToString("d");
          row[3] = DateTime.Parse(meDOJ.Text).ToString("d");
          if (rdoMale.Checked == true)
            row[4] = "Male";
          else
            row[4] = "Female";
          row[5] = decimal.Parse(txtSalary.Text);
          if (bMode == true)
            ds.Tables["mstTest"].Rows.Add(row);
          else
            bMode = true;
            txtEmpNo.ReadOnly = false;
          txtEmpNo.Text = "";
          txtName.Text = "";
          txtSalary.Text = "";
          meDOB.Text = "";
          meDOJ.Text = "";
          rdoMale.Checked = false;
          rdoFemale.Checked = false;
          bttnAdd.Text = "Add";
          txtEmpNo.Focus();
        }
        private void bttnSave_Click(object sender, EventArgs e)
        {
          con.Open();
          SqlCommand insertCommand = new SqlCommand("Insert into mstTest(EmpNo, EmpName, DOB, DOJ, Sex, Salary) Values(@EmpNo, @EmpName, @DOB, @DOJ, @Sex, @Salary)",con);
          SqlCommand updateCommand=new SqlCommand("Update mstTest set EmpName=@EmpName, DOB=@DOB, DOJ=@DOJ, Sex=@Sex, Salary=@Salary where EmpNo=@EmpNo", con);
          SqlParameterCollection iParam;
          iParam = insertCommand.Parameters;
          iParam.Add("@EmpNo", SqlDbType.VarChar, 50, "EmpNo");
          iParam.Add("@EmpName", SqlDbType.VarChar, 100, "EmpName");
          iParam.Add("@DOB", SqlDbType.DateTime, 0, "DOB");
          iParam.Add("@DOJ", SqlDbType.DateTime, 0, "DOJ");
          iParam.Add("@Sex", SqlDbType.VarChar, 10, "Sex");
          iParam.Add("@Salary", SqlDbType.Money, 0, "Salary");
          SqlParameterCollection uParam;
          uParam = updateCommand.Parameters;
          uParam.Add("@EmpNo", SqlDbType.VarChar, 50, "EmpNo");
          uParam.Add("@EmpName", SqlDbType.VarChar, 100, "EmpName");
          uParam.Add("@DOB", SqlDbType.DateTime, 0, "DOB");
          uParam.Add("@DOJ", SqlDbType.DateTime, 0, "DOJ");
          uParam.Add("@Sex", SqlDbType.VarChar, 10, "Sex");
          uParam.Add("@Salary", SqlDbType.Money, 0, "Salary");
          da.InsertCommand = insertCommand;
          da.UpdateCommand = updateCommand;
          da.Update(ds, "mstTest");
          con.Close();
          MessageBox.Show("Successfully Saved", "Saved", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        private void dgv_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
          if (e.RowIndex >= 0)
            SelectedIndex = e.RowIndex;
          txtEmpNo.Text = dgv.Rows[SelectedIndex].Cells[0].Value.ToString();
          txtEmpNo.ReadOnly = true;
          txtName.Text = dgv.Rows[SelectedIndex].Cells[1].Value.ToString();
          meDOB.Text = DateTime.Parse(dgv.Rows[SelectedIndex].Cells[2].Value.ToString()).ToString("d");
          meDOJ.Text = DateTime.Parse(dgv.Rows[SelectedIndex].Cells[3].Value.ToString()).ToString("d");
          if (dgv.Rows[SelectedIndex].Cells[4].Value.ToString() == "Male")
            rdoMale.Checked = true;
          else
            rdoFemale.Checked = true;
          txtSalary.Text = dgv.Rows[SelectedIndex].Cells[5].Value.ToString();
          bMode = false;
          bttnAdd.Text = "Update";
        }
      }
    

    效果:

     


    Cookie Luo[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    2011年3月16日 9:06
  • 你好!

    建议你使用 DataSet、ef 生成的实体类集合做为数据源,这两个对象都自带有数据版本功能。比如 DataSet、DataTable 都可以都通 GetChanges 来获取需要更新的数据,ef 生成的实体类则是使用 ObjectChangeTracker 属性,这样就能方便的进行数据更新了。否则你可能需要如上面所述去遍历整个数据源,或者自己维护绑定对象的数据版本。


    知识改变命运,奋斗成就人生!
    2011年3月16日 13:41
    版主
  • 我忘说了,我用的是VS2005版本,肖小勇版主说的DataSet和ef是不是得VS2008以上的版本才支持啊?

    2011年3月23日 3:23