After postback (click on a button) in my ASP.NET form, all the DataItem of my form are null. Why? What should I do to retrieve the content of the DataList even after postback?
protected void buttonAddRecord_Click(object sender, EventArgs e)
{
foreach (DataListItem item in listFields.Items)
{
// item.DataItem == null WTF?
}
}
protected void Page_Load(object sender, EventArgs e)
{
BindFields();
}
private void BindFields()
{
object setting = MySettings.GetSetting();
if (!Null.IsNull(setting))
{
listFields.DataSource =
DataProvider.GetData(int.Parse(setting.ToString()));
listFields.DataBind();
}
listFields.Visible = listFields.Items.Count > 0;
emptyMessage.Visible = listFields.Items.Count == 0;
}
Found my answer here.
What John said, the data source items are only avaliable when databound. They are no longer accessable after initial loading.
You might consider having an object or object collection representing onscreen data that you update with the grid, then persist changes from that to databases.
More precisely, I used an HiddenField to store an ID across posts and I request data from the database instead of trying to get it form the DataItem (which can't be used outside the databinding event).
The HiddenField control is used to store a value that needs to be persisted across posts to the server.