i’ve stuck with problem. I have an ASP.NET project with dynamically creating controls. Even more many controls depend on another controls (on postback), so they could change their appearance.
I have ListControl and binds it with data in one method:
public static class ListControlExtensions
{
public static void BindList(this ListControl list, IEnumerable dataSource, string valueKey, string textKey)
{
list.Items.Clear();
list.Items.Add(new ListItem("(Empty)", "-1"));
list.AppendDataBoundItems = true;
list.DataSource = dataSource;
list.DataValueField = valueKey;
list.DataTextField = textKey;
list.DataBind();
}
}
The incoming dataSource is good (as expected due to business logic), but rendered list control haven’t changed since last BindList. So problem – list control after fist databind (with default dataSource) doesn’t change after later databind.
The BindList invokes at the OnInit:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (CompaniesList != null)
{
BindCompaniesList(CompaniesList, valueToFilter);
}
}
protected void BindCompaniesList(ListControl listToBind, String valueToFilter)
{
if (listToBind != null)
{
var list = Helper.GetCompanies();
foreach (var item in list.Where(item => item.Value == valueToFilter))
{
item.Value = "-1";
}
listToBind.BindList(list, "Value", "Text");
}
}
FIXED: The solution: I think problem is that LoadViewState happens after OnInit and it overwrites the ListControl with the previous data, stored at ViewState. So I’ve moved DataBind to OnLoad from OnInit, and cached the selected value, because binding resets it.
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (CompaniesList != null)
{
var selected = CompaniesList.SelectedIndex;
BindCompaniesList(CompaniesList, valueToFilter);
CompaniesList.SelectedIndex = selected;
}
}
I would suggest moving the binding code to OnLoad and depending on how your code works it should look something like this
Also in the binding code I would suggest trying