日期:2014-05-18  浏览次数:21096 次

winfrom datagridview 删除选中的一行,现功能能用,想在删除的时候弹出确认按钮。
代码:
  private void btDel_Click(object sender, EventArgs e)
  {
  try
  {
  string connString = "Server=10.10.0.5;Database=xianggelia;User Id=sa;Password=12345678;";
  string sql = "delete from EquManager where 1=1";
  if (dataGridView1.CurrentRow.Selected)
  {
  sql = sql + "and Id=" + Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value.ToString());
  }
  int n = 0;
  SqlConnection conn = new SqlConnection(connString);
  SqlCommand cmd = new SqlCommand(sql, conn);
  conn.Open();
  n = cmd.ExecuteNonQuery();
  conn.Close();

  if (n < 0)
  {
  label1.Text = "删除成功";
  }

  else
  {
  label1.Text = "删除失败";
  }

  }
  catch (Exception ex)
  {
  MessageBox.Show("开啥子玩笑,删啥呢!", "提示");
  return;
  throw ex;
  }
  Refresh();
  shuliang.Text = "当前数量为:" + dataGridView1.Rows.Count.ToString();
  }

------解决方案--------------------
C# code

DialogResult dlResult = MessageBox.Show(this, "要删除这些记录吗?", "请确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dlResult == DialogResult.Yes)
                {
                    try
  {
  string connString = "Server=10.10.0.5;Database=xianggelia;User Id=sa;Password=12345678;";
  string sql = "delete from EquManager where 1=1";
  if (dataGridView1.CurrentRow.Selected)
  {
  sql = sql + "and Id=" + Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value.ToString());
  }
  int n = 0;
  SqlConnection conn = new SqlConnection(connString);
  SqlCommand cmd = new SqlCommand(sql, conn);
  conn.Open();
  n = cmd.ExecuteNonQuery();
  conn.Close();

  if (n < 0)
  {
  label1.Text = "删除成功";
  }

  else
  {
  label1.Text = "删除失败";
  }

  }
  catch (Exception ex)
  {
  MessageBox.Show("开啥子玩笑,删啥呢!", "提示");
  return;
  throw ex;
  }
  Refresh();
  shuliang.Text = "当前数量为:" + dataGridView1.Rows.Count.ToString();
                }