How can I use CategoryID or CategoryName as a data key to retrieve Categories data respectively in a GridView control? RRS feed

  • Question

  • User-830563764 posted

    In an ASP.net Walkthrough webpage, MasterDetail.aspx, the Categories table of the Morthwind database was
    displayed in a GridView.  Clicking the Details column will open a DetailsView displaying Prodcut data for the
    selected CategoryID.

    I added a CategoryName to the Product table and a new Details column to the GridView.  The I added another
    DetailsView, trying to display the Product data for the selected CategoryName.  The codes worked fine, but
    clicking the Details button from either column showed the data from the CategoyID only.

    Reviewing the Source codes, I found there is a DataKeyNames, i.e. CategoryID.  I deleted the CategoryID, hoping
    either the <asp:ControlParameter Name=CategoryID or CategoryName can work for the DetailsView controls.

    However, error popped up, indicating missing DataKeyName for the GridView.  How can I code the GridView,
    so that I can use either CatergoryID ro CategoryName to retrieve the GridView data? 

    Friday, May 13, 2016 7:15 PM


  • User-271186128 posted

    Hi wonjartran,

    From my point of view, I suggest you could use LinkButton to display the CategoryID and the CategoryName, and use the CommandName or CommandArgument to bind the CategoryID or CategoryName.

    Then, when you click relevant LinkButton, in the button click event, you can use the following code to get the CategoryID or CategoryName, then, redirect to the details page, and according to the parameter to query database and show details.

            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1">
                    <asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" InsertVisible="False" ReadOnly="True" SortExpression="EmployeeID" />
                    <asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
                    <asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
                    <asp:TemplateField >
                            <asp:LinkButton ID="lbnViewDetails" CommandName='<%# Eval("EmployeeID") %>' OnClick="lbnViewDetails_Click" runat="server">ViewDetails</asp:LinkButton>

    Code behind:

            protected void lbnViewDetails_Click(object sender, EventArgs e)
                LinkButton lbn = (LinkButton)sender;
                Response.Redirect(string.Format("DetailsPage.aspx?ID={0}", lbn.CommandName));

    Best regards,

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, May 14, 2016 10:23 AM