1

I am trying to learn C#.net and now I want delete whith gridview this is my code

<asp:GridView OnRowDeleted="catGrid_RowDeleted" ID="catGrid" runat="server" AutoGenerateColumns="False" DataSourceID="gridSqlCat" CssClass="gridStyle">
                    <Columns>
                        <asp:BoundField DataField="dor_category" HeaderText="دسته بندی ها" SortExpression="dor_category" />
                        <asp:ButtonField  Text="حذف" />
                    </Columns>
                </asp:GridView>

and this cs code

protected void catGrid_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {

    }

so what should I do?

ruakh
  • 175,680
  • 26
  • 273
  • 307

1 Answers1

1

This sample is easy :

<asp:GridView ID="GridView1"runat="server" AutoGenerateColumns="false">
<Columns>
    <asp:BoundField DataField="CustomerId" HeaderText="Id" HeaderStyle-Width="30"/>
    <asp:BoundField DataField="Name" HeaderText="Name" HeaderStyle-Width="150"/>
    <asp:BoundField DataField="Country" HeaderText="Country" HeaderStyle-Width="150"/>
    <asp:TemplateField HeaderStyle-Width="50">
        <ItemTemplate>
            <asp:HiddenField ID="hfCustomerId" runat="server" Value='<%# Eval("CustomerId") %>'/>
            <asp:LinkButton ID="lnkDelete" Text="Delete" runat="server"/>
        </ItemTemplate>
    </asp:TemplateField>
</Columns>
</asp:GridView>

And cs :

[WebMethod]
public static bool DeleteCustomer(int customerId)
{
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlCommand cmd = new SqlCommand("DELETE FROM Customers WHERE CustomerId = @CustomerId"))
        {
            cmd.Connection = con;
            cmd.Parameters.AddWithValue("@CustomerId", customerId);
            con.Open();
            int rowsAffected = cmd.ExecuteNonQuery();
            con.Close();
            return rowsAffected > 0;
        }
    }
}