ASP.NET / DataList 的 DataItem 回发后为空
在我的 ASP.NET 表单中回发(单击按钮)后,表单的所有 DataItem 均为 null。为什么?即使在回发后,我应该怎么做才能检索 DataList 的内容?
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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
找到我的答案 此处。
更准确地说,我使用 HiddenField 跨帖子存储 ID,并从数据库请求数据,而不是尝试从 DataItem 获取数据(不能在数据绑定事件之外使用)。
Found my answer here.
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).
DataItem
仅在数据绑定时可用。Load
发生在Click
之前,因此您无论如何都会覆盖数据。这样做:
您应该使用数据源(如 ObjectDataSource)来处理数据绑定和更新/插入。
更新/建议:
使用占位符将数据绑定到您会给自己带来麻烦。您应该考虑使用 ListView、GridView、DataList 或 Repeater。我确信其中任何一个都能满足您的需求,并且您将需要更少的编程。用你的时间来学习它们,而不是试图让它发挥作用,它注定会失败。
DataItem
is only available when databinding.Load
comes beforeClick
so you're overwriting your data anyways.Do this:
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.
检查每次回发后是否确实对 DataList 进行了 DataBind()。通常,当您不再次绑定 DataList、GridView、DropDownList(和其他控件)后,回发后它们会变为空。
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.