Is it possible to get invisible GridViewRow text in code?
I have a GridView BoundField defined as follows:
<asp:BoundField DataField="Id" />
In the code of the code, I can get an instance of the string and read the text as follows:
Row.Cells(0).Text
However, when I make BoundField invisible like this ...
<asp:BoundField DataField="Id" Visible="false" />
... Row.Cells(0).Text
returns an empty string.
The only solution I found was to create an element and change the element template, put a hidden field in it, and then get the hidden field using .FindControl()
. I do not really like this idea.
Use the DataKeyNames
gridview property.
<asp:GridView runat="server" ID="MyGridView" DataKeyNames="Id"> </asp:GridView>
And access this ID value as:
var data = MyGridView.DataKeys[RowIndex].Values[KeyIndex]
so in your case it could be as below for the 2nd row
var data = MyGridView.DataKeys[1].Values[0]
So, you want to access the field value from the code that is bound to the GridView.
You can simply define the event of binding the row to the gridview and access it just like this:
protected void gvMyGridView_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { int seminarId = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "PK_ID")); } //PK_ID is the database column name }
On an aspx page, you should have something like this
<asp:GridView ID="gvMyGridView" runat="server" AllowPaging="false" OnRowDataBound="gvSeminarRequestBucket_RowDataBound"> <asp:BoundField HeaderText="ID" DataField="PK_ID" /> </asp:GridView>
If you feel any kind of problem, feel free to ask
Hooray!!!
There is no need to add a BoundField
to an aspx page and make it invisible. You can use the DataBinder for this. If you need to access the Id
value in the ItemDataBound
event, use this
private void OnItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { //Use DataBinder.Eval(e.Row.DataItem, "ID") to receive Id value } }