Question: How can I insert items into a listbox from a database?
Here is what I tried:
public void Fetch()
{
using (SqlConnection cn = new SqlConnection(UtilObj.ConnectionString()))
{
cn.Open();
ExecuteFetch(cn);
cn.Close();
}
}
public void ExecuteFetch(SqlConnection cn)
{
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "spName";
cm.Parameters.AddWithValue("#Param1", Param1Val);
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{
while (dr.Read())
{
myListBox.Items.Add(dr["Color"].ToString());
}
}
}
}
This shows an empty list when I run the code even though it populates in debugger.
ASPX Page
<asp:ListBox ID="myListBox" runat="server" />
I think you're looking for something like this:-
Get reader object after executing your sp
SqlDataReader reader = cmd.ExecuteReader();
myListBox.DataSource= reader; //reader object
myListBox.DataTextField = "Color"; // the field you want to show in listbox
myListBox.DataValueField = "Color"; // the value filed behind the items.
myListBox.Databind();
Text and Value Fields can be same as well if you want it that way
That's it. It's the same way you bind items to a dropdown list. Just used this in our recent project
Hope it's helpful
Related
I am trying to add items to listbox from another class.
I create a form, form name called FilterControl, it has a listbox control(listBoxColumnHeaders)
I create separate class called FilterColumnHeader, There I created one method()addColumnHeader()
Now I am trying to items to listbox of FilterControl form from this FilterColumnHeader class
Here is my code:
public void addColumnHeader(string name)
{
try
{
string cs = ConfigurationManager.ConnectionStrings["TestConnectionString"].ConnectionString;
string query = #"SELECT
AsHeading
FROM
RSHeading WITH(NOLOCK);
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
con.Open();
SqlDataReader rd = cmd.ExecuteReader();
FilterControl fc = new FilterControl();
while (rd.Read())
{
fc.listBoxColumnHeaders.Items.Add(rd["AsHeading"].ToString());
MessageBox.Show(rd["AsHeading"].ToString()); //record is showing on message box
}
}
}
catch(Exception ee)
{
MessageBox.Show(ee.ToString());
}
}
Note
If I try directly from the same form(FilterControl). It is working fine, Also the database is retrieved record successfully.
I set the modifiers of listbox control to Public
Try this accessing your form inside the class:
var fc= Application.OpenForms.OfType<FilterControl>().SingleOrDefault();
while (rd.Read())
{
fc.listBoxColumnHeaders.Items.Add(rd["AsHeading"].ToString());
MessageBox.Show(rd["AsHeading"].ToString());
}
I am creating a database application and I'm having difficulty implementing a query. I have a query which populates a combobox with customer's bank accounts this is the code for the query:
private void ShowAccounts()
{
string sql = "SELECT account.custid, product.name FROM account INNER JOIN product ON account.prodid = product.prodid WHERE account.custid = #AccountID";
using (OleDbConnection connection = new OleDbConnection(Properties.Settings.Default.ConnectionScring))
{
OleDbCommand command = new OleDbCommand(sql, connection);
command.Parameters.AddWithValue("#AccountID", customerData.CustomerID);
connection.Open();
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
comboAccounts.Items.Add(reader["name"].ToString());
}
}
}
This works the way I need it to but based on the account selection I need to display the account balance and I'm wondering how to go about writing that query. Any help would be appreciated.
Thank you
I guess this is what you are trying to do? I am guessing on your column and table names so you will need to modify the sql statement if I got it wrong.
private string Get_Balance(string AccountNumber)
{
string sql = "SELECT balance FROM account WHERE custid = #AccountID";
string balance = "";
using (OleDbConnection connection = new OleDbConnection(Properties.Settings.Default.ConnectionScring))
{
OleDbCommand command = new OleDbCommand(sql, connection);
command.Parameters.AddWithValue("#AccountID", AccountNumber);
connection.Open();
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
balance = reader["balance"].ToString();
}
}
}
return (balance);
}
Use the SelectedIndexChanged event of your combo box to call the above code. You will need to add the event handler to the combo box (just double click it on the form and VS will do it for you).
private void comboAccounts_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboAccounts.Text != "")
{
balanceLabel.text = Get_Balance(comboAccounts.text); //Or whatever you named the label you want your balance to to into.
}
}
After you populate your combo box with your code, whenever the combo box is dropped down and changed it will pass the text of whatever is in the combo box to Get_Balance which will return a string that will be placed in the label.
I have a table called Product. One of the columns of this table is called Naam. It's the name of the product. When you press on the button, all product names have to be added to the combobox.
So if I have 2 products: Cola & Fanta.
The program has to show only the column Naam in the combobox. Not the other columns.
I have already this for my button, but it doesn't work.
db.AlleProducten("Select Naam from Product;", Product);
cb_product.Items.Add(Product.Naam);
And this is the method that runs the query:
public void AlleProducten(string commandText, product Product)
{
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(commandText, conn))
{
conn.Open();
using (var rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
rdr.Read();
Product.Naam = rdr.GetString(1);
conn.Close();
}
}
}
}
The error:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll
Additional information: De index ligt buiten de matrixgrenzen.
The additional information is in Dutch. Translated to English:
The index is located outside of the array bounds.
The first problem in your code is when you try to retrieve the value at index 1 of your SqlDataReader. Your query has only one column and in NET arrays start at index zero, so you need to retrieve the Naam value using this line
Product.Naam = rdr.GetString(0);
However, if you have more than one record to extract the Naam value then you need to loop using the SqlDataReader until it return false from the Read method and store the Naam values retrieve in some kind of collection structure.
I suggest to use a List<string>
public List<string> AlleProducten(string commandText)
{
List<string> names = new List<string>();
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(commandText, conn))
{
conn.Open();
using (var rdr = cmd.ExecuteReader())
{
while(rdr.Read())
names.Add(rdr.GetString(0));
}
conn.Close();
}
return names;
}
The code above loops over the returned results of the SqlDataReader and add every Naam to a List of strings and finally returns the list to the caller.
In this way you can assign the return value of the AlleProducten method to the DataSource of the combobox
List<string>result = db.AlleProducten("Select Naam from Product;");
cb_product.DataSource = result;
1 - You are out of range due you are using rdr.GetString(1) instead of rdr.GetString(0)
2 - There isn't any ComboBox in your code.
using (var rdr = cmd.ExecuteReader())
{
while (reader.Read())
{
Product.Naam = rdr.GetString(0);
YourComboBox.Items.Add(Product.Naam);
}
}
Take a look at SqlCommand.ExecuteReader documentation.
I am new to .net and C# and I want to perform update/delete. I am using e template which has a table. I want to get data from database and display in that table and then perform update.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
SqlDataReader rd;
SqlCommand comand = new SqlCommand();
//open connection with database
connection.Open();
//query to select all users with the given username
comand.CommandText = "select * from artikulli ";
rd = comand.ExecuteReader();
if(rd.HasRows )
{
while (rd.Read())
{
Row1.Items.Add(rd[0].ToString());
}
}
connection.Close();
}
Row1 is the id of table row. I know that this is not the best way and it doesn't work.
I get this error:
CS0103: The name 'Row1' does not exist in the current context
My table row Row1 is declared as below:
<td id="Row1" style="width: 73px"> </td>
It's apparent, as you've admitted, you are new to C#, so there are a number of things to point out, as have been addressed in the comments.
HTML elements are not going to be visible to the code-behind without the runat="server" attribute. (This attribute is required for ASP elements.)
As marc_s pointed out, your database communication would currently produce a run-time error, as the SqlCommand was not given a connection.
At some point you must really familiarize yourself with the using statement.
To correct your code-behind, it should be more like the following:
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString))
{
using (SqlCommand command = connection.CreateCommand())
{
//open connection with database
connection.Open();
//query to select all users with the given username
command.CommandText = "select * from artikulli ";
List<object> users = new List<object>();
using (SqlDataReader rd = command.ExecuteReader())
{
if (rd.HasRows)
{
while (rd.Read())
{
users.Add(rd[0].ToString());
}
}
}
myGridView.DataSource = users;
myGridView.DataBind();
}
}
}
Where myGridView is an instance of a GridView created in the aspx page. The list users should be a list of whatever class you want to create to show user data, which will determine how your GridView instance will be formatted.
Just to get you to the point where you can see your database query working at all you can instead do the following from your query result (though I definitely recommend implementing the GridView eventually):
System.Text.StringBuilder sb = new System.Text.StringBuilder();
using (SqlDataReader rd = command.ExecuteReader())
{
if (rd.HasRows)
{
while (rd.Read())
{
sb.Append(rd[0].ToString());
sb.Append("<br />");
}
}
}
Row1.InnerHtml = sb.ToString();
And you will have to change your Row1 to
<td id="Row1" style="width: 73px" runat="server"> </td>
Per the error, you'll need to bring your Row1 variable into scope
TableRow Row1 = new TableRow();
while (rd.Read())
{
Row1.Items.Add(rd[0].ToString());
Table1.Rows.Add(Row1);
}
Can anybody help me with the issue I'm seeing? For some reason when I run my page, I get my drop down lists to populate the data, however the first item in my database, per each SQL query, doesn't get populated.
For example, my database table is:
Category
1 Books
2 Clothing
3 Toys
4 Household Items
my first query -
SELECT Category FROM ProductCategories
my drop down list gets populated with
Clothing
Toys
Household Items
I have 2 other drop down lists I'm populating and those are doing the same thing. Once I get this figured out, I'll try to figure out the other problem I'm having with inserting the data in the database.
Thank you!
public partial class InsertItems : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connection;
SqlCommand populateList;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["LakerBids"].ConnectionString;
connection = new SqlConnection(connectionString);
populateList = new SqlCommand("USE LakerBids SELECT Category FROM ProductCategories;" +
"USE LakerBids SELECT SubCategory FROM ProductSubCategories;" +
"USE LakerBids SELECT LName FROM Users", connection);
if (!IsPostBack)
{
try
{
connection.Open();
reader = populateList.ExecuteReader();
while (reader.Read())
{
pcategory.DataSource = reader;
pcategory.DataValueField = "Category";
pcategory.DataBind();
}
reader.NextResult();
while (reader.Read())
{
psubcategory.DataSource = reader;
psubcategory.DataValueField = "SubCategory";
psubcategory.DataBind();
}
reader.NextResult();
while (reader.Read())
{
user.DataSource = reader;
user.DataValueField = "LName";
user.DataBind();
}
reader.Close();
}
finally
{
connection.Close();
}
}
}
protected void AddItem(object sender, EventArgs e)
{
if (Page.IsValid)
{
SqlConnection connection;
SqlCommand insertData;
string connectionString = ConfigurationManager.ConnectionStrings["LakerBids"].ConnectionString;
connection = new SqlConnection(connectionString);
insertData = new SqlCommand("INSERT INTO Products (ProductName, ProductDesc, CategoryID, SubCatID, StatusID, UserID, ReservePrice, AuctionLength, BidID)" +
"VALUES (#ProductName, #ProductDesc, #CategoryID, #SubCatID, 1, #UserID, #ReservePrice, #AuctionLength, NULL)", connection);
insertData.Parameters.Add("#ProductName", System.Data.SqlDbType.NVarChar, 50);
insertData.Parameters["#ProductName"].Value = pname.Text;
insertData.Parameters.Add("#ProductDesc", System.Data.SqlDbType.NVarChar, 200);
insertData.Parameters["#ProductDesc"].Value = pdesc.Text;
insertData.Parameters.Add("#CategoryID", System.Data.SqlDbType.Int);
insertData.Parameters["#CategoryID"].Value = pcategory.SelectedIndex;
insertData.Parameters.Add("#SubCatID", System.Data.SqlDbType.Int);
insertData.Parameters["#SubCatID"].Value = psubcategory.SelectedIndex;
insertData.Parameters.Add("#UserID", System.Data.SqlDbType.Int);
insertData.Parameters["#UserID"].Value = user.SelectedIndex + 2;
insertData.Parameters.Add("#ReservePrice", System.Data.SqlDbType.Money);
insertData.Parameters["#ReservePrice"].Value = Convert.ToDecimal(reserveprice.Text);
insertData.Parameters.Add("#AuctionLength", System.Data.SqlDbType.Int);
insertData.Parameters["#AuctionLength"].Value = Convert.ToInt32(auctionlength.Text);
try
{
connection.Open();
insertData.ExecuteNonQuery();
Response.Redirect("Categories.aspx");
}
catch (Exception error)
{
dberror.Text = error.ToString();
}
finally
{
connection.Close();
}
}
}
}
You need to either use a DataSet or populate business entities within a collection and then bind to the collection.
List<Category> cats = new List<Category>();
while (reader.Read())
{
Category cat = new Category();
// fill properties from DataReader
cats.Add(cat);
}
pcategory.DataSource = cats;
pcategory.DataValueField = "Category";
pcategory.DataBind();
Sab0tr0n, I suspect one of two things are happening.
1) If you are saying the first item does not appear AFTER you do some kind of "Add Category" action, then it might be that the dropdown is populated BEFORE the insert completes. Meaning, you need to requery after allowing the insert to be committed to the database.
OR
2) Put a breakpoint on this line:
string connectionString = ConfigurationManager.ConnectionStrings["LakerBids"].ConnectionString;
Then confirm the connectionString is to the correct database. I've seen old config files that point to test or staging databases cause this kind of confusion.
Good luck. If these aren't the answer, maybe simplify your example to us or elaborate on exactly what you do with your application and when you see the problem.
The "reader.read()" statement in each block is actually reading the first row of data, so when you set the DataSource, the first row has already been read. Try taking it out
You should use "while (reader.Read())" if you want to iterate over each result, not bind the resulset in one step.
That being said, the comments about using a Dataset, seperating logic, etc., are valid