Reputation: 702
I have a paginated GridView on an ASP.NET page. In the DataBound event of the GridView control, I am attempting to update the OnClick event of each cell in the row to window.open() a new page using a field in the underlying DataTable that is not displayed in the GridView. However, the GridView DataSource propety is null, as is the GridViewRow DataItem property. The GridView's DataKeys has a Count of 0. The paginated DataSet has 20 rows and is being rendered properly, I just can't find the underlying data to pull the ID needed for the window.open() call.
I have followed asp.net's guide when constructing my page:
So I have a DAL -> BLL -> ObjectDataSource -> GridView. The ID column is being hidden in the GridView:
<asp:GridView ID="pdfdocuments" runat="server" AllowPaging="True"
AutoGenerateColumns="False" DataSourceID="pdfods" PageSize="20"
ondatabound="pdfdocuments_DataBound">
<PagerSettings Mode="NumericFirstLast" />
<Columns>
<asp:BoundField DataField="pdf_id" HeaderText="pdf_id" InsertVisible="False"
ReadOnly="True" SortExpression="pdf_id" Visible="False" />
...
</Columns>
<HeaderStyle BackColor="#FFCC99" />
<AlternatingRowStyle BackColor="#FFFFCC" />
</asp:GridView>
How do I access the pdf_id value in the underlying DataTable?
Upvotes: 1
Views: 2655
Reputation: 2270
I agree with D-Mac to use RowDataBound event. But instead of using GridView.DataSourceObject try to access the row's DataItem property.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView rowView = e.Row.DataItem as DataRowView;
if (rowView != null)
{
//Check if the execution reach this pont
object pdf_id = rowView["pdf_id"];
}
}
You can find an example here
Upvotes: 1
Reputation: 92
Try accessing GridView.DataSourceObject in the RowDataBound event.
Unless there is some requirement to use javascript window.open it is probably better to use an anchor tag with a target like the following code:
<asp:GridView ID="GridView1" runat="server" DataSourceID="ODS1"
OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="False">
<Columns>
<asp:HyperLinkField DataTextField="FieldName" DataNavigateUrlFields="FieldID" DataNavigateUrlFormatString="somePage.aspx?id={0}" Target="_blank" />
</Columns>
</asp:GridView>
If you have to execute JavaScript you can still do it without accessing the underlying DataSourceObject directly using a TemplateField:
<asp:GridView ID="GridView1" runat="server" DataSourceID="ODS1"
OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<a href='javascript:window.open(<%# Eval("FieldID") %>);'><%#Eval("FieldName")%></a>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Upvotes: 2