从GridView中删除行时无法访问ID



我使用的是一个包含ID的Gridview。我想写一个Row_deleting事件,在该事件中我可以从.aspx页面访问ID,但我没有得到。

我该怎么做?

这是我的网格视图代码

<asp:LinkButton ID="lnkDelete" 
    runat="server" CssClass="gridLink" 
    CommandArgument='<%# Eval("Serial_key") %>' 
    CommandName="Delete">
    <b>Delete</b>
</asp:LinkButton>

首先在网格视图中设置AutoGenerateDeletebutton=true,然后使用此链接如何使用GridView自动生成删除按钮

protected void DeleteRowButton_Click(Object sender, GridViewDeleteEventArgs e)
{
var PN = GridView1.DataKeys[e.RowIndex].Values["Part_Number"];// this is how you get the right row to delete e.rowindex is used to do this
string PN = pn.ToString;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["XMLConnectionString"].ConnectionString);
// Create the command object
con.Open();
string str = "DELETE * FROM XML WHERE ([Part_Numbber] = " + PN + ")";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
Button1_Click(sender, e);
con.Close();
}

要从数据库中删除任何记录,您需要唯一或主键列。如果要删除使用列"Serial_key"的记录。然后将以下代码放入Delete。

<ItemTemplate> 
<asp:Label ID="lblSerial_key" runat="server" Text='<%# Eval("Serial_key") %>'></asp:Label>
<asp:Button ID="deleteButton" runat="server" CommandName="Delete" Text="Delete"  /></ItemTemplate>

现在您可以使用lblSerial_key删除一行

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string Serial_key = string.Empty;
        Label lblId = (Label)GridView1.Rows[e.RowIndex].Cells[0].FindControl("lblSerial_key");
        Serial_key = lblId.Text.ToString();
        string selectSQL = "delete from tablename where id='" + Serial_key + "'";
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        // Create the command object
        con.Open();
        SqlCommand cmd = new SqlCommand(selectSQL , con);
        cmd.ExecuteNonQuery();
        con.Close();
    }

最新更新