How to pull data from database and display in dropdownlist - c#

I want to display details of a receipt number when the user enters the number and do a search. After the user should be able to edit the details. I pull the information for the driver; however, when I click to edit the list of drivers from the database is not shown; but just the actual data.
private void BindData()
{
int parsedValue;
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "PP_spSearchReturnCrate";
if (!string.IsNullOrEmpty(txtReceiptNo.Text.Trim()))
{
cmd.Parameters.Add("#receiptNo", SqlDbType.VarChar).Value = txtReceiptNo.Text.Trim();
}
cmd.Connection = sqlConn;
sqlConn.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
String DATE = Convert.ToDateTime(dt.Rows[0]["returnDte"]).ToString("yyyy-MM-dd");
txtReturnDte.Text = DATE;
txtReceipt.Text = dt.Rows[0]["receiptNo"].ToString(); //Where ColumnName is the Field from the DB that you want to display
ddlCustomer.Text = dt.Rows[0]["CUSTNAME"].ToString();
//ddlDriver.Text = dt.Rows[0]["driverName"].ToString();
//ListItem lis = new ListItem(dt.Rows[0]["driverName"].ToString());
//ddlDriver.Items.Add(lis);
ddlUnitId.Text = dt.Rows[0]["unitId"].ToString();
txtNumber.Text = dt.Rows[0]["qtyReturned"].ToString();
txtLocation.Text = dt.Rows[0]["custLocation"].ToString();
//ddlDriver.DataSource = cmd.ExecuteReader();
//ListItem lis = new ListItem(dt.Rows[0]["driverName"].ToString());
//ddlCustomer.Items.Add(lis);
ddlDriver.DataSource = dt;
ddlDriver.DataBind();
ddlDriver.DataTextField = "driverName";
ddlDriver.DataValueField = "driverName";
ddlDriver.DataBind();
//ListItem li = new ListItem(dt.Rows[0]["driverName"].ToString());
//ddlDriver.Items.Add(li);
Panel1.Visible = true;
}
}

Your BindData() method is a good start, but it's little cluttered. And I am by no means an expert, but I'm going trim out some of the stuff you don't need for now and we'll see if we can get your drop down populated.
First you'll need to add a couple using directives at the top of your code behind page if they're not there already:
using System.Configuration;
using System.Data.SqlClient;
This is how I was shown:
private void BindData()
{
// Wrap the whole thing in a using() because it automatically closes the connection
// when it's done so you don't have to worry about doing that manually
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["name of your connection string"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
// Set the releveant properties like you already had
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "PP_spSearchReturnCrate";
// Double check that the connection is open
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
// Create your SqlDataAdapter and fill it with the data from your stored procedure
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
// Then set that as the DataSource, and finally bind it to your drop down
ddlDriver.DataSource = ds.Tables[0];
ddlDriver.DataBind();
}
}
}
And if you'd like the default option in your drop down to say something other than whatever comes first from your stored procedure you can set a property called AppendDataBoundItems to true, then manually add a ListItem to your drop down, and set its Value to -1 (to get it to show at the top):
<asp:DropDownList runat="server" ID="ddlDriver" AppendDataBoundItems="true">
<asp:ListItem Enabled="true" Text="Please Select" Value="-1"></asp:ListItem>
</asp:DropDownList>

Related

How to get data from SQL and write it in textbox?

I need a help.
I searched and I tried a lot but I am too bad to make it work on my project by myself.
This is code for button-Seek. I want to make Seek-button to fill textbox by respective data.
private void SeekClick(object sender, EventArgs e)
{
if (TBCusNumber.Text != "")
{
string Number = TBCusNumber.Text;
var Conn = new SqlConnection();
Conn.ConnectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApp1.Properties.Settings.DataBase"].ConnectionString;
var Cmd = new SqlCommand();
Cmd.Connection = Conn;
Cmd.CommandText = "SELECT * FROM CustomerList WHERE CustomerNumber = " + Number;
var DataAdapter = new SqlDataAdapter(Cmd);
DataSet DataSet = new DataSet();
DataAdapter.Fill(DataSet, "CustomerList");
CusView.DataSource = DataSet;
CusView.DataMember = "CustomerList";
}
}
And This is the data table.
This is what happens when I put 3 in the text box and press Seek-button.
So here, I want all text boxes to be filled by the data which I searched.
You will get only one row for the query right?
So give like that,
txtFirstName.Text = DataSet.Tables[0].Rows[0]["FirstName"].ToString();
txtLasttName.Text = DataSet.Tables[0].Rows[0]["LastName"].ToString();
Like this you need to assign the values to the respective text boxes.
There are three problem need to fix.
You forget to open the connection with DB,add Conn.Open(); before you excute sql command.
You need to add parameter to prevention SQL Injection
Please use using it will help you to use external resources to return the memory.
when the DataSet be filled you can get the data then fill in textbox
You can follow like this.
private void SeekClick(object sender, EventArgs e)
{
if (TBCusNumber.Text != "")
{
string Number = TBCusNumber.Text;
using (var Conn = new SqlConnection())
{
Conn.ConnectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApp1.Properties.Settings.DataBase"].ConnectionString;
using (var Cmd = new SqlCommand())
{
Cmd.Connection = Conn;
Cmd.CommandText = "SELECT * FROM CustomerList WHERE CustomerNumber = #Number";
Cmd.Parameters.AddWithValue("#Number", Number);
//You miss to add Conn.Open()
Conn.Open();
using (var DataAdapter = new SqlDataAdapter(Cmd))
{
DataSet DataSet = new DataSet();
DataAdapter.Fill(DataSet, "CustomerList");
CusView.DataSource = DataSet;
CusView.DataMember = "CustomerList";
//when the DataSet be filled you can get the data then fill in textbox
txt_firstName.Text = DataSet.Tables[0].Rows[0]["FirstName"].ToString();
}
}
}
}
}

Clearing data in SqlDataAdapter

I'm using SQLDataAdapter to populate data from my SQL server database in 2 DropDownLists. Depending on what is selected in the first dropdown, the corresponding data is populated in the second. It works fine but data that has since been deleted by the admin on their side of the application and is no longer in the database is still showing up in the dropdowns.
Is there a way in which I can reset or clear what is already in the DataAdapter, refresh it and then show only the current data?
If it helps here is how I have the data binding to the dropdowns. Firstly a general method which is called on page load to populate the first dropdown, and again in the _SelectedIndexChanged of the first dropdown to bind the relevant data to the second.
if (!IsPostBack)
{
DataBind();
string query = "select Distinct ClubID, ClubName from Pitch";
BindDropDownList(DDLClub, query, "ClubName", "ClubID", "Select Club");
DDLPitches.Enabled = false;
DDLPitches.Items.Insert(0, new ListItem("Select Pitch", "0"));
}
private void BindDropDownList(DropDownList DDL, string query, string text, string value, string defaultText)
{
string ConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(ConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
DDL.DataSource = cmd.ExecuteReader();
DDL.DataTextField = text;
DDL.DataValueField = value;
DDL.DataBind();
sda.Dispose();
con.Close();
}
}
DDL.Items.Insert(0, new ListItem(defaultText, "0"));
}
protected void DDLClub_SelectedIndexChanged(object sender, EventArgs e)
{
DDLPitches.Enabled = false;
DDLPitches.Items.Clear();
DDLPitches.Items.Insert(0, new ListItem("Select Pitch", "0"));
int ClubID = int.Parse(DDLClub.SelectedItem.Value);
if (ClubID > 0)
{
string query = string.Format("select PitchID, ClubID, ClubName, PitchName from Pitch where ClubID = {0}", ClubID);
BindDropDownList(DDLPitches, query, "PitchName", "PitchID", "Select Pitch");
DDLPitches.Enabled = true;
}
}

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

Listbox isn't populating with Data

I have set up a listbox called lboxsupplier, i have also created a data adapter which i then used to populate the supplier listbox. When i run the form the listbox is empty. I want the listbox to populate with supplier ID and company which i will then click on to populate another listbox with products.
Namespace Pennyburn_Greg
{
public partial class FormProcess : Form
{
SqlDataAdapter daSupplier;
DataSet dsPennyburnGreg = new DataSet();
SqlConnection conn;
SqlCommand cmdSupplierDetails;
SqlCommandBuilder cmdBSupplier;
DataRow drSupplier;
String connstr, sqlSupplier;
public FormProcess()
{
InitializeComponent();
}
private void FormProcess_Load(object sender, EventArgs e)
{
connstr = #"Data Source= arlene-pc; Initial Catalog= PennyburnGreg; Integrated Security=True";
//dataAdapter for supplier listbox
sqlSupplier = #"Select* from Supplier";
conn = new SqlConnection(connstr);
cmdSupplierDetails = new SqlCommand(sqlSupplier, conn);
daSupplier = new SqlDataAdapter(cmdSupplierDetails);
daSupplier.FillSchema(dsPennyburnGreg, SchemaType.Source, "Supplier");
}
private void filllboxsupplier(string str)
{
daSupplier.Fill(dsPennyburnGreg, "Supplier");
lboxsupplier.DataSource = dsPennyburnGreg.Tables["Supplier"];
lboxsupplier.DisplayMember = "Company";
lboxsupplier.ValueMember = "SupplierID";
}
}
}
First of all, why are you calling FillSchema, rather should be calling Fill method to get the data, like
daSupplier.Fill(dsPennyburnGreg, "Supplier");
Once you have the dataset filled, then in your FormProcess_Load() you can add the dataset as datasource to the listbox like
lboxsupplier.DataSource = dsPennyburnGreg.Tables["Supplier"]
First thing you need to do is loosely couple your UI and data a little bit. Try this code:
// Returns a DataTable of ALL suppliers
private DataTable GetSuppliers()
{
return GetSuppliers(0);
}
// Returns a DataTable of the given supplier
private DataTable GetSuppliers(int supplierId)
{
using (var connection = new SqlCommand())
{
connection.ConnectionString = #"Data Source= arlene-pc; Initial Catalog= PennyburnGreg; Integrated Security=True";
using (var command = new SqlCommand())
{
connection.Open();
command.CommandType = CommandType.Text;
command.Connection = connection;
if (supplierId == 0)
{
command.commandText = "SELECT * FROM Supplier";
}
else
{
command.commandText = "SELECT * FROM Supplier WHERE SupplierId=#id";
command.Parameters.AddWithValue("#id", supplierId);
}
using (var adapter = new SqlDataAdapter())
{
using (var ds = new DataSet())
{
adapter.SelectCommand = command;
adapter.Fill(ds);
if (ds.Tables.Count > 0)
return ds.Tables[0];
}
}
}
}
return null;
}
And now you can just do this:
lboxsupplier.DataSource = GetSuppliers(int.Parse(lboxsupplier.SelectedValue));
lboxsupplier.DisplayMember = "Company";
lboxsupplier.ValueMember = "SupplierID";
Or if you need all Suppliers, just do this:
lboxsupplier.DataSource = GetSuppliers();
lboxsupplier.DisplayMember = "Company";
lboxsupplier.ValueMember = "SupplierID";
This code will provide some separation. This is still not ideal, but beats what you had.
You're not doing anything with the listbox control in FormProcess_Load, so it will be empty when it first loads. I'm assuming you have lboxsupplier_Click bound to the Click event of lboxsupplier? If so, then you'll need to click on that listbox before it will populate the Dataset (which is a very odd user experience, but if that's truly what you need...). If lboxsupplier_Click isn't an event handler, then you're going to have to manually call it.
If it still isn't populating, then try running your query against the database directly, and make sure that it returns data and has columns named "Company" and "SupplierID"

Fill ComboBox with Access DB data

I'm using Visual Studio 2010 and C# to create a windows form with a combobox that should contain employees initials. I have spent the last few days searching through every solution I can find and I still can not get my combobox to populate.
This is what I've got as of now:
public static void FillComboBox(string Query, System.Windows.Forms.ComboBox LoggedByBox)
{
using (var CONN = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\Documents\\Service Request Application\\bin\\Debug\\servicereq1.mdb"))
{
CONN.Open();
DataTable dt = new DataTable();
try
{
OleDbCommand cmd = new OleDbCommand(Query, CONN);
OleDbDataReader myReader = cmd.ExecuteReader();
dt.Load(myReader);
}
catch (OleDbException e)
{
Console.WriteLine(e.ToString());
Console.ReadLine();
return;
}
LoggedByBox.DataSource = dt;
LoggedByBox.ValueMember = "ID";
LoggedByBox.DisplayMember = "Initials";
}
}
Then I call it when the form loads
private void Form1_Load(object sender, EventArgs e)
{
FillComboBox("select ID, Initials from [Fixers and Testers]", LoggedByBox);
}
When I run the program, the combobox is still blank. I'm positive that my column names and table names are correct. Any suggestions?
I finally got my ComboBox filled and I wanted to share what I changed for anyone else who stumbles across this question in their searches. After spending a bit more time searching through other questions and MSDN, I was able to come up with this.
private void LoadComboLogged()
{
AppDomain.CurrentDomain.SetData("DataDirectory",#"\\prod\ServiceRequests");
string strCon = #"Provider=Microsoft.Jet.OLEDB.4.0;DataSource=|DataDirectory|\servicereq1.mdb";
try
{
using (OleDbConnection conn = new OleDbConnection(strCon))
{
conn.Open();
string strSql = "SELECT Initials FROM [Fixers and Testers] WHERE [Status] ='C'";
OleDbDataAdapter adapter = new OleDbDataAdapter(new OleDbCommand(strSql, conn));
DataSet ds = new DataSet();
adapter.Fill(ds);
loggedByComboBox.DataSource = ds.Tables[0];
loggedByComboBox.DisplayMember = "Initials";
loggedByComboBox.ValueMember = "Initials";
}
}
catch (Exception ex)
{
}
}
I also found that I needed to call
LoadComboLogged();
when I initialized my form. Without that line, the ComboBox would only show a blank dropdown list. Hope this helps someone else who runs into this problem.
Passing control to static method causing this issue. Instead of passing control to the method make that method returns the table and within the load method load the control.
SqlConnection con = new SqlConnection("Data Source=RUSH-PC\\RUSH;Initial Catalog=Att;Integrated Security=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select name from userinfo", con);
DataTable dt = new DataTable();
da.Fill(dt);
DataRow dr;
dr = dt.NewRow();
dt.Rows.InsertAt(dr, 1);
comboBox1.DisplayMember = "name";
comboBox1.ValueMember = "name";
comboBox1.DataSource = dt;
con.Close();
This may help you...
Good luck...:-)
Another possible solution would be to query and return a list of strings. Perhaps it may be less efficient, but it's what I used in a recent project of mine. Here's an example that would reside in a method, possibly called GetInitialsFromDatabase():
using(var conn = new MySqlConnection(connectionString)
{
conn.Open();
using(MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT Initials FROM [Fixers and Testers] WHERE [Status] ='C'";
MySqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
// initials is a List<String> previously defined (Assuming strings)
initials.Add(String.Format("{0}", reader[0]));
}
}
conn.Close();
}
And then return the initials List, and then in your GUI you could say:
comboBox1.DataSource = returnedList;
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;

Categories