Reputation: 4919
I bind data to the repeater on Page Init:
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
repeaterInfo.DataSource = //getDataSource;
repeaterInfo.DataBind();
}
}
Here's the markup page
<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>
Here's the Item created event:
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
}
And I would like to save the user input to database when the user clicks the submit button:
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
}
And here's the problem:
The repeaterInfo datasource is null on postback
If I remove the !IsPostBack, the txtUserInput text will be resetted (0.0)
I've enabled the viewstate on the markup page using EnableViewState="true"
How I can get the text in txtUserInput?
Upvotes: 1
Views: 3487
Reputation: 18008
The repeater's datasource is not persisted in cross postbacks. If you just want to iterate and get the user inputs, you can just iterate through the items and get those like this:
foreach (RepeaterItem item in repeaterInfo.Items)
{
if(item.ItemType == ListItemType.Item)
{
var txtUserInput = item.FindControl("txtUserInput") as TextBox;
}
}
If you want the datasource to be persisted (may be to avoid database calls), use the ViewState
(watch out for large number of rows):
ViewState["myDataSource"] = myDatasource;
Upvotes: 2