Populate drop down list from SQL Server database - c#

I have an ASPX page that has a drop down on it.
<div>
<p>Pick a customer to show their order(s)</p>
<asp:DropDownList ID="customerSelect" AutoPostBack="true" runat="server" OnSelectedIndexChanged="customerSelect_SelectedIndexChanged"></asp:DropDownList>
</div>
I want the options in the drop down to be populated from a database of customer names.
Here is what my database looks like
Here is my code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populateDropDown();
customerSelect_SelectedIndexChanged(null, null);
}
}
public void populateDropDown()
{
SqlCommand cmd = new SqlCommand("SELECT * FROM [Orders]", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
cmd.Connection.Open();
SqlDataReader ddlValues;
ddlValues = cmd.ExecuteReader();
customerSelect.DataSource = ddlValues;
customerSelect.DataValueField = "OrderID";
customerSelect.DataTextField = "CustomerName";
cmd.Connection.Close();
cmd.Connection.Dispose();
}
I've used this code before. So I must be missing something simple but I'm not sure what it is.
EDIT
I am getting no errors. The code compiles. But the drop down list remains blank.

Well, I think you forget to bind your dropdownlist like;
customerSelect.DataBind();
And use using statement to dispose your SqlCommand, SqlConnection and SqlDataReader instead of calling .Dispose() method manually.
using(SqlConnection con = new SqlConnection(connString))
using(SqlCommand cmd = con.CreateCommand())
{
...
...
using(SqlDataReader ddlValues = cmd.ExecuteReader())
{
...
}
}

Related

I am trying to use a selectedItem from a drop down menu in my SQL statement to populate a textbox in C# asp.net

So far everything loads without error, and the SQL calls will be replaced with more secure stored procedures once everything is working. When I select a furnace from the drop down down menu, it should pass to the method and fill the textbox with the run number. But when I select anything, it only goes back to the first index 10A. I have also coded that index 0 should say "Select Furnace" but that is also not showing, only the first index. Is there any suggestions on how to grab a selected Index and populate a textbox from a SQL query?
<asp:Content ID="BodyContent" ContentPlaceHolderID="BodyPlaceHolder" runat="server">
<center>
<table style="text-align:left">
<tr>
<td align="right">
<asp:Label ID="FurnaceID" Text="JUMP TO FURNACE : " runat="server" />
</td>
<td></td>
<td>
<asp:DropDownList ID="FurnID" runat="server" AutoPostBack ="true"
onselectedindexchanged="FurnID_SelectedIndexChanged" Width="150px">
<asp:ListItem Text="Select Furnace" Value = "0" />
</asp:DropDownList>
Behind The Code:
LoadList(); is called in the page_load event
public void LoadList()
{
SqlCommand cmd = new SqlCommand("SELECT * FROM [Furnace]", new SqlConnection(ConfigurationManager.ConnectionStrings["FurnaceDeckConnectionString"].ConnectionString));
cmd.Connection.Open();
SqlDataReader Furns;
Furns = cmd.ExecuteReader();
FurnID.DataSource = Furns;
FurnID.DataValueField = "Furnaceno";
FurnID.DataTextField = "Furnaceno";
FurnID.DataBind();
cmd.Connection.Close();
cmd.Connection.Dispose();
}
When the index is changed this method is called:
protected void FurnID_SelectedIndexChanged(object sender, EventArgs e)
{
if (IsPostBack)
{
String selectedFurn = "";
ListItem selectFurn = FurnID.Items.FindByText(selectedFurn);
LoadFurnDetails(selectedFurn);
}
}
public void LoadFurnDetails(String F)
{
String selectF = F;
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("SELECT * FROM [Furnace Run Data Table] Where Furnace = 'selectF' and Completed = 0 ", new SqlConnection(ConfigurationManager.ConnectionStrings["FurnaceDeckConnectionString"].ConnectionString));
cmd.Connection.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
lblFurnId.Text = dt.Rows[0]["runno"].ToString();
}
cmd.Connection.Close();
cmd.Connection.Dispose();
}
This part
if (IsPostBack)
{
String selectedFurn = "";
ListItem selectFurn = FurnID.Items.FindByText(selectedFurn);
LoadFurnDetails(selectedFurn);
}
... is defining a string "selectedFurn" as an empty string.
Then you try to find an Item by text with this empty string. I'd assume, that this Item doesn't exist... Anyway, you do not use the found ListItem, but just pass over the empty string...
You most propably are interested in the currently selected item and load details for this special item, aren't you? Try to find the ListItem with .Selecteditemrather than to pass the empty string as parameter in LoadFurnDetails...
The next problem is here:
SqlCommand cmd = new SqlCommand("SELECT * FROM [Furnace Run Data Table] Where Furnace = 'selectF' and Completed = 0 " ...
You think that you are passing in the variable "selectF" but you are searching for a hardcoded "selectF" actually... You must replace "selectF" by the actual content of the variable.
Again a no-go: You should always use parameters and do not concatenate a string command!
#Schnugo, you gave the clues, and here is some code help if others are having this same problem. This solved it for me.
if (IsPostBack)
{
String selectFurn = FurnID.SelectedItem.Text.ToString();
SqlConnection m_sqlConnection;
string m_connectionString = ConfigurationManager.ConnectionStrings["FurnaceDeckConnectionString"].ConnectionString;
using (m_sqlConnection = new SqlConnection(m_connectionString))
{
using (SqlCommand cmd = new SqlCommand("Load_Furn"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#selectFurn", selectFurn);
cmd.Connection = m_sqlConnection;
m_sqlConnection.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
A datareader reads the data row by row and is used with a while statement to read the rows. You will have to use a SqlDataAdapter to fill a dataset that you can use as a datasource for the drop down menu. The default value should also be added to that dataset, otherwise it will not be shown after you set the datasource as you noticed.
Load your data into a table, then use your table as the data.
Try this out:
public void LoadList()
{
var table = new System.Data.DataTable("Furnaceno");
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["FurnaceDeckConnectionString"].ConnectionString))
{
conn.Open();
using (var cmd = new SqlCommand("SELECT * FROM [Furnace]", conn))
{
table.Load(cmd.ExecuteReader());
}
}
FurnID.DataSource = table.DefaultView;
FurnID.DataValueField = "Furnaceno";
FurnID.DataTextField = "Furnaceno";
FurnID.DataBind();
}

why listbox2 still empty?

I can not find where is the problem, when I put while loop as a comment it works,after while loop we can not read from sqldatareader more?
listbox2 still empty!
public partial class exTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
string sql = "select employeeid,firstname,lastname from employees";
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
string item;
ListBox1.Items.Clear();
while (reader.Read())
{
item =reader.GetString(1) + reader.GetString(2);
ListBox1.Items.Add(item);
}
ListBox2.DataSource = reader;
ListBox2.DataValueField = "employeeId";
ListBox2.DataTextField = "firstname";
ListBox2.DataBind();
reader.Close();
con.Close();
}
}
You cannot use the reader again.
From the MSDN Doc
Provides a way of reading a forward-only stream of rows from a SQL Server database.
You can read one row at a time, but you cannot go back to a row once you've read the next row.
What you have to do is you have to create a list of an object (e.g. employee object) that contains employeeId, firstname, lastname. Fill the list and assign it as a source for list2 or something similar.

ASP.NET C# update query not working

I am working on one project for the university and I want to say that I am pretty new in asp.net.
Please find below the code that I am experiencing problems with. The problem is that the update function is not working. In the page load I have some select queries and I load a data from the database into some textareas and textfields. This is working fine - it loads the sample data that I have added manually in my database.
I have buttons that should update the database on click.
This is the code for the buttons:
<a id="A1" class="button" onserverclick="box1_Click" runat="server">
<span>Запази полето <img src="notification-tick.gif" width="12" height="12" /></span>
</a>
This is the code behind:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class admin_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Loading the data from the database
string DatabaseConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["proekt"].ConnectionString;
string sql1_title = "SELECT title FROM home WHERE id=1";
string sql1_image = "SELECT image FROM home WHERE id=1";
string sql1_text = "SELECT text FROM home WHERE id=1";
string sql2_title = "SELECT title FROM home WHERE id=2";
string sql2_image = "SELECT image FROM home WHERE id=2";
string sql2_text = "SELECT text FROM home WHERE id=2";
string sql3_title = "SELECT title FROM home WHERE id=3";
string sql3_image = "SELECT image FROM home WHERE id=3";
string sql3_text = "SELECT text FROM home WHERE id=3";
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
//box1 data load
SqlCommand cmd1_title = new SqlCommand(sql1_title, conn);
conn.Open();
box1_title.Text = (string)cmd1_title.ExecuteScalar();
conn.Close();
SqlCommand cmd1_image = new SqlCommand(sql1_image, conn);
conn.Open();
box1_img.Text = (string)cmd1_image.ExecuteScalar();
conn.Close();
SqlCommand cmd1_text = new SqlCommand(sql1_text, conn);
conn.Open();
box1_text.InnerText = (string)cmd1_text.ExecuteScalar();
conn.Close();
//box2 data load
SqlCommand cmd2_title = new SqlCommand(sql2_title, conn);
conn.Open();
box2_title.Text = (string)cmd2_title.ExecuteScalar();
conn.Close();
SqlCommand cmd2_image = new SqlCommand(sql2_image, conn);
conn.Open();
box2_img.Text = (string)cmd2_image.ExecuteScalar();
conn.Close();
SqlCommand cmd2_text = new SqlCommand(sql2_text, conn);
conn.Open();
box2_text.InnerText = (string)cmd2_text.ExecuteScalar();
conn.Close();
//box3 data load
SqlCommand cmd3_title = new SqlCommand(sql3_title, conn);
conn.Open();
box3_title.Text = (string)cmd3_title.ExecuteScalar();
conn.Close();
SqlCommand cmd3_image = new SqlCommand(sql3_image, conn);
conn.Open();
box3_img.Text = (string)cmd3_image.ExecuteScalar();
conn.Close();
SqlCommand cmd3_text = new SqlCommand(sql3_text, conn);
conn.Open();
box3_text.InnerText = (string)cmd3_text.ExecuteScalar();
conn.Close();
}
}
protected void box1_Click(object sender, EventArgs e)
{
string DatabaseConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["proekt"].ConnectionString;
string sql1 = "UPDATE home SET title=#title, image=#image, text=#text WHERE Id=1";
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd2 = new SqlCommand(sql1, conn);
cmd2.Parameters.AddWithValue("#title", box1_title.Text);
cmd2.Parameters.AddWithValue("#image", box1_img.Text);
cmd2.Parameters.AddWithValue("#text", box1_text.InnerText);
conn.Open();
cmd2.ExecuteNonQuery();
conn.Close();
}
}
protected void box2_Click(object sender, EventArgs e)
{
}
protected void box3_Click(object sender, EventArgs e)
{
}
}
When I make a change to the title of the box1 and then click the button to update the database it is actually refreshing the page and loading the sample data again and my change is not saved.
Could you please help me with this?. There is no errors nothing.
Thank you guys very much.
PS: I have noticed that when I load the page in my browser and then delete the whole code block for the data load, make a change in the browser in one of the fields and then press the button it s actually updating the database. It is very strange...
This is because you need to take care about the ASP.NET lifecycle.
You need to check if its a PostBack (A postback occurs when you click the button) or not ...
Or you will allways override your data.
protected void Page_Load(object sender, EventArgs e)
{
if (!PostBack)
{
string DatabaseConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["proekt"].ConnectionString;
string sql = "SELECT id,title,image,text FROM home WHERE id in (1,2,3) order by id";
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
conn.Open();
search for datareader -> and use it here ... Save the returning data into
the datareader and filter by ID and if its item/title etc like here and here
conn.Close();
}
}
}
Fisrt, I want to suggest that, in the Page_Load, you only open the sql connection once and execute all the commands while the connection is open and then close it at the end. This will make your page load faster.
Second, you could use asp linkbutton to create a postback when clicked. The syntax should look like this:
<asp:LinkButton ID="A1" runat="server" OnClick="box1_Click">
<span>Запази полето <img src="notification-tick.gif" width="12" height="12" /></span>
</asp:LinkButton>

problem in accessing data from sql in two drop down list at same time

i have two drop down list in web form..for both of them i've used following code to bind with sql..but whenever i'm trying to bind second drop down list with same method..it's giving error..
the code i've used:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlPropertyType.AppendDataBoundItems = true;
String strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
String strQuery = "select ID, PropertyName from PropertyType";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
ddlPropertyType.DataSource = cmd.ExecuteReader();
ddlPropertyType.DataTextField = "PropertyName";
ddlPropertyType.DataValueField = "ID";
ddlPropertyType.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
}
You want to create two dropdownlists with a dependency between them.
You need to enable AutoPostBack in the "parent" dropdownlist, add the changed event to it, and in the event load your "child" dropdownlist.
You have a good example here: http://www.aspsnippets.com/Articles/Creating-Cascading-DropDownLists-in-ASP.Net.aspx
u can directly bind dropdown using sql data base.......no need to do cding

sd display the details of selected item in the dropdown list from database

This is the code i have written to display the details of employee selected from the drop down list into textboxes. I didn't get any error but the details are not getting displayed in the textboxes...
protected void dlstemps_SelectedIndexChanged(object sender, EventArgs e)
{
int empno=Convert.ToInt32(dlstemps.SelectedItem.Value);
SqlConnection con = new SqlConnection();
con.ConnectionString=constr;
SqlCommand cmd=new SqlCommand();
cmd.CommandText = "select * from emp where empno="+empno;
cmd.Connection = con;
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
reader.Read();
txtempno.Text = reader["empno"].ToString();
txtename.Text = reader["ename"].ToString();
txtsal.Text = reader["sal"].ToString();
txtdeptno.Text = reader["deptno"].ToString();
txtadress.Text = reader["adress"].ToString();
reader.Close();
}
catch(Exception er)
{
lblerror.Text=er.Message;
}
finally
{
con.Close();
}
}
I don't understand what went wrong in this code....
Please help me to fix it.
Dropdownlist databinding
check whether databinding of dropdownlist employees dlstemps is done inside !Page.IsPostBack if block.

Categories