DataKeyNames for different tables with different primary key names

378 Views Asked by At

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?

2

There are 2 best solutions below

3
On BEST ANSWER

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.

1
On

In GridView control you can have a TemplateField containing Hyperlink (see the link to my article for details of this solution).

Also, it might be less labor-intensive if you use SqlDataSource assigning your select statement to its property and passing it to GridView.DataSource property. It will take just several lines of code and do the job for you. Regards, AB