Reputation:
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;
}
Upvotes: 9
Views: 15242
Reputation:
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.
Upvotes: 9
Reputation: 4023
DataItem
is only available when databinding.
Load
comes before Click
so you're overwriting your data anyways.
Do this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindFields();
}
}
You should use a DataSource (like ObjectDataSource) to handle DataBinding and Update/Insert.
Update / advise:
Using PlaceHolders to bind data to you are getting yourself in trouble. You should consider using either a ListView, GridView, DataList or Repeater. I'm sure any of those do what you want and you will have to program less. Use your time to learn them instead of trying to get this to work, its doomed to fail.
Upvotes: 6
Reputation: 935
Check if you really DataBind() the DataList after each postback. Normally you get DataList, GridView, DropDownList (and other Controls) empty after a PostBack when you don't bind them again.
Upvotes: 0