How to add item to Repeater control manually
asp.net, c#, repeater
Solution
If you only need to fetch data once and you're going to use viewstate, get the data first time you need it, store it in VS and get it from VS for all future PostBacks.
Example:
public List<int> Data
{
get
{
if (ViewState["Data"] == null)
{
// Get your data, save it and return it.
var data = new List<int> { 1, 2, 3 };
ViewState["Data"] = data;
return data;
}
return (List<int>)ViewState["Data"];
}
set
{
ViewState["Data"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData(Data);
}
}
private void BindData(List<int> data)
{
_ddlOptions.DataSource = data;
_ddlOptions.DataBind();
}
protected void OnAdd(object sender, EventArgs e)
{
var existing = Data;
existing.Add(_ddlOptions.SelectedItem);
_ddlOptions.Items.RemoveAt(_ddlOptions.SelectedIndex);
Data = existing;
BindData(existing);
}
I didn't test this - and its only my first thought but you can build on it from here.
Patrick.
Problem
First of all: - _ddlOptions is drop down list - _selectedOptions is repeater control and it's just provisional code of my final control. What I want to do is to get data for _ddlOption on !IsPostBack. There is Add button that enables user to move selected drop down item to repeater control. It the following way of updating Repeater.Items correct? I found many solution of adding/removing elements manually using DataSource, but here my DataSource is null, as I set it only on !IsPostBack. ``` protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { _ddlOptions.DataSource = new[] { 1, 2, 3 }; _ddlOptions.DataBind(); } } protected void OnAdd(object sender, EventArgs e) { var list = new ArrayList(_selectedOptions.Items); list.Add(_ddlOptions.SelectedItem); _ddlOptions.Items.RemoveAt(_ddlOptions.SelectedIndex); _selectedOptions.DataSource = list; _selectedOptions.DataBind(); } ```