1
votes

I am having a problem where when I try and retrieve the selected value of an item within a drop down, it only brings me back the selected value of the very first item within it.

This is the code I use to fill the drop down list with data from a table within Sql-Server

  protected void Page_Load(object sender, EventArgs e)
    {
        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");
        DataTable DT = DS.Tables["SupportTeam"];


        DropDownList1.DataValueField = "supportTeamID";
        DropDownList1.DataTextField = "supportTeamName";
        DropDownList1.DataSource = DT;
        DropDownList1.DataBind();
}

Everything works fine when I load the web form, all of the items do display within the drop down list but the problem I am having is that when I change the selected item in the drop down then the DataValueField stays the same

Here is an example. I have 2 rows within my table in Sql

SupportTeamID SupportTeamName

5         -         Marketing 

8         -         e-Learning

When I load my web form, the selected index is set at 0 meaning that the DataValueField is 5. When I select e-Learning from the drop down list, when I debug it still says that DataValueField is 5 when it should be 8.

Here is the code I use to retrieve to selected value within a button click event

  supportTeamID = Convert.ToInt32(DropDownList1.SelectedValue);

Every time I run this the supportTeamID is always set to 5

Is there something I am doing wrong or missing? Thanks in advance

1
where do you write this code? in Form_Load? - mhsankar
I wrote the top code in the form load and the selected value retrieval code in a button click event - Jack Henry
send your code here - mhsankar

1 Answers

1
votes

you must write code when its not IsPostBack

protected void Page_Load(object sender, EventArgs e)
{
    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");
    DataTable DT = DS.Tables["SupportTeam"];


    DropDownList1.DataValueField = "supportTeamID";
    DropDownList1.DataTextField = "supportTeamName";
    DropDownList1.DataSource = DT;
    DropDownList1.DataBind();
    }
}