Using DataBinder.Eval in the RowDataBound Event
Often times in the RowDataBound event, I have a need to perform some logic based on a field in my data source that I don't need to display on the screen. When this happened, I was using things like HiddenFields or Labels to get at that data. It seems there is a much better way, using DataBinder in your code behind just like you do in the ASPX page, that I was simply unaware of.
Let's say I have a DropDownList named ddlMyList that I need to populate dynamically based on values in my database. My GridView looks like so:
<asp:DropDownList ID="ddlMyList" runat="server" />
I then need to set the selected value of ddlMyList to the ID field in my data source. Previously what I would have done is create a HiddenField control or Label (which I would then hide), set the value of it to the ID, and then used this control in the RowDataBound event to get that ID value.
We really don't need to do that though... we can use DataBinder in our code behind and get that value directly.
protected void MyGridView_OnRowDataBound(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow)
DropDownList ddlMyList = (DropDownList)e.Row.FindControl("ddlMyList");
// Do some logic to populate my ddlMyList with data
ddlMyList.SelectedValue = DataBinder.Eval(e.Row.DataItem, "ID").ToString();
I'm really amazed that I've been doing this for so long using HiddenFields and Labels and never realized that there was a so much simpler way to do this. I've looked at numerous tutorials online and until recently never seen it done any other way (I wish I had a link to where I first saw this, but I failed to keep a bookmark). I hope by mentioning it here, I'll save a few others the pain and suffering that I endured.
And maybe someone will tell me if this was just something obvious I completely missed or if you missed it too.
This article has been view 14685 times.