SQL Server Column to Combobox? - c#

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.

Related

Get list of IDs from Access Database using OleDbDataReader

Using a Microsoft Access database for a Web App Quiz Manager, I have table with a ID column that has a list of IDs which looks something like this:
ID Answer QuesDescription QuesAnswer QuestionNum
1 1 Example Example 1
3 3 Example Example 2
4 4 Example Example 3
6 1 Example Example 4
Using the query SELECT ID FROM (QuizName) with OleDbCommand I managed to get the ID values from the database and stored into OleDbDataReader reader. But i don't know how to get the ID values from the reader and store them as a String List. Does anyone know how to do this?
I've tried using stuff like
public List<string> GetIDValueFromQuestionNumber(string quizNumber)
{
try
{
string strSQL = string.Concat("SELECT count(ID) as RowCount FROM ", quizNumber);
List<string> resourceNames = new List<string>();
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(strSQL, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
reader.Read();
int rowCount = (int)reader["RowCount"];
strSQL = string.Concat("SELECT ID FROM ", quizNumber);
command = new OleDbCommand(strSQL, connection);
using (reader = command.ExecuteReader())
{
while (reader.Read())
{
resourceNames.Add(" " + reader.GetString(0));
}
}
connection.Close();
for (int count = 0; count < rowCount; count++)
{
int value = (int)reader.GetValue(count);
resourceNames.Add(value.ToString());
}
}
return resourceNames;
}
catch (Exception e)
{
return null;
}
}
But to no luck.
I should note that these tables can vary in depth.
I suggest this approach.
Say a form - DataGridView to display our data.
And say a listbox to display the list of id that you build up into that List
So, this form:
And the button click code:
private void button1_Click(object sender, EventArgs e)
{
// load up our data list with Hotels
string strSQL =
#"SELECT ID, FirstName, LastName, City, HotelName
FROM tblHotelsA ORDER BY HotelName";
DataTable rstData = MyRst(strSQL);
dataGridView1.DataSource = rstData;
// now build up a list of id in to string colleciton
List<string> MyIDList = new List<string>();
foreach (DataRow MyOneRow in rstData.Rows)
{
MyIDList.Add(MyOneRow["ID"].ToString());
}
// Lets set the id list to a listbox
listBox1.DataSource = MyIDList;
}
DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (OleDbConnection conn = new OleDbConnection(Properties.Settings.Default.AccessDB))
{
using (OleDbCommand cmdSQL = new OleDbCommand(strSQL, conn))
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
And now we get/see this:
So, pull the table. Display it, do whatever.
Then use the SAME table, and simple loop each row, grab the ID and add to your list.
And of course, one would probably hide the "id" in the above list (just add the columns using edit columns - only add the ones you want). You can still get/grab/use ANY column from the data source - it not a requirement to display such columns.

Access Query on C# Not Generating Results

I am using the following Access query on C# MVC to compare two tables and return records that fall within the date range and machine selected by the user. The query code runs perfectly on the actual Access database but I guess something is wrong with the connection string and the code to return the results. I am not sure what's wrong with the code and I would appreciate if someone could help me determine what's wrong. Thanks!
C# MVC Controller code:
public ActionResult MissingChecksheets(string startDate, string endDate, string machine)
{
var query = $#"SELECT * FROM [TrackingLog]
WHERE [TrackingLog].[Workcenter] = '{machine}' AND
[TrackingLog].[Complete Date] > #{startDate}# AND
[TrackingLog].[Complete Date] < #{endDate}# AND
[TrackingLog].[Order Item] NOT IN (SELECT [OrderNum] FROM [dbo_Checksheet])";
var sheets = new List<Checksheet>();
using (var con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Checksheets.accdb;"))
{
using (var command = new OleDbCommand(query, con))
{
con.Open();
using (var reader = command.ExecuteReader())
{
while (reader.NextResult())
{
sheets.Add(new FabChecksheet
{
OrderNum = reader.GetString(0),
PartNum = reader.GetString(1)
});
}
}
}
}
return PartialView(sheets);
}
OleDbDataReader.NextResult() method used to move between result set if the query string has multiple result sets (e.g. more than two SELECT statements, not counting SELECT inside aggregate functions). Since your query has single result set, OleDbDataReader.Read() must be used to move between records:
using (var con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Checksheets.accdb;"))
{
using (var command = new OleDbCommand(query, con))
{
con.Open();
using (var reader = command.ExecuteReader())
{
// Only single result set, use 'Read' here
while (reader.Read())
{
sheets.Add(new FabChecksheet
{
OrderNum = reader.GetString(0),
PartNum = reader.GetString(1)
});
}
}
}
}
Note that if NextResult() is used, the data reader will move to next result set which has empty data.
Related issue:
Difference between SqlDataReader.Read and SqlDataReader.NextResult

Insert into ListBox from a Database

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

Multiples Table in DataReader

I normally use DataSet because It is very flexible. Recently I am assigned code optimization task , To reduce hits to the database I am changing two queries in a procedure. one Query returns the count and the other returns the actual data. That is , My stored procedure returns two tables. Now, I know how to read both tables using DataSets, But I need to read both tables using DataReader. In search of that I found This.
I follow the article and wrote my code like this:
dr = cmd.ExecuteReader();
while (dr.Read())
{
}
if (dr.NextResult()) // this line throws exception
{
while (dr.Read())
{
But I am getting an exception at dt.NextResult. Exception is :
Invalid attempt to call NextResult when reader is closed.
I also googled above error , but still not able to solve the issue.
Any help will be much appreciated. I need to read multiple tables using datareader, is this possible?
Try this because this will close connection ,data reader and command once task get over , so that this will not give datareader close exception
Also do check like this if(reader.NextResult()) to check there is next result,
using (SqlConnection connection = new SqlConnection("connection string here"))
{
using (SqlCommand command = new SqlCommand
("SELECT Column1 FROM Table1; SELECT Column2 FROM Table2", connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
MessageBox.Show(reader.GetString(0), "Table1.Column1");
}
if(reader.NextResult())
{
while (reader.Read())
{
MessageBox.Show(reader.GetString(0), "Table2.Column2");
}
}
}
}
}
I have tried to reproduce this issue (also because i haven't used multiple tables in a reader before). But it works as expected, hence i assume that you've omitted the related code.
Here's my test code:
using (var con = new SqlConnection(Properties.Settings.Default.ConnectionString))
{
using (var cmd = new SqlCommand("SELECT TOP 10 * FROM tabData; SELECT TOP 10 * FROM tabDataDetail;", con))
{
int rowCount = 0;
con.Open();
using (IDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
String object1 = String.Format("Object 1 in Row {0}: '{1}'", ++rowCount, rdr[0]);
}
if (rdr.NextResult())
{
rowCount = 0;
while (rdr.Read())
{
String object1 = String.Format("Object 1 in Row {0}: '{1}'", ++rowCount, rdr[0]);
}
}
}
}
}
I built on Pranay Rana's answer because I like keeping it as small as possible.
string rslt = "";
using (SqlDataReader dr = cmd.ExecuteReader())
{
do
{
while (dr.Read())
{
rslt += $"ReqID: {dr["REQ_NR"]}, Shpr: {dr["SHPR_NR"]}, MultiLoc: {dr["MULTI_LOC"]}\r\n";
}
} while (dr.NextResult());
}
The question is old but I find the answers are not correct.
Here's how I do it:
List<DataTable> dataTables = new();
using IDataReader dataReader = command.ExecuteReader();
do
{
DataTable dataTable = new();
dataTable.Load(dataReader);
dataTables.Add(dataTable);
}
while (!dataReader.IsClosed);

How to read columns and rows with C#?

Hello I'm in need of a code to read columns and rows for C#.
I've come this far:
obj.MysqlQUERY("SELECT * FROM `players` WHERE name = "+name+";"); // my query function
Grateful for help;]
Here is a standard block of code that I use with MySql a lot. Note that you must be using the MySql connector available here.
string myName = "Foo Bar";
using (MySqlConnection conn = new MySqlConnection("your connection string here"))
{
using (MySqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = #"SELECT * FROM players WHERE name = ?Name;";
cmd.Parameters.AddWithValue("Name", myName);
MySqlDataReader Reader = cmd.ExecuteReader();
if (!Reader.HasRows) return;
while (Reader.Read())
{
Console.WriteLine(GetDBString("column1", Reader);
Console.WriteLine(GetDBString("column2", Reader);
}
Reader.Close();
conn.Close();
}
}
private string GetDBString(string SqlFieldName, MySqlDataReader Reader)
{
return Reader[SqlFieldName].Equals(DBNull.Value) ? String.Empty : Reader.GetString(SqlFieldName);
}
Note that I am using a method to return a specific value if the database value is null. You can get creative and provide various return values or incorporate nullable types, etc.
Also you can use:
Create your own dataTable. When reader reaches end, you will have datatable which is custom created, and custom filled by yourself.
DataTable dt = new DataTable();
dt.Columns.Add("Id",typeof(int));
dt.Columns.Add("Name",typeof(string));
dt.Columns.Add("BlaBla",typeof(string));
dt.AcceptChanges();
// Your DB Connection codes.
while(dr.Read())
{
object[] row = new object[]()
{
dr[0].ToString(),// ROW 1 COLUMN 0
dr[1].ToString(),// ROW 1 COLUMN 1
dr[2].ToString(),// ROW 1 COLUMN 2
}
dt.Rows.Add(row);
}

Categories

Resources