not adding correct value from asp dropdown to database

Populate dropdown
myConnection.Open();
            
            SqlDataReader myReader = null;
            SqlCommand myCommand = new SqlCommand("Select ID, DispatcherName FROM Dispatchers", myConnection);
            myReader = myCommand.ExecuteReader();
            Dispatcher.Items.Clear();
            while (myReader.Read())
            {
                string DispatcherName = myReader["DispatcherName"].ToString();
                string ID = myReader["ID"].ToString();
                Dispatcher.Items.Add(new ListItem(DispatcherName, ID));
            }

Open in new window


Form submission (add button click event)
SqlCommand myInsert = new SqlCommand("INSERT INTO Users (Dispatcher) Values ('" +Dispatcher.SelectedItem.Value + "')", myConnection);
                myInsert.ExecuteNonQuery();
                GridView1.DataBind();

Open in new window


aspx code
Company<br />
                    <asp:DropDownList ID="Dispatcher" runat="server"></asp:DropDownList>

Open in new window


This does not bomb at all and writes the record to the database, but it always writes the value of the first option of the dropdown regardless of what I select.
LVL 9
BobHavertyComhAsked:
Who is Participating?
 
Lokesh B RDeveloperCommented:
Hi,

You need to populate the DropDownList  within the PostBack.

protected void Page_Load(object sender, EventArgs e)
{
            if (!IsPostBack)
            {
                SqlDataReader myReader = null;
                SqlCommand myCommand = new SqlCommand("Select ID, DispatcherName FROM Dispatchers", myConnection);
                myReader = myCommand.ExecuteReader();
                Dispatcher.Items.Clear();
                while (myReader.Read())
                {
                    string DispatcherName = myReader["DispatcherName"].ToString();
                    string ID = myReader["ID"].ToString();
                    Dispatcher.Items.Add(new ListItem(DispatcherName, ID));
                }

            }

// rest of the code goes here
}

Open in new window


When you click on Button again Page_Load event occurs and the DropDownList Binds and sets the First item as Selected.
0
 
BobHavertyComhAuthor Commented:
Tah! Dah! Thank you.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.