Multi Value Data Binding and State Management

  • Thread starter Thread starter Icon Iconoclast
  • Start date Start date
I

Icon Iconoclast

I am facing a problem with state management while using Multi Value Data
Binding. ViewState is enabled. When I click on a radiobutton and click the
Button, the output always is:
From Listbox selection: -1

What's the solution to retain state?

Here's Default.aspx:
##############
<body>
<form id="form1" runat="server">
<div>
<asp:RadioButtonList ID="rdLaptops" runat="server" />
<asp:Button ID="cmd" runat="server" Text="OK" onclick="cmd_Click" />
<asp:Label ID="lbl" runat="server" Text="" /><br />
</div>
</form>
</body>
###############

Here's Default.aspx.cs:
###############
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

List<string> myLaptops=new List<string>();
myLaptops.Add("Lenovo");
myLaptops.Add("DELL");
myLaptops.Add("Acer");
myLaptops.Add("HP");

rdLaptops.DataSource = myLaptops;
DataBind();
}
protected void cmd_Click(object sender, EventArgs e)
{
string myString;
myString = rdLaptops.SelectedIndex.ToString();
lbl.Text = "From Radiobutton selection: " + myString;
}
}
###################
 
Your resetting the datasource each time the page is posted back to the
server. Try checking for Page.IsPostBack, see code below.

if (!Page.IsPostBack)
{
List<string> myLaptops = new List<string>();
myLaptops.Add("Lenovo");
myLaptops.Add("DELL");
myLaptops.Add("Acer");
myLaptops.Add("HP");

rdLaptops.DataSource = myLaptops;
DataBind();
}
 
better yet, move the code to oninit and turn off viewstate (make those
pages lighter and faster).

-- bruce (sqlwork.com)
 
Back
Top