我的表单上有一个单选按钮,一个gridview和一个按钮。这是我的datagridview selection_changed代码示例:
datagridview selection_changed
private void DataGridView1_SelectionChanged(object sender, EventArgs e) { if (rdb_Delete.Checked) { lbl_deleteMsg.Text = DataGridView1.SelectedRows.Count.ToString() + " rows selected."; } }
我想从数据库中删除选定的行,并在用户按下删除按钮时刷新datagridview。我的数据库中有一个Id列,但没有在datagridview上向用户显示。
因此,通过sql查询如何从数据库中删除所选行?这是我的删除按钮单击的代码,但似乎不起作用(由于选择更改了事件):
private void btn_Delete_Click(object sender, EventArgs e) { if (rdb_Delete.Checked) { int count = DataGridView1.SelectedRows.Count; int length = DataGridView1.RowCount; if (!count.Equals(0)) { if (confirm()) { for (int i = 0; i < length; i++) { if (DataGridView1.Rows[i].Selected) { //DataGridView1.SelectedRows[i].Selected = false; DataGridView1.Rows.RemoveAt(i); i--; } } } } } }
编辑:我也发现一个小的答案也许在这种情况下可以帮助某人。DataGridView的any列可以是 visible = false, 因此可以通过以下代码进行访问:
int rowID = int.Parse(DataGridView1[0, selectedIndex].Value.ToString());
试试这个:
private void btn_Delete_Click(object sender, EventArgs e) { if (rdb_Delete.Checked) { foreach (DataGridViewRow row in DataGridView1.SelectedRows) { //delete record and then remove from grid. // you can use your own query but not necessary to use rowid int selectedIndex = row.Index; // gets the RowID from the first column in the grid int rowID = int.Parse(DataGridView1[0, selectedIndex].Value.ToString()); string sql = "DELETE FROM Table1 WHERE RowID = @RowID"; // your code for deleting it from the database // then your code for refreshing the DataGridView DataGridView1.Rows.Remove(row); } } }