Reputation: 11
I am trying to save the dropdown list selected value in a glbal variable .. I have lots of country on the dropdown list , whan I choose one of them and press a button :
protected void Button1_Click(object sender, EventArgs e)
{
Button2.Enabled = true;
Button2.Visible = true;
DropDownList1.Visible = true;
DropDownList9.Items.Clear();
if (!Class1.Search_Continent.Equals("-"))
{
SqlConnection conn1 = new SqlConnection(@"Data Source=AK-PC\MSSQLSERVER1;Initial Catalog=DB;Integrated Security=True");
conn1.Open();
SqlCommand cmd1 = new SqlCommand("Select Country_name FROM Country WHERE Continent_name='" + DropDownList1.SelectedValue + "'", conn1);
SqlDataReader dr1;
dr1 = cmd1.ExecuteReader();
while (dr1.Read())
{ DropDownList9.Items.Add(dr1["Country_name"].ToString() + "\n"); }
dr1.Close();
conn1.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
// Redirect to Country page
Class1.CountryName = DropDownList9.SelectedValue.ToString();
Response.Redirect("Country.aspx", true);
}
it doesnt take the selected value ! it always take the first value of the dropdown list ! Please help me !
Upvotes: 0
Views: 2107
Reputation: 218877
it always take the first value of the dropdown list
This is very common in web forms if you're populating the data incorrectly. Where are you populating the drop down list? I'm going to guess that you're doing it in Page_Load
. I'm also going to guess that you don't have it wrapped in something like if (!IsPostBack)
. If you put a debugging breakpoint in Page_Load
you'll find that it's called in the post-back before Button2_Click
is called.
Keep in mind that HTTP is stateless. This means that the entire server-side page object needs to be constructed on each request to the server. Page_Load
is part of that construction, and it happens before event handlers do. So what's likely happening is:
The most common solution to this problem is to use the aforementioned conditional in Page_Load
:
protected void Page_Load(object sender, EventArgs e)
{
// some initial logic
if (!IsPostBack)
{
// stuff that should only happen when the page first loads
// for example, populating controls from the database
}
// any other logic, etc.
}
The values for the controls shouldn't need to be re-populated with each postback because things like viewstate should keep the necessary data available. (Though if you mess with that at all then you might need to tinker some more.)
Upvotes: 0
Reputation: 21127
You are probably re-binding the DropDownList9
on postback and losing the SelectedValue
.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostback)
{
//bind data
}
}
Upvotes: 1