Store ID from a dropdown list - c#

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

Related

.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 save dropdown-list Selected-Item as a session

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.

Dropdownlist date format

I am using a DataTable to populate a dropdownlist on my web form, as well as using a stored procedure to query the database. The list retrieves only one field from the database and will be used in conjunction with a gridview to view all reservations made on a specific date.
Everything works fine, except for the format of the date. Right now it is showing the date as well as hours, minutes, and seconds. I have tried using the DataFormatString property the the web form but no luck.
Webform:
<b>Please select a date:</b>
<asp:DropDownList ID="ddlDateSelection" runat="server" DataFormatString="{0:MM/dd/yyyy}"></asp:DropDownList>
<br />
<asp:Label ID="lblError" runat="server" CssClass="validate"></asp:Label>
code behind used to query database:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
loadDates();
}
protected void loadDates()
{
DataTable dates = new DataTable();
using (SqlConnection con = new SqlConnection(DBAccess.GetConnectionString()))
{
SqlCommand cmd = new SqlCommand("usp_sel_ReservationDates", con);
cmd.CommandType = CommandType.StoredProcedure;
try
{
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dates);
ddlDateSelection.DataSource = dates;
ddlDateSelection.DataTextField = "ReservationDate";
ddlDateSelection.DataBind();
}
catch (Exception ex)
{
lblError.Text = "Something bad has happened. Please try again.<br />Message: " + ex;
}
}
ddlDateSelection.Items.Insert(0, new ListItem("Please Select", "0"));
}
Any help would be greatly appreciated, as this is a learning project for myself. Thanks
Probably you need to refer to the correct property
<asp:DropDownList ID="ddlDateSelection" runat="server"
DataTextFormatString="{0:MM/dd/yyyy}">
</asp:DropDownList>
DropDownList properties
You can edit your SQL code to return only date
SELECT CONVERT (DATE, GETDATE())
 
RESULT: 2013-07-14

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();

accessing data of a GridView on button click

I am having a gridview with some columns and a template field column that contains a button and I want to call a procedure on button click, however I want to pass a value of a column to the procedure but I am getting an error, here is the action listener of the button: (column name in the gridview is team_ID)
error: Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
error line: int team_ID = Convert.ToInt32(Eval("team_ID"));
protected void Button1_Click(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("join_team", conn);
cmd.CommandType = CommandType.StoredProcedure;
int team_ID = Convert.ToInt32(Eval("team_ID"));
string email = Session["email"].ToString();
cmd.Parameters.Add(new SqlParameter("#team_ID", team_ID));
cmd.Parameters.Add(new SqlParameter("#myemail", email));
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
First, to handle a button what was clicked in an TemplateField, you'll want to subscribe to the RowCommand method:
<asp:GridView runat="server" ID="gv" OnRowCommand="yourMethod">
You can have multiple buttons in your grid and surmise which caused the click with the CommandName property. The code below shows this, as well as how to get the row of the button that was clicked, and retrieve other controls from that row so you can get their values.
<asp:TemplateField>
<ItemTemplate>
<asp:Button CommandName="yourButtonName" runat="server" />
Code Behind
protected void yourMethod(object sender, GridViewCommandEventArgs e) {
if (e.CommandName == "yourButtonName") {
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
TextBox someTextBox = row.FindControl("tb") as TextBox;
string textValue = someTextBox.Text;
}
}

Categories