private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
int Index = 0;
if (MessageBox.Show("Are you sure?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
string delete = dataGridView1.Rows[Index].Cells[1].Value.ToString();
SqlCeCommand cmd = new SqlCeCommand("delete from Contact_List where Name='" + delete + "'", con);
con.Open();
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
MessageBox.Show("Record Deleted Successfully");
filldata();
}
else
{
MessageBox.Show("Record not Deleted....Please try again.");
}
}
}
con.Close();
为什么这段代码只会在我选择第二行时删除第一行?
请帮助!!
答案 0 :(得分:0)
您已在第一行指定了Index = 0
。因此,每次调用该方法时,它总是删除第一行,即索引0。
如果要删除所选行,则必须使用SelectedIndex
。请考虑以下示例代码:
string delete = dataGridView1.Rows[dataGridView1.SelectedIndex].Cells[1].Value.ToString();
答案 1 :(得分:0)
变量Index
已使用0
进行初始化,并且在执行期间不会更新该值,因此每次第一行都会被删除。所以你想要做的是,使用当前行索引更新变量Index
,如下所示:
Index= datagridview.CurrentCell.RowIndex;
string itemToDelete = dataGridView1.Rows[Index].Cells[1].Value.ToString();
// this will be the `Cells[1]` value at the selected index