Inserting a contextual JS function in a DataGrid LinkButton

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
 
G

Guest

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
 
W

Walter Wang [MSFT]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top