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:
We really don't need to do that though... we can use DataBinder in our code behind and get that value directly.
And maybe someone will tell me if this was just something obvious I completely missed or if you missed it too.
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:GridView ID="MyGridView" runat="server" AutoGenerateColumns="False" OnRowDataBound="MyGridView_OnRowDataBound" > <Columns> <asp:TemplateField HeaderText="License"> <ItemTemplate> <asp:DropDownList ID="ddlMyList" runat="server" /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView>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.
2 comments:
super god bless ur helping hand
Thank Q Very much kootes balu.........
Post a Comment