要求点击按钮就能删除鼠标选定的行 连接了access数据库 代码如下 后头的怎么写?有人说用行ID删。 但是用行ID是删除指定那自动增长的 啊。 不懂原理。。 求代码 private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (dataGridView1.CurrentRow == null || dataGridView1.CurrentRow.IsNewRow)
{
MessageBox.Show("未选中行", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
} if (dataGridView1.CurrentRow.Index < 0)
{
MessageBox.Show("未选中行", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
} int productid = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value);
{
if (dataGridView1.CurrentRow == null || dataGridView1.CurrentRow.IsNewRow)
{
MessageBox.Show("未选中行", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
} if (dataGridView1.CurrentRow.Index < 0)
{
MessageBox.Show("未选中行", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
} int productid = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value);
{
InitializeComponent();
dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
{
Name = "id",
DataPropertyName = "productid", // 把productid换成你的数据表中主键的名称
Visible = false
}); }在ToolStripMenuItem的Click事件中就可以通过隐藏列的名称(id)来取到主键: ... ...
int productid = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["id"].Value);
你有主键的话直接获取到该行的主键啊,之后根据主键到数据库中执行删除语句不就行了吗
sql:delete from table where PRIMARYKEYName = '" + productid + "';//(你取到的值)
即可,你肯定有一个sqlhelper类啊
int keyid = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["主键名"].Value); SqlCommand cmd = new SqlCommand(string.Format("DELETE FROM TABLE WHERE KEYID={0}",keyid.ToString()), conn);
cmd.ExecuteNonQuery();
int keyid = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["主键名"].Value);SqlCommand cmd = new SqlCommand(string.Format("DELETE FROM TABLE1 WHERE KEYID={0}",keyid.ToString()), conn);
cmd.ExecuteNonQuery(); //删除这条记录//下面代码重新获取数据
DataTable table=new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("select * from TABLE1", connection);
adapter.Fill(table);dataGridView1.Columns.Clear();
dataGridView1.DataSouce=null;
dataGridView1.DataSouce=table;