C# DropDownList selecting a value

In my last blog, I had attached a video that showed how to create a DropDownlist that’s connected to a database. What it didn’t show was how to capture the selected value in the DropDownlist. I needed to be able to transfer the value once it’s been submitted and update the database. This was how my code looked like after the video:

<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true" DataSourceID="SqlDataSource1">        
<asp:ListItem Text="--- Select ----" Value=" " />

The AppendDataBoundItems=”true” allows the user to add asp:ListItems that are not part of the database. In this example, I added “ — — Select — -”. The code behind exists in the <filename>.aspx.cs. In order to be able to select an item and have the value updated to the database, in the DropDownList add the AutoPostBack property and set it to true. Then, add the OnSeletedIndexChanged property and choose the ‘create new event’ option. It will created a method automatically in the <filename>.aspx.cs.

<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true" DataSourceID="SqlDataSource1" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Text="--- Select ----" Value=" " />
<asp:Button ID="AssignWorkoutButton" Text="Assign" runat="server" OnClick= "AssignWorkoutButton_Click"/>
AutoPostBack property get or set a value that indicate whether a postback to the server automatically occurs when the user changes the list selection. OnSelectedIndexChanged method raises the SelectedIndexChanged event that allow developers to provide a custom handler for the event.

In the code behind file, I added the following:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
DropDownList1.SelectedValue = DropDownList1.SelectedItem.Value;

This assigns the current SelectedItem.Value property to the SelectedValue property. When the submit button is clicked, the SelectedValue can be passed to the database via various methods created in the Business Layer.

This completes the DropDownList and the properties needed to be able to select the value and pass it on to other methods.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.