Postback and DropDownList problem [RESOLVED]
Hello,
I have a Dropdownlist which pulls its items from a Database, when the user selects an item a second Dropdownlist becomes visible with items populated with a database again. This all works fine. The Second Dropdownlist in the Page_Load inside a If (IsPostback) Loop. The problem is when the user presses the submit button on the web form the IsPostBack is called and the value i get is the first value in the DropDownlist.
Hopefully if you see my code you will understand:
Code:
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
OleDbConnection WO_Conn = new OleDbConnection(ConfigurationSettings.AppSettings["DSN"]);
string SQL;
SQL = "SELECT * FROM MainMenu ORDER BY MainMenuList DESC";
OleDbCommand myCmd = new OleDbCommand(SQL, WO_Conn);
OleDbDataReader myReader;
WO_Conn.Open();
myReader = myCmd.ExecuteReader();
ddlMainMenu.DataSource = myReader;
ddlMainMenu.DataTextField = "MainMenuList";
ddlMainMenu.DataValueField = "MainMenuList";
ddlMainMenu.DataBind();
myReader.Close();
WO_Conn.Close();
}
if (IsPostBack)
{
OleDbConnection WO_Conn = new OleDbConnection(ConfigurationSettings.AppSettings["DSN"]);
string SQL;
SQL = "SELECT * FROM SubMenu WHERE mainMenu LIKE '%" + ddlMainMenu.SelectedItem.ToString() + "%'";
OleDbCommand myCmd = new OleDbCommand(SQL, WO_Conn);
OleDbDataReader myReader;
WO_Conn.Open();
myReader = myCmd.ExecuteReader();
ddlSubMenu.DataSource = myReader;
ddlSubMenu.DataTextField = "subMenuList";
ddlSubMenu.DataValueField = "subMenuList";
ddlSubMenu.DataBind();
myReader.Close();
WO_Conn.Close();
ddlSubMenu.Visible = true;
}
}
Now when the user clicks the submit form button the second DropDownlist is re-populated and therefore the selected valur from the user is not received. I have tried using session variable to store the selectedValue but this doesn't work.
Any help greatly appreciated.
Re: Postback and DropDownList problem
Couldn't you put your DB code in the dropdownlist.changed event, to prevent it from running when a button is pushed?
Re: Postback and DropDownList problem
This is because when you click the submit button the Form_Load event fires BEFORE btnSubmit_Click event.
In your Page_Load event you are setting the datasource of the 2nd drop down, and thus the old values, and selected value, are reset and reloaded.
the code to loads values into the 2nd combo sould be in the ddlMyDropDown_Click event...I think it's the click event anyways.
Woka
Re: Postback and DropDownList problem [RESOLVED]
Thanks alot! That solved the probem.