I am writing to seek help in regards deleting database record using checkbox gridview controls.
I am trying to delete the records from “ViewData” using checkbox and gridview but the 'if' condition keeps failing. Any further assistance as to where I may be going wrong would be very much appreciated. Thank you very much for your time and feedback.
//Method for Deleting Record
protected void DeleteRecord(int ID)
{
SqlConnection con = new SqlConnection(cs);
SqlCommand com = new SqlCommand("delete from tbl_Users where ID=@ID", con);
com.Parameters.AddWithValue("@ID", ID);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
protected void btnDeleteRecord_Click(object sender, EventArgs e)
{
foreach (GridViewRow grow in ViewDataGrid.Rows)
{
//Searching CheckBox("chkDel") in an individual row of Grid
CheckBox chkdel = (CheckBox)grow.FindControl("chkDel");
//If CheckBox is checked than delete the record with particular empid
if (chkdel.Checked)
{
int ID = Convert.ToInt32(grow.Cells[1].Text);
DeleteRecord(ID);
}
}
//Displaying the Data in GridView
showData();
}
Error: Input string was not in the correct format in: int ID = Convert.ToInt32(grow.Cells[1].Text);
In following line
int ID = Convert.ToInt32(grow.Cells[1].Text);
The actual value of grow.Cells[1].Text might be containing alphabetic characters or the whitespace so you are getting this error.
Convert.ToInt32(stringVal) actually converts the specified string representation of a number to an equivalent 32-bit signed integer but the parameter should be a string that contains the number only.
With your select query in the line string SelectQuery = "SELECT FROM tbl_Users WHERE ID=" + ID; you are missing the values you are selecting.
You will either have to select the specific columns required are input * to select all columns. eg string SelectQuery = "SELECT * FROM tbl_Users WHERE ID=" + ID; or string SelectQuery = "SELECT column1,column3 FROM tbl_Users WHERE ID=" + ID;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.