Reputation: 525
I have a radiobutton, a gridview and a button on my form. Here is my datagridview selection_changed
code sample:
private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (rdb_Delete.Checked)
{
lbl_deleteMsg.Text = DataGridView1.SelectedRows.Count.ToString()
+ " rows selected.";
}
}
I want to delete selected rows from database and refresh the datagridview when user pushes the delete button. I have an Id column in my database but I don't show it to the user on datagridview.
So by sql query how can I delete the selected row from my database? Here is my delete button clicked code but it doesn't seems to work (because of selection changed event):
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--;
}
}
}
}
}
}
Edit : I also find a small answer maybe helps someone in such a case. DataGridView's any column can be visible = false so it'll be accessible by code such as :
int rowID = int.Parse(DataGridView1[0, selectedIndex].Value.ToString());
Upvotes: 2
Views: 12086
Reputation: 18260
Try this:
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);
}
}
}
Upvotes: 3
Reputation: 11
private void button60_Click(object sender, EventArgs e) {
foreach (DataGridViewRow row in dataGridView7.SelectedRows)
{
dd = row.Cells["date"].Value.ToString();
ms = row.Cells["month"].Value.ToString();
day = row.Cells["day"].Value.ToString();
string txt = row.Cells["descrip"].Value.ToString();
con.Open();
SqlCommand cmd = new SqlCommand("delete from holidays where date like '" + dd + "%' and descrip like '"+ txt +"'", con);
SqlCommand cmd1 = new SqlCommand("delete from stholidays where holiday like '" + dd + "%' and holidescrip like '" + txt + "'", con);
cmd.ExecuteNonQuery();
cmd1.ExecuteNonQuery();
con.Close();
foreach (DataGridViewCell oneCell in dataGridView7.SelectedCells)
{
if (oneCell.Selected)
dataGridView7.Rows.RemoveAt(oneCell.RowIndex);
}
}
Upvotes: 0
Reputation: 13743
1.) You must use two-way binding. 2.) You must affirm the changes in order for them to be non-temporary.
Upvotes: 0