我将数据绑定到Page Init:
上的转发器 protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
repeaterInfo.DataSource = //getDataSource;
repeaterInfo.DataBind();
}
}
这是标记页
<table class="beautifulTable">
<asp:Repeater runat="server" ID="repeaterInfo" OnItemCreated="repeaterInfo_ItemCreated">
<ItemTemplate>
<tr>
<td style="display: none">
<asp:TextBox runat="server" Width="90%" ID="txtUserInput"></asp:TextBox>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
这是Item创建的事件:
protected void repeaterInfo_ItemCreated(object sender, RepeaterItemEventArgs e)
{
if (e.Item.DataItem == null)
return;
TextBox txtUserInput= e.Item.FindControl("txtUserInput") as TextBox;
txtUserInput.Text = "0.0"; //Default value
}
当用户点击提交按钮时,我想将用户输入保存到数据库:
protected void btnSubmit_Click(object sender, EventArgs e)
{
List<repeaterType> source = repeaterInfo.DataSource as List<repeaterType>;
for (int z = 0; z < source.Count; z++)
{
TextBox txtUserInput = repeaterInfo.Items[z].FindControl("txtUserInput") as TextBox;
//Get text and do logic here
}
//Saves data to database
}
这就是问题所在:
回发时repeaterInfo数据源为空
如果我删除了!IsPostBack,则会重置txtUserInput文本(0.0)
我已使用EnableViewState="true"
如何在txtUserInput中获取文本?
答案 0 :(得分:2)
转发器的数据源不会在交叉回发中保留。如果您只想迭代并获取用户输入,您可以遍历这些项目并获得以下内容:
foreach (RepeaterItem item in repeaterInfo.Items)
{
if(item.ItemType == ListItemType.Item)
{
var txtUserInput = item.FindControl("txtUserInput") as TextBox;
}
}
如果要保留数据源(可能是为了避免数据库调用),请使用ViewState
(注意大量行):
ViewState["myDataSource"] = myDatasource;