TeaDrinkingGeek
TeaDrinkingGeek

Reputation: 2023

How to delete in GridView

How to you link the id of the row in GridView to the deletecommand so to delete a row?

Here is my code:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
        AllowSorting="True" DataSourceID="SqlDataSource1" 
        AutoGenerateColumns="False">
    <Columns>
        <asp:CommandField ShowDeleteButton="True" />
        <asp:BoundField DataField="SDate" HeaderText="SDate" SortExpression="SDate" />
        <asp:BoundField DataField="STime" HeaderText="STime" SortExpression="STime" />
        <asp:BoundField DataField="SPrice" HeaderText="SPrice" 
                SortExpression="SPrice" />
        <asp:BoundField DataField="SDuration" HeaderText="SDuration" 
                SortExpression="SDuration" />
        <asp:BoundField DataField="SNoPlaces" HeaderText="SNoPlaces" 
                SortExpression="SNoPlaces" />
        <asp:BoundField DataField="ScheduleId" HeaderText="ScheduleId" 
                InsertVisible="False" ReadOnly="True" SortExpression="ScheduleId" />
    </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:ChinatowndbConnString %>" 
        DeleteCommand="DELETE FROM Schedule WHERE (ScheduleId = @ScheduleId)" 
        SelectCommand="SELECT SDate, STime, SPrice, SDuration, SNoPlaces, ScheduleId FROM Schedule">
    <DeleteParameters>
        <asp:Parameter Name="ScheduleId" />
    </DeleteParameters>
</asp:SqlDataSource>

I am using Visual Studio 2010.

Upvotes: 1

Views: 3641

Answers (2)

Vishal Suthar
Vishal Suthar

Reputation: 17194

Link your id in the Gridview property

DataKeyNames="your_id"

You can also define multiple ids as below:

DataKeyNames="your_id1, your_id2"

And you can access the value as below:

protected void GridView1_Deleting(object sender, ObjectDataSourceMethodEventArgs)  
{
    //e.Command.Parameters["your_id1"].Value;
}

Upvotes: 0

Kris van der Mast
Kris van der Mast

Reputation: 16623

You forgot to set the DataKeyNames property on the GridView control.

Change your GridView like:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
    AllowSorting="True" DataSourceID="SqlDataSource1" 
    AutoGenerateColumns="False"
    DataKeyNames="ScheduleId" >

For another example: SqlDataSource.DeleteCommand Property

Upvotes: 3

Related Questions