Click here to Skip to main content
15,893,161 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I have a DDL that is bound to a SQL Server table depending on the selection of another DDL and inserting text into a Label depending on the selection. The problem is that the label is either not getting the data or the DDL are providing NULL to the label. Please check my code below and help resolve. Thank you.

protected void Page_Load(object sender, EventArgs e)
    {
        if(DropDownList1.SelectedIndex > 0)
        BindDropDownList2(DropDownList1.SelectedItem.Text);
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
           if (DropDownList1.SelectedIndex == 5)
                if (DropDownList2.SelectedIndex == 3)
                       Label1.Text = "You selected index 5 from ddl1 and index 3 from ddl2";

    }

private void BindDropDownList2(string field)
    {
        if (DropDownList1.SelectedIndex != 5)
        {
            con.ConnectionString = strcon;
            com.Connection = con;
            con.Open();

            string strQuery = @"SELECT " + DropDownList1.SelectedItem.Text + " FROM NUMS";
            da = new SqlDataAdapter(strQuery, con);
            da.Fill(ds);

            DropDownList2.DataSource = ds;
            DropDownList2.DataTextField = field;
            DropDownList2.DataValueField = field;
            DropDownList2.DataBind();

            con.Close();
        }
        else
        {
            DropDownList2.Items.Clear();
            DropDownList2.Items.Add("");
            DropDownList2.Items.Add("A");
            DropDownList2.Items.Add("B");
        }
    }
Posted
Updated 1-Jun-11 22:58pm
v3
Comments
Fabio V Silva 1-Jun-11 19:04pm    
Edited formatting.
Sergey Alexandrovich Kryukov 1-Jun-11 20:46pm    
ASP.NET? Add a tag!
--SA
cuteband 1-Jun-11 21:29pm    
if(DropDownList1.SelectedIndex > 0)
BindDropDownList2(DropDownList1.SelectedItem.Text);
Try to remove if(DropDownList1.SelectedIndex > 0) and see if its loading again

Hi use isPostBack in Page_Load
C#
protected void Page_Load(object sender, EventArgs e)
    {
        if(!isPostBack)
        {
            if(DropDownList1.SelectedIndex > 0)
            BindDropDownList2(DropDownList1.SelectedItem.Text);
        }   
    }


Thanks,
 
Share this answer
 
hi,

add this code at page load

if(isPostBack)
    return;



and make the ddl autopostback property true

this will help.
 
Share this answer
 
v2
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900