ASP.net save dropdown-list Selected-Item as a session - c#

I want to save the selected item of a drop down list as a session but I am always getting the first result from the locations table.
ASP.net:
<div>
<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
</div>
C# (just getting the locations to the drop down list is working fine)
using(SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("select location_id, location_name from locations", con);
con.Open();
DropDownList1.DataTextField = "location_name";
DropDownList1.DataValueField = "location_id";
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataBind();
}
The problem: always retrieving the first location from the db.
protected void btnGo_Click(object sender, EventArgs e)
{
string location;
Session["userLocation"] = DropDownList1.SelectedItem;
location = Session["userLocation"].ToString();
}
Thanks for the helpers.

You should do the binding only if Page.IsPostBack equals False.
The reason might be that your data operation for filling the DropDownList1 is called every time the page is requested. It is also possible that this data retrieval happens before btnGo_Click is executed and as a result the SelectedIndex will reset to 0 which is the first location in your case.

Related

How do I keep my items in asp:dropdownlist after !Page.IsPostBack?

I am loading a list of value/text into a asp:dropdownlist by calling a stored procedure. I populate the dropdownlist on the PageLoad method inside a !Page.IsPostBack block like so:
if (!Page.IsPostBack)
{
GetDropDownLists();
DataBind();
}
And this is my code implementation for the backend:
protected void GetDropDownLists()
{
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("get_articletype", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
xArticleTypeList.Items.Clear();
xArticleTypeList.Items.Insert(0, new ListItem("- Select.. -", "0"));
xArticleTypeList.SelectedIndex = 0;
xArticleTypeList.DataSource = dt;
xArticleTypeList.DataValueField = "TypeValue";
xArticleTypeList.DataTextField = "TypeName";
xArticleTypeList.DataBind();
}
If my code isn't inside a !Page.IsPostBack block, after I click my save button the default value will always be the first item of the dropdownlist. But once I put my code inside the !Page.IsPostBack block my dropdownlist is empty. For reference here is the frontend implementation of my asp:dropdownlist.
<asp:DropDownList ID="xArticleTypeList" EnableViewState="true" AutoPostBack="true" CssClass="form-control" runat="server" />
I understand that there are other topics that cover this question, but none of the proposed solutions worked for me. Thanks you in advance for your inputs.
Your problem is that you inserting the blank please select row BEFORE you bind. As a result, when you bind, you are blowing out the drop down.
Try it this way:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmd = new SqlCommand("get_articletype", conn))
{
DataTable dt = new DataTable();
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
dt.Load(cmd.ExecuteReader());
xArticleTypeList.DataSource = dt;
xArticleTypeList.DataValueField = "TypeValue";
xArticleTypeList.DataTextField = "TypeName";
xArticleTypeList.DataBind();
xArticleTypeList.Items.Insert(0, new ListItem("- Select.. -", "0"));
}
}
}
And GET RID of your extra call re-bind You have this:
GetDropDownLists();
DataBind(); <--- remove unless you need, or execute BEFORE the GetDropDownList()
So move your add/insert blank row to the drop down to AFTER the drop down data bind.
And REMOVE your DataBind() - you don't need it, and if for some reason you do, then move the DataBind() to before your load of the GetDropDownLists() - but my guess is that you just tossed that in the hope of making this work, and it going to cause the combo box to re-select - so remove unless you give a REALL GOOD HIGH quality outline and narrative as to why you have the DataBin() command there - (but as as noted, if you really, but really really do need to execute that DataBind() command - move it to before the load of the combo).
So, add the blank row after

Storing data into SQL Server database and generating html div dynamically and display sql database content c#

This button will store what I typed in my textbox into my SQL Server database:
string aOption = Request.Form["option"].ToString();
string ATitle = Request.Form["title"].ToString();
string Adesc = Request.Form["desc"].ToString();
con = new SqlConnection(constr);
con.Open();
cmd = new SqlCommand("INSERT INTO Thread (shareORask, Thread_Title, Thread_Description) VALUES (#shareORask, #Thread_Title, #Thread_Description)", con);
cmd.Parameters.AddWithValue("#shareORask", askORshare_Selected);
cmd.Parameters.AddWithValue("#Thread_Title", AS_Title);
cmd.Parameters.AddWithValue("#Thread_Description", AS_desc);
cmd.ExecuteNonQuery();
con.Close();
Next, I wanted to dynamically generate div and display database content. I did it in Page Load.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Thread", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
reptater.DataSource = ds;
reptater.DataBind();
con.Close();
}
<asp:Repeater runat="server" ID="reptater">
<ItemTemplate>
<div><%#Eval("Thread_Description") %></div>
</ItemTemplate>
It works but when I submit my input into the textbox. I'm not able to get data shown in the dynamically created. It only works when i refresh the page.
However, duplicate data will be added into my SQL Server database, how do I solve this?
I'm assuming that the button code is in a method called something like MyButton_Click(object sender, EventArgs e).
The button click event is a "Control event" and these happen after the Page_Load event in the page life cycle. To insert into the database during the click event and render the div in one page cycle you would need to render the div in one of the later events, probably the Page_PreRender event.

Store ID from a dropdown list

I have been working on this for a while but seems I can't figure this out. So I have a dropdown list called ddStudent where the textField value is from a sql table I made called 'Student from a column called 'firstName'. Now I used the 'studentID' as the value field.
Here is where I am having the issue. I want to execute my stored procedure that takes studentID as a paramter but I don't understand how to store the actual student ID into the parameter.
Here is what I have so far-
protected void btnRegister_Click(object sender, EventArgs e)
{
int selValClass = Convert.ToInt32(ddClassNames.SelectedValue);
int selValStudent = Convert.ToInt32(ddStudents.SelectedValue);
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("procRegStudent", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#studentID", selValStudent);
cmd.Parameters.AddWithValue("#classID", selValClass);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
and here is my code for databinding-
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT studentID, firstName, lastName, ssn, address, city, state, zip FROM Student ", con);
con.Open();
ddStudents.DataSource = cmd.ExecuteReader();
ddStudents.DataTextField = "firstName";
ddStudents.DataValueField = "studentID";
ddStudents.DataBind();
}
Now my question is, is there a way I can store the actual studentID from the dropdown list when I select it? For some reason when I do this, the page reloads and selects the first student ID for a student I didn't select. I'm not exactly sure what's going on.
Thanks.
EDIT-
I wanted to make sure I clarify-
I have 3 students in my student dropdown. When I select student 3 (with student ID 3), the first student in the dropdownlist is being passed as the parameter and I can't tell why.
This issue is logical for Dropdownlist control because your dropdownlist missed to have a defaultitem to render when it comes back from the server.The soultion is very simple you should add a default list item to be the default value when the page loads
Here I made a simple example to how can we solve this issue :
in the Page.aspx:
<asp:DropDownList ID="ddStudents" runat="server" DataTextField = "firstName" DataValueField = "studentID" AppendDataBoundItems="true">
<asp:ListItem Text="===Select Student===" Value="0"></asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnRegister" runat="server" Text="Register" OnClick="btnRegister_Click" />
<asp:Label ID="lblMessage" runat="server" Text="Label"></asp:Label>
in the Page.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDown();
}
}
private void BindDropDown()
{
DataTable dt = new DataTable();
dt.Columns.Add("studentID", typeof(int));
dt.Columns.Add("firstName", typeof(string));
dt.Rows.Add(dt.NewRow());
dt.Rows[0]["studentID"] = 1;
dt.Rows[0]["firstName"] = "Markus";
dt.Rows.Add(dt.NewRow());
dt.Rows[1]["studentID"] = 2;
dt.Rows[1]["firstName"] = "Arthur";
ddStudents.DataSource = dt;
ddStudents.DataBind();
}
protected void btnRegister_Click(object sender, EventArgs e)
{
if (ddStudents.SelectedIndex > 0)
{
lblMessage.Text = String.Format("You selected {0} with Number : {1}", ddStudents.SelectedItem.Text,ddStudents.SelectedValue);
}
}
Hint: I marked the dropdownlist AppendDataBoundItems Property to true just to tell the dropdownlist to include the default listitem when the data binded..
I hope my code helps you solving your problem :)
Try with this
int selValStudent = int.Parse(this.ddStudents.SelectedValue);
and put your
BindDropDown();
into your postback

.NET web form drop down list resets on postback

I've searched through a heap of similar questions and done a bit of googling but I cannot find the answer to my problem...
I would like to have a drop down list that is populated by categories in a database...upon selecting a category and hitting submit, a gridview is populated with all the items in that category.
Now, everything works, except whenever I select anything in the category drop down box, it resets straight away to the first selection. So I'm unable to submit any value other than the first to the gridview. I am using autopostback on this item. I have tried to use appenddatabounditems too but that just populated the list with more and more of the same entries...
I would love if anyone could tell me how I can just get the dropdownlist to hold its position after postback?
Selected Category:
<asp:DropDownList ID="ddlCategory" runat="server" AutoPostBack="True" ViewStateMode="Enabled">
</asp:DropDownList>
<asp:Button ID="buttonCategorySubmit" runat="server" OnClick="buttonCategorySubmit_Click" Text="Submit" />
<br />
</div>
<asp:GridView ID="CategoryGridView" runat="server">
</asp:GridView>
<br />
protected void Page_Load(object sender, EventArgs e)
{
PopulateCategorySelection();
}
public void PopulateCategorySelection()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnString"]);
SqlCommand cmd = new SqlCommand("AllCategories", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlDataReader ddlValues = cmd.ExecuteReader();
ddlCategory.DataSource = ddlValues;
ddlCategory.DataValueField = "CategoryID";
ddlCategory.DataTextField = "Title";
ddlCategory.DataBind();
conn.Close();
}
protected void buttonCategorySubmit_Click(object sender, EventArgs e)
{
PopulateCategoryTable();
}
public void PopulateCategoryTable()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["Connstring"]);
SqlCommand cmd = new SqlCommand("SelectCategory", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Selected", ddlCategory.SelectedItem.Value);
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
adapter = new SqlDataAdapter(cmd);
adapter.Fill(ds);
conn.Close();
CategoryGridView.DataSource = ds.Tables[0];
CategoryGridView.DataBind();
conn.Close();
}
I literally just worked it out everyone...For anyone that has the same issue, you need to check in the page_load method whether the page is loading because a new page is being generated, or information is just being posted-back for the user. If its just postback, we dont want to populate the category dropdown box again. So we use the IsPostBack object in the page_load method, like this:
if (!IsPostBack)
{
PopulateCategorySelection();
}

ASP.net Drop Down List Populating More Than Once on Refresh

I'm sorry for the trivial question, but I cannot find info about this on Google, or in my reference books, which accurately describes/solves my problem.
I have some DropDownList controls on a page, that I am populating with info from a SQL table. When the page is refreshed, the DropDownLists don't lose their old values, but instead get the same values added to them all over again, so now they are double populated. The functionality all still works the same, but it makes the DropDownList controls look less neat and obviously is unwanted.
<asp:DropDownList ID="DropDownList2" runat="server" OnLoad="LoadDutchessSubjects"
AppendDataBoundItems="true">
The LoadDutchessSubjects function in my code behind just grabs all records from the SQL table and loads them into the DDL:
public void LoadDutchessSubjects(object sender, EventArgs e)
{
string connectionString = SqlHelperClass.ConnectionString;
DataTable subjects = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM cfhudson_counties ORDER BY County", con);
adapter.Fill(subjects);
DropDownList2.DataSource = subjects;
DropDownList2.DataTextField = "County";
DropDownList2.DataValueField = "County";
DropDownList2.DataBind();
}
catch (Exception ex)
{
DropDownList2.Items.Insert(0, new ListItem("<ERROR: Occured in populating.>", "1"));
}
con.Close();
}
//Overall.Items.Insert(0, new ListItem("<Select Subject>", "0")); //(dev test)
}
Is there something I can do in the Code Behind to prevent this from happening? Does this have to do with ASP.net state and refreshing/what's going on server side? Maybe we can turn this question into a more useful and general explanation of why this is happening in the first place, because I evidently don't understand some important thing about ASP.net here.
do not reload the items on postbacks. they are persisted in viewstate
public void LoadDutchessSubjects(object sender, EventArgs e)
{
if (IsPostback)
return;
string connectionString = SqlHelperClass.ConnectionString;
DataTable subjects = new DataTable();

Categories