使用gridview ASP.NET删除记录

时间:2016-05-15 12:52:32

标签: c# asp.net gridview

我写信是为了寻求有关使用复选框gridview控件删除数据库记录的帮助。

我正在尝试使用复选框和gridview从“ViewData”中删除记录,但“if”条件仍然失败。对于我可能出错的地方的任何进一步帮助将非常感谢。非常感谢您的时间和反馈。

//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();
}

错误:输入字符串的格式不正确: int ID = Convert.ToInt32(grow.Cells [1] .Text);

2 个答案:

答案 0 :(得分:0)

以下一行

int ID = Convert.ToInt32(grow.Cells [1] .Text);

grow.Cells [1] .Text的实际值可能包含字母字符或空格,因此您收到此错误。

Convert.ToInt32(stringVal)实际上将数字的指定字符串表示形式转换为等效的32位有符号整数,但参数应该是仅包含数字的字符串。

答案 1 :(得分:0)

使用行中的选择查询 string SelectQuery =" SELECT FROM tbl_Users WHERE ID =" + ID; 你错过了你选择的值。

您必须选择所需的特定列,输入*才能选择所有列。 例如string SelectQuery =" SELECT * FROM tbl_Users WHERE ID =" + ID; 要么 string SelectQuery =" SELECT column1,column3 FROM tbl_Users WHERE ID =" + ID;

相关问题