Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Composite Key in DataKeyField of DataGrid 2

Status
Not open for further replies.

PankajVerma

Programmer
Sep 24, 2001
20
US
Hi,
I am populating a datagrid with the data from a table which has the primary key as the combination of 3 columns.Please let me know how to set that in DataKeyField of the DataGrid. Without setting it I am not able to identify the row I have selected.

Pankaj
 
There is couple of ways of doing this. First is to combine the three primary keys columns in one, set the DataKey property to this "made up" key and then extract them in the event handler. Or, set the first field as DataKey in the grid and bind the other two keys to hidden columns in the grid. The second way is probably easier(assumming that all three fields are integers):
Code:
html:
<asp:DataGrid ID=myGrid Runat=Server DataKeyField=&quot;keyOne&quot; AutoGenerateColumns=False>
 <asp:TemplateColumn Visible=False>
   <ItemTemplate>
    <asp:Label ID=&quot;keyTwoHolder&quot; Runat=Server Text='<%# DataBinder.Eval(Container.DataItem, &quot;keyTwo&quot;).ToString() %>' />
   </ItemTemplate>
 </asp:TemplateColumn>
 <asp:TemplateColumn Visible=False>
   <ItemTemplate>
    <asp:Label ID=&quot;keyThreeHolder&quot; Runat=Server Text='<%# DataBinder.Eval(Container.DataItem, &quot;keyThree&quot;).ToString() %>' />
   </ItemTemplate>
 </asp:TemplateColumn>
 .....
 .....
</asp:DataGrid>

//page code behind ItemCommand event handler:
private void myGrid_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
 //find first key
 int keyOne = Convert.ToInt32(myGrid.DataKeys[e.Item.ItemIndex]);
 //find second key
 Label lblKeyTwo = (Label)e.Item.FindControl(&quot;keyTwoHolder&quot;);
 int keyTwo = Convert.ToInt32(lblKeyTwo.Text.Trim());
 //find third key
 Label lblKeyThree = (Label)e.Item.FindControl(&quot;keyThreeHolder&quot;);
 int keyThree = Convert.ToInt32(lblKeyThree.Text.Trim());
}
Hope this helps.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top