i have a problem as subject said.
i have a Table courses in sql server Fields are courseID and course.
what i want is list the course in dopdown and i succeeeded but what i’m not able to do is when i select a course from dropdown list, a courseID should be selected in HiddenField/textbox/label
how to do that
here is a code i tried::
protected void Page_Load(object sender, EventArgs e)
{
string select = "select * from courses";
DropDownList1.Items.Add("-- Select Course --");
DropDownList1.SelectedIndex = 0;
DataTable dt = con.select_command(select);
for (int i = 0; i < dt.Rows.Count; i++)
{
DropDownList1.Items.Add(dt.Rows[i][1].ToString());
DropDownList1.DataValueField = dt.Rows[i][0].ToString();
DropDownList1.DataTextField = dt.Rows[i][1].ToString();
}
}
in dropdownlist i’m getting values in Page Load method
i also tried dropdownlist_selectedindex change method too to select courseID
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
LLabel1.Text = DropDownList1.SelectedValue.ToString();
}
what i’m doing wrong ???
Place a block of
if (!IsPostBack)before you update the dropdown in your page_loadThe problem is that your code will re-populate the dropdown menu after the
DropDownList1_SelectedIndexChangedevent will be triggred.That will make a post request to the server and he will run the
DropDownList1_SelectedIndexChangedfunction attached to theIndexChangeevent and thenpage_loadbecause the page suppose to be loaded again
and will result in a new selected value that will not be what you expect it to be.
One more thing: use string identifiers when getting a value from a Row of a DataTable the code will be much more friendly that way. (Readability is very important…)