Jack Henry
Jack Henry

Reputation: 302

Drop Down List is not finding correct value

When I connect my dropdownlist (cmbStaff) and then try and apply a selected value to cmbStaff it will always return the very first value within the dropdownlist. Here is the code I use to bind data to the dropdownlist

 if(!IsPostBack)
{
    String Sql = @" select * from SupportTeam";

 SqlConnection conn = new SqlConnection(Properties.Resources.cString);
 SqlDataAdapter DA = new SqlDataAdapter(Sql, Properties.Resources.cString);
 DataSet DS = new DataSet();
 DA.Fill(DS, "SupportTeam");

 cmbStaff.DataValueField = "SupportTeamID";
 cmbStaff.DataTextField = "SupportTeamName";
 cmbStaff.DataSource = DS;
 cmbStaff.DataBind();
 cmbStaff.Items.Insert(0, "--Please select a support team--");
}

But in future code when I try and apply a selected value to the drop down it will always select the first index.

For example, if I do this

cmbStaff.SelectedValue = "TEL";

When I debug, it will always return this

cmbStaff.SelectedValue = "--Please select a support team--"
cmbStaff.SelectedIndex = 0;

Why is it doing this. I have data stored in the table as the combo works it just does not set starting index to the value that I want and that is what I need it to do.

Here is a snippet of the data I have stored in the SupportTeam Table enter image description here

Sorry if is seem vague, thanks in advance!

Upvotes: 0

Views: 152

Answers (2)

Jack Henry
Jack Henry

Reputation: 302

The problem I was having was Sql Related. It keep adding blank spaces onto the end of the value I was entering. I changed

String Sql = @" select * from SupportTeam";

to

String Sql = @" select rtrim(SupportTeamID) as SupportTeamID, rtrim(SupportTeamName) as SupportTeamName from SupportTeam";

It now works. I cannot find the exact reason why this happened. Of course the .Trim() function will also work when declaring Sql variables in c#.

Upvotes: 0

Sujit.Warrier
Sujit.Warrier

Reputation: 2869

That is not how you set a selected value for a drop down list. you use the findbyvalue function and set selected =true

cmbStaff.Items.FindByValue("TEL").Selected = true;

Upvotes: 1

Related Questions