yrazlik
yrazlik

Reputation: 10787

Cannot get the selected value of combobox in asp.net

I created a dropdown combobox in asp.net. Here it is:

<asp:ComboBox ID="dropdown_course3" runat="server" AutoPostBack="False" 
         DropDownStyle="DropDownList"
         AutoCompleteMode="Suggest" CaseSensitive="False" 
         ItemInsertLocation="Append">
</asp:ComboBox>

Then i have a button in my page, and when i click it, i want to get the value of selected item in combobox. The button causes postback. Here is my code:

protected void button_conflict_check_button_Click(object sender, EventArgs e)
{
    string dr3 = dropdown_course3.Text;
}

But this returns an empty string even though it should not be empty. Also, i tried selectedItem and it returns null. Can anyone help me with this?

And also, here is how i fill the combobox:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        DataTable subjects = new DataTable();
        CommonFunctions.con.ConnectionString = CommonFunctions.getConnectionString();
        CommonFunctions.con.Open();

        try
        {

            SqlDataAdapter adapter = new SqlDataAdapter("SELECT [crn], [subj], [numb], [section] FROM Courses", CommonFunctions.con);
            adapter.Fill(subjects);

            foreach (DataRow dr in subjects.Rows)
            {
                string displayVal = dr["subj"].ToString() + " " + dr["numb"].ToString() + " " + dr["section"].ToString();

                dropdown_course1.Items.Add(new ListItem(displayVal));
                dropdown_course2.Items.Add(new ListItem(displayVal));
                dropdown_course3.Items.Add(new ListItem(displayVal));
            }
        }
        catch (Exception ex)
        {
            // Handle the error
        }

        // Add the initial item - you can add this even if the options from the
        // db were not successfully loaded

        CommonFunctions.con.Close();
    }
}

Thanks

Upvotes: 1

Views: 1661

Answers (1)

yrazlik
yrazlik

Reputation: 10787

I have found the problem, since i fill the combobox at page load and inside if(!Page.IsPostBack) block, the button causes postback and combobox seems to be empty.

Upvotes: 1

Related Questions