Tuesday, February 24, 2009

Run time primary keys for Datagrids

I believe a common problem we have faced in many of our screens is not having a primary key for the items in the datagrid.

It sometimes becomes very difficult to differentiate between rows of the grids, especially in javascript and we have to use field combinations. Sometimes even that won’t work (if all fields are equal in two rows).

Here’s an easy work around.
What this does is generate an integral key for every row. You can use either the property that just-returns the key or increments-and-returns the key depending on whether you’re on the same row or moving to the next row.

<asp:TemplateColumn HeaderText=”Authorized”>
<ItemTemplate>
<input type=”text” name=”Txt<%#IncLogSn%>” value=”<%#DataBinder.Eval(Container.DataItem,”Authorized”)%>”>
<input type=”hidden” name=”Hid<%#LastLogSn%>” value=”<%#DataBinder.Eval(Container.DataItem,”Authorized”)%>”>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>

private int LogSerialNum = -1;

protected int IncLogSn
{
get
{
return ++LogSerialNum;
}
}

protected int LastLogSn
{
get
{
return LogSerialNum;
}
}

No comments:

Post a Comment