DataBind of DropDownList works, but does not show in code behind
I'm working on web pages that have an ASP DropDownList defined, and on page load the data source is bound to it through DataSource.D开发者_如何学编程ataBind(). When I step through the code, the drop down list does not show anything in it, but when the page actually displays, it does have items in the list. When exactly does DataBind() get applied to the control?
The problem is that some of the values returned by the SQL back end have a null Text, so nothing is displayed in the drop down list for that row. I want to just use the Value as the Text, but only if the Text is null. And when I put the code to loop through and do that right after the DataBind(), there is nothing in the drop down list at that point in the code.
Thanks!
The best option for your specific example is to do what kd7 said, and modify your query. However, if you ever need to do other modifications to the items, you can access them in the DataBound event of the DropDownList. MSDN. This event fires after the binding occurs.
You could
a) Modify your database query to exclude null values
or
b) Before you databind, iterate through the data returned and remove the undesired values.
You can just use LINQ on the data before you assign it to create a new type on the fly with the data arranged how you want. Here is a quick example:
// This simulates the data you get from the DB
List<SomeObject> lstData = new List<SomeObject>();
lstData.Add(new SomeObject() { ID = "1", Text = "One" });
lstData.Add(new SomeObject() { ID = "2", Text = "" });
lstData.Add(new SomeObject() { ID = "3", Text = "Three" });
// This will take your data and create a new version of it substituting the
// ID field into the Text field when the Text is null or empty.
yourDropDownList.DataSource = lstData.Select(i => new {
ID = i.ID,
Text = string.IsNullOrEmpty(i.Text) ? i.ID : i.Text }).ToList();
// Then just databind
yourDropDownList.DataBind();
The DropDownList
would have the following items:
One
2
Three
精彩评论