asp .net dropdownlist selectedindex not working
I have the following piece of code:
DataRow CreateRow(DataTable dt, string name, string country)
{
DataRow dr = dt.NewRow();
dr["Name"] = name;
dr["Country"] = country;
return dr;
}
protected void Page_Load(object sender, EventArgs e)
{
// creating the data table
DataTable dt = new DataTable("Student Details");
// adding two columns Name and Country
dt.Columns.Add("Name", typeof(String));
dt.Columns.Add("Country", typeof(String));
// create 3 rows
dt.Rows.Add(CreateRow(dt, "Varun", "India开发者_StackOverflow"));
dt.Rows.Add(CreateRow(dt, "Li", "China"));
dt.Rows.Add(CreateRow(dt, "Yishan", "China"));
// create a data view
DataView dv = new DataView(dt);
DropDownList1.DataSource = dv;
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "Country";
DropDownList1.DataBind();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
int x = DropDownList1.SelectedIndex;
int temp = 0;
temp++;
}
and the markup looks like this:
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
<br />
<asp:DropDownList ID="DropDownList1" runat="server"
onselectedindexchanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="true">
</asp:DropDownList>
</div>
</form>
</body>
The problem is that label is always showing Varun no matter what I select. I debugged the code and found out that "DropDownList1.SelectedIndex" is always returning 0 for some reason.
I am not sure why is this happening. The function "DropDownList1_SelectedIndexChanged" is getting called every time I select something from the drop down list.
Thanks
Looks like you are binding the drop down in the Page_Load...
Remember that when the drop down is changed, it does a post back (AutoPostBack='True'), and since you are binding on Page_Load it will simply rebind ever time the index is changed... not what you want!
you should do something like this:
if (!IsPostBack)
{
BindDropDownList1();
}
Make sure ViewState is enabled (for change events), and move the code in your OnLoad
to OnInit
. This will prevent ViewState being overwritten as it occurs after Init and before Load.
Optionally you should also wrap the initialisation code inside an IsPostback
check to avoid having to load the data on every request.
you can use this code:
foreach (ListItem item in DropDownList1.Items)
{
if (item.Text == defaultText)
{
item.Selected = true;
break;
}
}
You can try overriding the OnPreRender
method of the page:
protected override OnPreRender(EventArgs e)
{
DropDownList1.SelectedIndex = Convert.ToInt32(ViewState["PageIndex"]);
base.OnPreRender(e);
}
Also, make sure that EnableViewState
is set to True
.
精彩评论