How to keep Dropdown value same after refresh the page - c#

I am using three dropdowns, in first dropdown i bind data from sql. In second dropdown i also bind data from sql and the third dropdown is bind according to second dropdown so in second dropdown there is autopostback property true. I have one search button which fetch the result from database on click.
I want to keep all the Dropdownlist value same after my result show on the page. One thing i did is, at the time of button click i make the session and check it at page load when it is not null bind the dropdown value. Till this point it is working fine i am able to bind prevoius selected values.
This is in my master page and result are display in result page, which is using this masterpage.
aspx :
<asp:DropDownList ID="dd_category" runat="server" AutoPostBack="True"
onselectedindexchanged="dd_category_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="dd_subcategory" runat="server" ></asp:DropDownList>
<asp:Button ID="but_go" runat="server" Text="Go" onclick="but_go_Click"/>
page load :
if (!IsPostBack)
{
FillStates();
FillCategory();
}
if (Session["state"] != null)
{
dd_state.SelectedValue = (string) Session["state"];
}
aspx.cs :
private void FillStates()
{
SqlCommand cmd = new SqlCommand("sps_bindcountrystate", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#flag", 2);
cmd.Parameters.AddWithValue("#CountryID", 1);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
dd_state.DataSource = objDs.Tables[0];
dd_state.DataTextField = "s_name";
dd_state.DataValueField = "s_id";
dd_state.DataBind();
dd_state.Items.Insert(0, "Select State");
}
}
protected void dd_category_SelectedIndexChanged(object sender, EventArgs e)
{
int CategoryID = Convert.ToInt32(dd_category.SelectedValue);
FillSubCategory(CategoryID);
}
private void FillCategory()
{
SqlCommand cmd = new SqlCommand("sps_bindcategory", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#flag", 1);
cmd.Parameters.AddWithValue("#CategoryID", 0);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
dd_category.DataSource = objDs.Tables[0];
dd_category.DataTextField = "category_name";
dd_category.DataValueField = "category_id";
dd_category.DataBind();
dd_category.Items.Insert(0, "Select Category");
dd_subcategory.Items.Insert(0, "Select Sub-Category");
}
}
private void FillSubCategory(int CategoryID)
{
SqlCommand cmd = new SqlCommand("sps_bindcategory", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#flag", 2);
cmd.Parameters.AddWithValue("#CategoryID", CategoryID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
dd_subcategory.DataSource = objDs.Tables[0];
dd_subcategory.DataTextField = "subcategory_name";
dd_subcategory.DataValueField = "subcategory_id";
dd_subcategory.DataBind();
dd_subcategory.Items.Insert(0, "Select Sub-Category");
}
}
protected void but_go_Click(object sender, EventArgs e)
{
Session["state"] = dd_state.SelectedValue;
Session["category"] = dd_category.SelectedValue;
Session["subcategory"] = dd_subcategory.SelectedValue;
Response.Redirect("Results.aspx");
}
Now problem is when i again choose some different value in first dropdown and try to choose different value in second dropdown, the second dropdown is having postback so it refreshes page and according to session state it changes my first dropdown value back to prevoius one.
Tell me what to do so that new selected value does'nt change due to page refresh.

Related

C#/ASP.NET gridview databind dropdownlist index changed

I am new to .net world and I could not figure out why the below code does not work. I have a dropdownlist populated with DEPARTMENT_NAME and value as DEPARTMENT_ID. I have a gridview which populates the employees data based on department_id selected from dropdown list. I have written the following code but the gridview is not populating. Can someone please help what I am doing wrong here.
protected void ddDepartments_SelectedIndexChanged(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["myCon"].ConnectionString;
OracleConnection oConn = new OracleConnection(connStr);
oConn.Open();
string SqlText = "Select * from employees where department_id = :department_id";
OracleCommand cmd = new OracleCommand(SqlText, oConn);
cmd.CommandType = CommandType.Text;
OracleParameter p_department_id = new OracleParameter();
p_department_id.OracleDbType = OracleDbType.Varchar2;
p_department_id.Value = ddDepartments.SelectedItem.Value;
cmd.Parameters.Add(p_department_id);
OracleDataAdapter adapter = new OracleDataAdapter(cmd);
DataTable dtEmployees = new DataTable();
adapter.Fill(dtEmployees);
gvEmployees.DataSource = dtEmployees;
gvEmployees.DataBind();
dtEmployees.Dispose();
adapter.Dispose();
cmd.Dispose();
oConn.Close();
oConn.Dispose();
}
You need to use a Session variable to persist the gridView datasource on Postback which is sent by the dropdownlist.
So right after:
gvEmployees.DataSource = dtEmployees;
gvEmployees.DataBind();
Add:
Session("gvDS") = gvEmployees.DataSource;
In the page Load() method:
if (Session["gvDS"] != null && IsPostBack)
{
gvEmployees.DataSource = Session["gvDS"];
gvEmployees.DataBind();
}
else
BindGridView(); // you initial gvEmployees binding method
Please see my answer #:
Asp.net Web Forms GridView Dynamic Column Issue

Populating a dropdownlist using a SQL Connection

I have a DropdownList in asp.net form that needs populating through SQL. I'm using a ScriptManager in my Page_Load()and due to this dropdownList doesn't get populated. I need to use the ScriptManager since I'm using a AjaxCalendarExtender.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = dba.getNames();
ddNames.DataSource = ds.Tables["EMPLOYEE"].DefaultView;
ddNames.DataTextField = "Username";
ddNames.DataValueField = "Username";
ddNames.DataBind();
}
if (ScriptManager.GetCurrent(Page) == null)
{
Page.Form.Controls.AddAt(0, new ScriptManager());
}
}
getNames() function in DB_Access.cs
public DataSet getNames()
{
if (conn.State.ToString() == "Closed")
{
conn.Open();
}
SqlCommand newCmd = conn.CreateCommand();
newCmd.Connection = conn;
newCmd.CommandType = CommandType.Text;
newCmd.CommandText = "Select DISTINCT Username from dbo.EMPLOYEE";
SqlDataAdapter da = new SqlDataAdapter(newCmd);
DataSet ds = new DataSet();
da.Fill(ds, "EMPLOYEE");
conn.Close();
return ds;
}
I found the answer to be in the Script Manager in aspx page instead of Creating the it Dynamically in the Page Load event.
<asp:ScriptManager ID="ScriptManager1" runat="server" />

Asp.net dropdownlist getselectedvalue doesnt return anything

Im having a problem with a dropdownlist in asp.net.
When i try to get the selected value of the list it doesnt return anything.
The aspx looks like this
<div class="form-signin">
<h2 class="form-signin-heading">Slet besked</h2>
<div class="input-group">
<span class="input-group-addon">ID</span>
<asp:dropDownList runat="server" CssClass="form-control" ID="sletBox" />
</div>
<asp:Button runat="server" CssClass="btn btn-lg btn-block btn-danger" Text="Slet" OnClick="Slet" />
</div>
And the kode behind it looks like this
protected void Slet(object sender, EventArgs e)
{
Response.Write("wow der sker noget");
Response.Write(sletBox.SelectedItem.Value);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection myconnection = new SqlConnection();
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder();
myconnection.ConnectionString = constr;
myconnection.Open();
string sqlcmd = "DELETE FROM messages WHERE messageid = '" + sletBox.SelectedValue.ToString() + "'";
SqlCommand messageDelete = new SqlCommand(sqlcmd, myconnection);
messageDelete.ExecuteNonQuery();
myconnection.Close();
}
The only thing that works is the response.write(wow) not the selectedvalue
EDIT:
The page_load code
protected void Page_Load(object sender, EventArgs e)
{
DataTable subjects = new DataTable();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT messageId, messageText FROM messages", con);
adapter.Fill(subjects);
sletBox.DataSource = subjects;
sletBox.DataTextField = "messageText";
sletBox.DataValueField = "messageId";
sletBox.DataBind();
}
sletBox.Items.Insert(0, new ListItem("Vælg besked", ""));
}
You're doing the databinding for the dropdownlist in the pageload and not checking for IsPostBack. As a result when the button triggers the clik it resets the selectedvalue. Change you PageLoad like below
if (!IsPostBack)
{
DataTable subjects = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT messageId, messageText FROM messages", con);
adapter.Fill(subjects);
sletBox.DataSource = subjects;
sletBox.DataTextField = "messageText";
sletBox.DataValueField = "messageId";
sletBox.DataBind();
}
sletBox.Items.Insert(0, new ListItem("Vælg besked", ""));
}
As a side note as Mathew suggested try adding using to better manage your connections objects so it's properly disposed after it's been used.
You must load your DropDownList data only if IsPostBack is false, otherwise you'll be reloading the control every postback. Once the data bound to the control is changed, the selected value is lost as well. Keep in mind that the Page_Load event is fired when the SelectedIndexChanged event occurs.
if(!Page.IsPostBack)
{
DataTable subjects = new DataTable();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT messageId, messageText FROM messages", con);
adapter.Fill(subjects);
sletBox.DataSource = subjects;
sletBox.DataTextField = "messageText";
sletBox.DataValueField = "messageId";
sletBox.DataBind();
}
sletBox.Items.Insert(0, new ListItem("Vælg besked", ""));
}

Dynamically Binded Dropdownlist always taking first value when get by ddl.SelectedValue

I have a dynamically bind dropdownlist from which i want insert selected value in a table. But when I submit the form it is taking the very first value of dropdownlist not the selected value and inserts the first value of the dropdownlist.
Here is my code
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(connection.getConnection()))
{
string sqlGetClass = "select pk_classID,brachName+'-'+classYear as classInfo from tbl_studentClass";
SqlCommand cmdGetClass = new SqlCommand(sqlGetClass, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdGetClass);
DataSet ds = new DataSet();
da.Fill(ds);
ddlClass.DataSource = ds;
ddlClass.DataTextField = "classInfo";
ddlClass.DataValueField = "pk_classID";
ddlClass.DataBind();
ddlClass.Items.Insert(0, new ListItem("--SELECT--", ""));
conn.Close();
}
}
protected void btnStdRegisterSubmit_Click(object sender, EventArgs e)
{
string dateOfBirth = txtStdDOBYear.Text+"-"+ddlStdDOBMonth.SelectedValue + "-"+txtStdDOBDate.Text;
using (SqlConnection conn = new SqlConnection(connection.getConnection()))
{
string sqlInsertStd = "Insert into tbl_studentRegistration (firstName,surname,studentUsername,studentPassword,studentDOB,studentGender,studentMobile,class) values(#firstName,#surname,#studentUsername,#studentPassword,#studentDOB,#studentGender,#studentMobile,#class)";
conn.Open();
SqlCommand cmdInsertStd = new SqlCommand(sqlInsertStd, conn);
cmdInsertStd.Parameters.AddWithValue("#firstName", txtStdFirstName.Text);
cmdInsertStd.Parameters.AddWithValue("#surname", txtStdSurname.Text);
cmdInsertStd.Parameters.AddWithValue("#studentUsername", txtStdUsername.Text);
cmdInsertStd.Parameters.AddWithValue("#studentPassword", txtStdPassword.Text);
cmdInsertStd.Parameters.AddWithValue("#studentDOB", DateTime.Parse(dateOfBirth).ToString("yyyy-MM-dd"));
cmdInsertStd.Parameters.AddWithValue("#studentGender", ddlStdGender.SelectedValue.ToString());
cmdInsertStd.Parameters.AddWithValue("#studentMobile", txtStdMobile.Text);
cmdInsertStd.Parameters.AddWithValue("#class", ddlClass.SelectedValue);
cmdInsertStd.ExecuteNonQuery();
conn.Close();
txtStdFirstName.Text = "";
txtStdSurname.Text = "";
txtStdUsername.Text = "";
ddlClass.SelectedValue = "";
txtStdPassword.Text = "";
txtStdConfirmPassword.Text = "";
ddlStdDOBMonth.SelectedValue = "";
txtStdDOBDate.Text = "";
txtStdDOBYear.Text = "";
ddlStdGender.SelectedValue = "";
txtStdMobile.Text = "";
Response.Redirect("~/index.aspx");
}
}
Please help I am new to asp.net
Problem : You are adding the items into DropDownList for every Page request as your code added in Page_Load EventHandler. so the DropDownList always contain the first item as selectedItem even though you selected different item.
Solution: You need to append the items into DropDownList only when page is Loaded but not on every PostBack request.
You can use Page.IsPostBack to identify wether page request is PostBack request or not.
Try This:
if(!Page.IsPostBack)
{
using (SqlConnection conn = new SqlConnection(connection.getConnection()))
{
string sqlGetClass = "select pk_classID,brachName+'-'+classYear as
classInfo from tbl_studentClass";
SqlCommand cmdGetClass = new SqlCommand(sqlGetClass, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdGetClass);
DataSet ds = new DataSet();
da.Fill(ds);
ddlClass.DataSource = ds;
ddlClass.DataTextField = "classInfo";
ddlClass.DataValueField = "pk_classID";
ddlClass.DataBind();
ddlClass.Items.Insert(0, new ListItem("--SELECT--", ""));
conn.Close();
}
}
Page_Load executes every time the page posts back, such as when you click your submit button. You should put your using stateme3nt in a
conditional:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
using (SqlConnection conn = new SqlConnection(connection.getConnection()))
{
string sqlGetClass = "select pk_classID,brachName+'-'+classYear as classInfo from tbl_studentClass";
SqlCommand cmdGetClass = new SqlCommand(sqlGetClass, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdGetClass);
DataSet ds = new DataSet();
da.Fill(ds);
ddlClass.DataSource = ds;
ddlClass.DataTextField = "classInfo";
ddlClass.DataValueField = "pk_classID";
ddlClass.DataBind();
ddlClass.Items.Insert(0, new ListItem("--SELECT--", ""));
conn.Close();
}
}
}
So that your list is not repopulated every time you click your submiit button.
(you should consider putting the list population code in a separate method)

To Display controls based on the dropdownlist selected item?

For Dropdownlist items i have written the following code:
protected void dropdowndatasrc()
{
con = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
string command = "select eventname from Events";
cmd = new OleDbCommand(command);
dataadapter = new OleDbDataAdapter(command, con);
DataSet dataset = new DataSet();
con.Open();
DataTable dt = new DataTable("PayEvent");
dataadapter.Fill(dt);
DropDownList4.DataSource = dt;
DropDownList4.DataTextField = dt.Columns[0].ToString();
// DropDownList4.DataValueField = dt.Columns[0].ToString();
DropDownList4.DataBind();
}
I have to display controls based on the value of the dropdownlist (in the access database there is a column named payevent in that it has Yes/No datatype if the selected item in the database have 'yes' means display controls if not no controls must be displayed)
I have tried this code but not worked
protected void DropDownList4_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox11.Text = DropDownList4.SelectedItem.Text;
con = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
string query = "select payevent from Events where eventname=#dropdownlist";
con.Open();
//string query="select payevent from Events";
cmd = new OleDbCommand(query, con);
cmd.Parameters.Add("#dropdownlist", selectedtext);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string value = reader.GetValue((0)).ToString();
TextBox11.Text = value.ToString();
if (value == "True" || value == "true")
{ pnl.Visible = false; }
else if (value == "False" || value == "false")
{ pnl.Visible = true; }
}
}
the table structure as follows:
**eventname payevent**
Work Shop Yes
emsisoft workshop Yes
ECE No
CSE No
Need help !!!
The usually issue is that you make databind on the dropdownlist again after the post back and the value is lost. So on page load, do not call the dropdowndatasrc on post back as:
if(!IsPostBack)
dropdowndatasrc();
same issue: Dropdown list not selecting value asp.net

Categories