datagridview使用适配器删除行

时间:2016-08-28 14:44:05

标签: c# .net winforms datagridview

使用arapter.Update(Dataset)创建/更新/删除我的应用程序。一切正常,但我正在寻找如何在执行update之前添加问题对话框

当我点击删除按钮时,我想看到如下问题的对话框:

 DialogResult delete = MessageBox.Show("are you sure you want to delete this ?", "Delete Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

if (delete == DialogResult.OK)
  {
      MessageBox.Show("Deleted");
  }

这段代码我想在下面的代码中输入但是不确定如何确定是否触发了删除命令!

  private void saveToolStripButton_Click(object sender, EventArgs e)
    {
        try
        {
            this.Validate();
            this.bs.EndEdit();

            cmb = new SqlCommandBuilder(dataAdapter);

            dataAdapter.UpdateCommand = cmb.GetUpdateCommand();           
            dataAdapter.Update(this.ds, "grupe");

            MessageBox.Show("Update successful");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

1 个答案:

答案 0 :(得分:0)

试试这个,

编写一个以DataRowState作为参数的方法;

 public DialogResult Dialog(DataRowState state)
        {

            if (state == DataRowState.Modified)
            {

                DialogResult update = MessageBox.Show("are you sure you want to update this ?", "Update Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

                return update;
            }
            if (state == DataRowState.Deleted)
            {

                DialogResult delete = MessageBox.Show("are you sure you want to delete this ?", "Delete Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

                return delete;
            }
            return DialogResult.None;

        }

按下按钮;

 private void button1_Click(object sender, EventArgs e)
        {

            DataTable dt = dataTbl.GetChanges(); //it will return the changes
            foreach (DataRow item in dt.Rows)
            {
                if (Dialog(item.RowState) == DialogResult.OK) 
                {
                    SqlCommandBuilder cmb = new SqlCommandBuilder(adp);
                    adp.UpdateCommand = cmb.GetUpdateCommand();
                    adp.Update(this.dataTbl);

                }
            }
        }

DataTable始终为null。填充适配器后使用datatable.AcceptChanges()

希望有所帮助,