0

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?

Kevin
  • 3,209
  • 9
  • 39
  • 53

2 Answers2

1

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.

Mayur Desai
  • 683
  • 5
  • 13
  • I see that it is only doing Eva("Table1ID"). How would this get the pk of Table 2 then? – Kevin May 08 '13 at 21:44
  • change your query as below SELECT Table1ID, Title FROM Table1 UNION ALL SELECT Table2ID AS Table1ID, Title FROM Table2 – Mayur Desai May 09 '13 at 08:32
  • Awesome! I didn't use the templatefield but knowing that I could do the SELECT Table2ID AS Table1ID really helped! – Kevin May 14 '13 at 22:15
0

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

Alexander Bell
  • 7,842
  • 3
  • 26
  • 42
  • Hmm not sure exactly how to use the GridView.DataSource in this case. Also, I should add that I do paging on this gridview so I put everything into a DataTable then I do DataBind() – Kevin May 08 '13 at 21:45