reZach
reZach

Reputation: 9479

Which parameter do you use to retrieve column values in a GridView?

I need to make a delete statement for results that are displayed in my GridView. This delete statement must use some of the columns themselves as parameters in the delete statement

My gridview is this:

 <asp:GridView 
        ID="GridView1" 
        runat="server" 
        AllowPaging="True" 
        AutoGenerateColumns="False" 
        DataSourceID="SqlDataSource1"
        style="z-index: 1; left: 222px; top: 139px; position: absolute; height: 299px; width: 458px" DataKeyNames="Id">
        <Columns>
            <asp:CommandField ShowDeleteButton="True" />
            <asp:BoundField DataField="Column1" HeaderText="Column1" SortExpression="Column1" ReadOnly="True" Visible="False" />
            <asp:BoundField DataField="Id" HeaderText="Id" SortExpression="Id" ReadOnly="True" Visible="False" />
            <asp:BoundField DataField="department" HeaderText="department" SortExpression="department" />
            <asp:BoundField DataField="courseCode" HeaderText="courseCode" SortExpression="courseCode" />
            <asp:BoundField DataField="courseName" HeaderText="courseName" SortExpression="courseName" />
        </Columns>
    </asp:GridView>

I need to use "Column1" and "Id" from my SELECT query (That is stored within a stored procedure) for the DELETE query that is ran when the "Delete" button is hit on my Gridview. A problem that may be happening is my select statement uses one primary key, but my delete statement needs two primary keys (which are "Column1" and "Id"), so I do not know what to set DataKeyNames to.

Here is the SQLDataSource:

<asp:SqlDataSource 
        ID="SqlDataSource1" 
        runat="server" 
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
        SelectCommand="GetPreviouslyTakenCourses" 
        SelectCommandType="StoredProcedure"
        DeleteCommand="DELETE FROM UserHasCourse WHERE UserHasCourse.userId=@Column1 AND UserHasCourse.courseId=@Id"
        DeleteCommandType="Text">
        <SelectParameters>
            <asp:SessionParameter DefaultValue="1" Name="userId" SessionField="userId" Size="10" Type="Int32" />
        </SelectParameters>
        <DeleteParameters>
            <asp:Parameter Name="Column1" Type="Int32" />
            <asp:Parameter Name="Id" Type="Int32" />
        </DeleteParameters>
    </asp:SqlDataSource>

As of now nothing happens when I hit "Delete" on the GridView, so I can imagine the problem I am having is almost fixed. I can imagine there is a problem with <asp:Parameter but I don't know what.

Upvotes: 0

Views: 493

Answers (1)

reZach
reZach

Reputation: 9479

DataKeyNames should be set to

DataKeyNames="Column1,Id"

And this problem is fixed

Upvotes: 1

Related Questions