Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Change value of dropdown list on post back 1

Status
Not open for further replies.

luckydexte

Programmer
Apr 26, 2001
84
US
Hello,

I am struggling with this problem for several days now and cannot find a solution. I have a web form, when I enter a value it does a query on the value entered. I have several dropdown lists and need to populate the values. Some of these lists are dynamic and some are static. Currently I having a problem with the static dropdown lists. An example of code that WORKS is below:

private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack) {
ddlActiveYN.Items.Insert(0, "Select One");
}
}

private void txtChargeCode_TextChanged(object sender, System.EventArgs e)
{
addChargeCodeDataToForm();
}

private void addChargeCodeDataToForm()
{
string strChargeCode;
strChargeCode = txtChargeCode.Text;

try {
cmdChargeCodeById.Parameters["@chargecode"].Value = strChargeCode;
sqlConnection1.Open();
System.Data.SqlClient.SqlDataReader dreader;
dreader = cmdChargeCodeById.ExecuteReader(CommandBehavior.SingleRow);

if (dreader.Read()) {
string strActive;

// Have to rebuild the DDL
ddlActiveYN.Items.Clear();
ddlActiveYN.Items.Insert(0, "Select One");
ddlActiveYN.Items.Insert(1, "Y");
ddlActiveYN.Items.Insert(2, "N");
ddlActiveYN.Items.FindByValue(strActive).Selected = true;

}
dreader.Close();
}
catch (System.Data.SqlClient.SqlException) {
lblError.Text = "Server Error: Unable to load database!";
}
catch (System.Web.HttpException) {
lblError.Text = "No idea what is going on!";
}
catch {
lblError.Text = "In Exception";
}
finally {
sqlConnection1.Close();
}
}

For some reason I have to rebuild the dropdown list before I can use the following line:

ddlActiveYN.Items.FindByValue(strActive).Selected = true;

If I do not use the clear, and then rebuild the DDL I get the following error:

A DropDownList cannot have multiple items selected.

Any ideas??? Thanks.

Brandon
 
I found an answer for my own question if anyone is interested. This has frustrated me for hours so it hope it hopes someone:

Change the line:

ddlActiveYN.Items.FindByValue(strActive).Selected = true;

To:

ddlActiveYN.SelectedIndex = ddlActiveYN.Items.IndexOf(ddlActiveYN.Items.FindByValue(strActive));
 
A big thanks Brandon.
I was trying to do the same thing in ASP.NET using VB and your solution worked for me as well.
It seemed simple in theory but not easy to find the answer in practice.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top