Click here to Skip to main content
14,735,092 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Everyone,

i have an issue i have been battling with for sometime now, my dynamic DropDownList always return to the first item from database, i have done a few researches on how to resolve this including enabling Viewstate for the page and DropDownList and placing the code on if(!Page.IsPostback) but the issue persists!

Here is my code:

What I have tried:

if (!Page.IsPostBack)
                {
                    string appType2 = Session["applicationType"].ToString();
                    if (appType2 == "nur")
                    {

                        FetchApplicationFeeFromDB("NURSERY");
                        this.ddlAppClass.Items.Clear();
                        this.ddlApplicationType.Items.Insert(0, "NURSERY SCHOOL");

                        string query = string.Format("SELECT [Teaching Room Category] ,[Description] FROM [Corona Schools_ Trust Council$Teaching Room Level] WHERE [Teaching Room Category] = '{0}'", "NURSERY");
                        BindDropDownList(this.ddlAppClass, query, "Description", "Teaching Room Category", "---Select---");
                    }

                }


Binding Method:

private void BindDropDownList(DropDownList ddl, string query, string text, string value, string defaultText)
    {
        string conString = ConfigurationManager.ConnectionStrings["DatabaseDemo Database NAV (8-0)1"].ConnectionString;
        SqlCommand cmd = new SqlCommand(query);
        using (SqlConnection con = new SqlConnection(conString))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                con.Open();
                ddl.DataSource = cmd.ExecuteReader();
                ddl.DataTextField = text;
                ddl.DataValueField = value;
                ddl.DataBind();
                con.Close();
            }
        }
        ddl.Items.Insert(0, new ListItem(defaultText, "0"));
    }


My DropdownList Source code:

<asp:DropDownList ID="ddlAppClass" runat="server" AutoPostBack="True" Height="20px" Width="188px" OnSelectedIndexChanged="ddlAppClass_SelectedIndexChanged" EnableViewState="true"></asp:DropDownList>


Reading Value:
if (this.ddlAppClass.SelectedIndex != 0)
                {
                    SchoolAge(this.ddlAppClass.SelectedItem.Text);                    
                }


SchoolAge Method:

private void SchoolAge(string _classType)
        {
            try
            {
                var select = "SELECT [ClassType],[age] FROM [Corona Schools_ Trust Council$AddAge] WHERE [ClassType] = @ClassType";
                SqlDataReader rder = null;
                using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseDemo Database NAV (8-0)1"].ConnectionString))
                {
                    using (var command = new SqlCommand(select, connection))
                    {
                        command.CommandType = CommandType.Text;
                        command.Parameters.Add("@ClassType", SqlDbType.VarChar, 50).Value = _classType;
                        connection.Open();
                        rder = command.ExecuteReader();
                        while (rder.Read())
                        {

                            ValidateAge.Text = (rder["age"].ToString());

                        }

                    }
                }
            }
            catch (SqlException ex)
            {
                //lblMsg.Text = ex.Message;
                //lblMsg.ForeColor = System.Drawing.Color.Red;
            }

        }



I appreciate your assistance!
Posted
Updated 16-Feb-16 5:53am
v2
Comments
F-ES Sitecore 16-Feb-16 10:28am
   
How\where are you reading the selected item? Or are you saying it returns to the first item after the auto postback?
Uwakpeter 16-Feb-16 10:32am
   
i am reading the first item by selecting from the drop down list, when the page is run
F-ES Sitecore 16-Feb-16 10:38am
   
Update the question to include that code also.
Uwakpeter 16-Feb-16 10:54am
   
I have just done that sir.
F-ES Sitecore 16-Feb-16 10:58am
   
How is that code called, though, is it via a button_click event? A different auto-postback event? If you put a breakpoint on the code that binds the dropdown and a breakpoint on the code that reads the value, is the code that does the binding ran before the one that reads the value?
Uwakpeter 16-Feb-16 11:01am
   
i called the code on txtDateOfBirth TextChanged event, i event tried it on a post back event, was not able to resolve it. The thing is that whenever the page is being postback, it will be resettling to zero index even if i select from another dropdown list that the auto post is set to true. thanks
F-ES Sitecore 16-Feb-16 11:14am
   
You're not quite getting that the context of the code is vital to why it might be working or not, posting snippets doesn't give us the full picture. I'll post a solution that does what you've described that works and you're just going to have to see where your solution is different.
Richard Deeming 16-Feb-16 11:24am
   
Although you're using a static value at the moment, your BindDropDownList method promotes code which is vulnerable to SQL Injection[^]. As soon as you need to call that method with a query that uses user-supplied parameters, your code will be vulnerable.

You should rewrite the method to accept query parameters and use a properly parameterized command, as your SchoolAge method does.

1 solution

<asp:DropDownList ID="ddlAppClass" runat="server" AutoPostBack="True" Height="20px" Width="188px" OnSelectedIndexChanged="ddlAppClass_SelectedIndexChanged" EnableViewState="true"></asp:DropDownList>

<asp:TextBox ID="txtDateOfBirth" OnTextChanged="txtDateOfBirth_TextChanged" AutoPostBack="true" runat="server" />

Selected item: <asp:Literal ID="LiteralResult" runat="server" />


code-behind

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        string query = string.Format("SELECT [Teaching Room Category] ,[Description] FROM [Corona Schools_ Trust Council$Teaching Room Level] WHERE [Teaching Room Category] = '{0}'", "NURSERY");
        BindDropDownList(this.ddlAppClass, query, "Description", "Teaching Room Category", "---Select---");
    }
}

private void BindDropDownList(DropDownList ddl, string query, string text, string value, string defaultText)
{
    ddl.Items.Add(new ListItem { Text = "One", Value = "1" });
    ddl.Items.Add(new ListItem { Text = "Two", Value = "2" });
    ddl.Items.Add(new ListItem { Text = "Three", Value = "3" });

    ddl.Items.Insert(0, new ListItem(defaultText, "0"));
}


protected void ddlAppClass_SelectedIndexChanged(object sender, EventArgs e)
{

}

protected void txtDateOfBirth_TextChanged(object sender, EventArgs e)
{
    if (this.ddlAppClass.SelectedIndex != 0)
    {
        LiteralResult.Text = this.ddlAppClass.SelectedItem.Text;
    }
}
   

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

  Print Answers RSS
Top Experts
Last 24hrsThis month



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