简体   繁体   中英

How to change value of a dropdown list from a SQL select?

I need to update the displayed value of a drop down list from the results of a query.

This is an asp.net webform in c# using a sql db and all data needs to be handled in the codebehind.

This page is intended to update the Building table. The building table contains a companyID that corresponds a company code in the company table.

On page load I call GetCompanyCodes() and fill the drop down with the available company codes from company. Then I call BindForm() which fills in the the two other text boxes and a check box on the form using a stored procedure that joins the company table and returns the appropriate company code for the companyID listed in the building table.

What I can not figure how to do is to change the displayed value of the drop down list when I load in the data from the Building table.

I have no issue setting the value of the other controls, just the drop down.

Any suggestions on how to achieve this?

Let's say this is the data returned by the SqlDataSource which is set as the data source of the DropDownList :

在此处输入图片说明

Now, for displaying the company name in the DropDownList you should go to the DropDownList Tasks and then Choose Data Source. Then in the Data Source Configuration Wizard windows, select the CompanyName as a display field and the CompanyId as a value field. Later, if you wanted to update the DropDownList just call the DataBind() method.

this.DropDownList1.DataBind();

The easiest way is like this, by specifying the text and value fields from the source.

protected void Button1_Click(object sender, EventArgs e)
{
    DropDownList1.DataSource = loadFromDataBase();
    DropDownList1.DataValueField = "ID";
    DropDownList1.DataTextField = "Name";
    DropDownList1.DataBind();
}

Ok, so I was able to get the value I wanted to the drop down, but now I can't access the value of the drop down for a different call.

@VDWWD, you corrected part of the issue - I was calling .SelectedValue and .DataTextField was what did the trick.

The other part of the issue is that I was trying to get to the .SelectedItem to the columne name when I bound the form, but what it needed to be was .SelectedItem.Text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM