DropDownList losing data on page submission or on page postback

Q.”Why doesn’t my DropDownList keep it’s Selection?”
Q.”Why is the selectedindex for my (ASP.Net control) always turning up a -1?”

Answer:

The problem occurs due to not checking of Page Post Back on Page Load

private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
BindDropDownList1();
}
}

[Note: you may be missing if(!IsPostBack) line on page load.
!Page.IsPostBack read as Not Page is Page Back prevents on each subsequent loading of the page, the control doesn’t go through the redundant action of re-loading the control. It loads it only once, at the initial page load and the selection which was made by the end user is maintained throughout the post back.
BindDropDownList1() is the method created by You to fill your DropDownList box.]
Below is the BindDopDownList1 method that you have written in your page or in any other class.

private void BindDropDownList1()
{
string strConn = “server=(local);uid=UID;pwd=PWD;database=Northwind”;
string MySQL = “Select LastName from Employees”;
SQLConnection MyConn =new SQLConnection(strConn);
SQLDataReader objDR ;
SQLCommand Cmd =new SQLCommand(MySQL, MyConn);
MyConn.Open();
objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection);
DropDownList.DataSource = objDR;
DropDownList.DataBind();
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: