Inserting a contextual JS function in a DataGrid LinkButton

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I hava a DataGrid with a bunch of columns. The first column ([0]) is a
Username and the last column is set up like this:

<asp:TemplateColumn>
<ItemTemplate>
<asp:LinkButton ID="ProfileLBtn" runat="server"
CausesValidation="false" CommandName="Profile"
Text="Profile" />
</ItemTemplate>
</asp:TemplateColumn>

I don't want to actually use this last column to execute a Server-Side
function post-back at all. Instead, I want it to make a client-side
JavaScript call USING A VALUE FROM THE FIRST COLUMN FOR EACH ROW IN MY
DATAGRID.

I've tried doing this as follows...

protected void UsersDG_ItemCreated(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
string Username = e.Item.Cells[0].Text;
LinkButton LBtn = e.Item.FindControl("ProfileLBtn") as LinkButton;
LBtn.OnClientClick = "PopUserProfile('" + Username + "');
return(false);";
}
}

So everything about this works EXCEPT that the value of Username is always
EMPTY. Is this because during execution of "UsersDG_ItemCreated", the value
hasn't yet been populated?

Alex
 
Try using the ItemDataBound event instead of ItemCreated. The item should
definitely be there in that handler.
Otherwise, it could be possible that e.Item.Cells[0] isn't the actual
control that is holding the value, e.g., it might be
e.ItemCells[0].Controls[0].Text, for example.
Peter
 
Thanks Peter for your input.

Hi Alex,

I agree with Peter on this that you should use the ItemDataBound event
instead of ItemCreated. Besides, you can use the event's parameter
DataGridItemEventArgs.Item.DataItem to access the row data rather than
reading the cell's text. For example, if you are binding the DataGrid to a
DataSource, use following sample code to read the other fields:

protected void DataGrid1_ItemDataBound(object sender,
DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType ==
ListItemType.AlternatingItem)
{
DataRowView v = (DataRowView) e.Item.DataItem;
object id = v["ProductID"];
}
}

Hope this helps. Please feel free to post here if anything is unclear.

Regards,
Walter Wang
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
 
Back
Top