Search code examples
c#asp.netprimary-keydatakey

DataKeyNames for different tables with different primary key names


I'm wondering if there is a way to use datakeynames to access the primary keys of different tables if those primary key names are different in those tables.

For example, I have a table called Table1 and Table2 where the primary keys are Table1ID and Table2ID respectively.

My ultimate goal is to combine the contents of both tables into 1 gridview, and to generate a hyperlink for both every row. So my c# looks something like this:

 protected void Page_Load(object sender, EventArgs e)
 {
    SqlCommand command = new SqlCommand("(SELECT Table1ID, Title FROM Table1" +
                                             "UNION ALL SELECT Table2ID, Title FROM Table2)", connection);

 GridView1.DataBind();
}

Then in my Gridview_Databound method, I go through and set the hyperlinks for each row individually. The problem is how do I access Table1ID and Table2ID? In my .aspx code, can I set that to be a BoundField because the DataField won't be consistent? I can't just do the following because then it neglects Table2ID right?

  <asp:BoundField DataField="Table1ID"/>

Maybe I need to use a templateField or something?


Solution

  • You can use templatefield as below code

     <asp:TemplateField HeaderText="Action">
     <ItemTemplate>
       <asp:LinkButton runat="server" ID="lnkEdit" ToolTip="Click to edit" CommandName="EditContent" CommandArgument='<%# Eval("Table1ID") %>' />    
     </ItemTemplate>
     </asp:TemplateField>
    

    Now on your OnRowCommand="GridView1_RowCommand" you will get the pk id of this tables.