我想删除gridview的行。为此,我使用了以下代码。在它工作之前,但现在在datatable中没有任何值。
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
DataTable dt = GridView1.DataSource as DataTable;
sQLcONN.Open();
MySqlCommand objcmd = new MySqlCommand("delete from shoppingcart where with_puja = '" + Convert.ToInt32(dt.Rows[e.RowIndex]["id"]).ToString() + "'", sQLcONN);
objcmd.ExecuteNonQuery();
Bindgrid();
sQLcONN.Close();
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
答案 0 :(得分:0)
检查行数,如果> 0删除
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
DataTable dt = GridView1.DataSource as DataTable;
if(dt.rows.count>0)
{
sQLcONN.Open();
MySqlCommand objcmd = new MySqlCommand("delete from shoppingcart where with_puja = '" + Convert.ToInt32(dt.Rows[e.RowIndex]["id"]).ToString() + "'", sQLcONN);
objcmd.ExecuteNonQuery();
Bindgrid();
sQLcONN.Close();
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
答案 1 :(得分:0)
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
string id = GridView1.DataKeys[e.RowIndex].Values["with_puja"].ToString();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "delete from shoppingcart where with_puja='" + id + "'";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write("<script>alert('An Error occurred.</script>");
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
Bindgrid();
}
}
并在aspx页面上添加DatekeyNames
<asp:GridView ID="GridView1" runat="server" ForeColor="#333333"
GridLines="None" DataKeyNames="with_puja">
</GridView>