Question

I have Datalist with a LinkButton and a Label. I need to get the primary key value of the record for a particular record when I click on that data record. How to achieve that ?

<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="DataList1_SelectedIndexChanged" RepeatColumns="1" ShowFooter="False" ShowHeader="False" Width="587px" style="margin-right: 25px; margin-bottom: 116px">
    <ItemTemplate>
        &nbsp;<table style="width:100%;">
            <tr>
                <td>
                    <asp:LinkButton ID="LinkButton1" runat="server" Font-Bold="True" Font-Names="Tahoma" Font-Size="Medium" Font-Strikeout="False" ForeColor="Black" OnClick="LinkButton1_Click" Text='<%# Eval("title") %>'></asp:LinkButton>
                </td>
                <td>
                &nbsp;</td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="contentLabel" runat="server" Font-Names="Tahoma" Text='<%# Eval("content") %>' />
                </td>
                <td>

                    <br />

                </td>
            </tr>
        </table>
    </ItemTemplate>
</asp:DataList>
Was it helpful?

Solution

You need to return the primary key in your query. then assign the primary key to a column. you can then access this column and its value from code behind etc

eg:

                            <td>
                                <asp:Label ID="id" runat="server" Font-Names="Tahoma" Text='<%# Eval("id") %>' />
                            </td>

OTHER TIPS

You should include the DataKeyNames in your definition of the DataList.

<asp:DataList ID="DataList1" runat="server" DataKeyNames="ID" ... />

Then in the codebehind you can retrieve it:

protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{

    if (e.CommandName == "Edit")
    {

       string strId = DataList1.DataKeys[e.Item.ItemIndex].ToString();

    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top