Reputation: 648
I am new to the wonderful world of dropdownlists and I know this is going to be difficult for me to explain but I will try the best I can.
Here is my data:
**Type** **ID** **Status**
Letter 1 A
Letter 2 B
Letter 3 C
Letter 4 D
Letter 5 E
From my query result I return the ID of "3" and my Drop Down List displays a "C". I have accomplished this piece already :). My question is, how can I populate the dropdownlist with the Statuses? My DDL will display a "C" and when it the arrow is clicked, the rest of the Status values will be displayed.
Is this something that can be done with the sql query? Do I have to create a separate method? If someone could point me in the right direction or provide some helpful code that would be awesome! Here is my code:
SqlDataAdapter adapter = new SqlDataAdapter("SELECT Status FROM dbo.database WHERE ID = @ID AND Type = 'Letter'", mySqlConnection1);
adapter.SelectCommand.Parameters.Add("@ID", SqlDbType.Char).Value = lblID.Text;
adapter.Fill(test);
ddlStatus.DataSource = test;
ddlStatus.DataTextField = "Status";
ddlStatus.DataValueField = Status";
ddlStatus.DataBind();
Upvotes: 0
Views: 935
Reputation: 25855
I think this is what you are looking for:
SqlDataAdapter adapter = new SqlDataAdapter(
"SELECT ID, Status FROM dbo.database WHERE Type = 'Letter'",
mySqlConnection1);
adapter.Fill(test);
ddlStatus.DataSource = test;
ddlStatus.DataTextField = "Status";
ddlStatus.DataValueField = "ID";
ddlStatus.DataBind();
ddlStatus.SelectedValue = lblID.Text;
First, fill the DropDownList with the values you need, then set the SelectedValue to have that value automatically displayed. From what I understand, you want the Status to be displayed to the user, but the actual selected value should be the ID.
Depending on your usage of ViewState, you may only need to load the DropDownList once (when the page is first loaded) and then simply set the SelectedValue after that. (You'd need to reload the list on a second page load. Use the IsPostBack
value to determine whether or not to reload). There is, however, very little harm in reloading each time, other than a fraction of a second being added to your page load time.
Upvotes: 1
Reputation: 26396
I think what you are looking for is SelectedValue
ddlStatus.DataSource = test;
ddlStatus.DataTextField = "Status";
ddlStatus.DataValueField = "ID";
ddlStatus.DataBind();
//Add this line
string defaultValue = "3";
ddlStatus.SelectedValue = defaultValue; //C has ID of 3
Upvotes: 0