Reputation: 4623
I have a GirdView table in my application. I have a Delete link button and a checkbox in my first column. Below are snapshots:
I can manually delete each row by clicking Delete link button on each row.
However, I would want to enable the checkbox to delete multiple rows.
Below is my code for my Delete link button:
LinkButton lnk = (LinkButton)sender;
string stid = lnk.CommandArgument.ToString();
SqlConnection conn = new SqlConnection("Data Source=DATASOURCE");
string sql = string.Format("DELETE FROM [UserDB] where Employee like '%{0}%'",stid);
SqlCommand cmd = new SqlCommand(sql,conn);
conn.Open();
cmd.ExecuteNonQuery();
Below is my code for the current Delete Checked button:
bool atLeastOneRowDeleted = false;
foreach (GridViewRow row in GridView1.Rows)
{
// Access the CheckBox
CheckBox cb = (CheckBox)row.FindControl("UserSelection");
if (cb != null && cb.Checked)
{
atLeastOneRowDeleted = true;
// How do I get the value from my Employee column?
string userID = ???;
SqlConnection conn = new SqlConnection("Data Source=DATASOURCE");
string sql = string.Format("DELETE FROM [UserDB] where Employee like '%{0}%'",userID);
SqlCommand cmd = new SqlCommand(sql,conn);
conn.Open();
cmd.ExecuteNonQuery();
}
}
I would like to know how should I grep userID, which is Employee
key in the GridView, to INSERT
it into my SQL delete statement?
Upvotes: 1
Views: 3210
Reputation: 18192
This question has already been answered but here's an article which shows which entire flow using datbase, Gridview, Business Logic and DAL.
Final Preview looks something like this
You can find the entire source code here
Upvotes: 0
Reputation: 13028
Using 'row.Cells[3].Text' to fetch column values is a bad way. If he adds another column in between then the index would change. Use dataKeys instead to reference your column values.
Upvotes: 0
Reputation: 4659
well without seeing your code for the checkboxes, I would say set the value of the checkboxes to the UserID of the employee. Then on submit set the checked values to a list or array and then parse that list or array with your delete single method.
Upvotes: 1
Reputation: 3563
I think you want
bool atLeastOneRowDeleted = false;
foreach (GridViewRow row in GridView1.Rows)
{
// Access the CheckBox
CheckBox cb = (CheckBox)row.FindControl("UserSelection");
if (cb != null && cb.Checked)
{
atLeastOneRowDeleted = true;
//assuming you have the ID column after the controls
string CusId = (row.Cells[3].Text);
SqlConnection conn = new SqlConnection("Data Source=DATASOURCE");
string sql = string.Format("DELETE FROM [UserDB] where Employee like '%{0}%'",userID);
SqlCommand cmd = new SqlCommand(sql,conn);
conn.Open();
cmd.ExecuteNonQuery();
}
}
Upvotes: 1