I'm trying to read from an access database and put the results in a listbox. Here is the code I have, it keeps telling me that "No data exists for the row/column. I have data entered in a Column named "GroupName" and have data in a column named "RandomNumber" in the table "GroupNames"
db = new OleDbConnection();
db.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + fileName;
db.Open();
string sql = "SELECT * FROM GroupNames ORDER BY RandomNumber ASC";
cmd = new OleDbCommand(sql, db);
rdr = cmd.ExecuteReader();
lblist.Text = (string)rdr["GroupName"];
Try this:
lblist.Items.Clear();
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//lblist.Text += (string)rdr["GroupName"];
lblist.Items.Add((string)rdr["GroupName"]);
}
You need to move the reader to the first row by calling rdr.Read().
If there is no row to move to, Read() will return false.
Related
Below is a snapshot of my code. I am trying to access the only column in the customer table and place the values into a textbox on the form. I keep getting the error with my code "InvalidOperationException was unhandled" at the line declaring dr as a OleDbDataReader object.
What do I have wrong with the below code that would be giving me this error?
Should I do a list to pick out the text I want from the database?
How can I return the column values from access into a list in C# so that I can search the list for a particular value?
string strsql = "Select * from Customer";
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = strsql;
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
textBox1.Text += dr["Customer"].ToString();
}
conn.Close();
A command carries the info to be executed, a connection carries the info to reach the database server. The two objects should be linked together to produce any result. You miss that line
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = strsql;
cmd.Connection = conn; // <= here
conn.Open();
Remember also that disposable objects like a command, a reader and a connection should be disposed immediately after usage. For this pattern exists the using statement
So you should write
string cmdText = "Select * from Customer";
using(OleDbConnection conn = new OleDbConnection(.....constring...))
using(OleDbCommand cmd = new OleDbCommand(cmdText, conn))
{
conn.Open();
using(OleDbDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
.....
}
}
Here is some sample code.
try
{
using (OleDbConnection myConnection = new OleDbConnection())//make use of the using statement
{
myConnection.ConnectionString = myConnectionString;
myConnection.Open();//Open your connection
OleDbCommand cmdNotReturned = myConnection.CreateCommand();//Create a command
cmdNotReturned.CommandText = "someQuery";
OleDbDataReader readerNotReturned = cmdNotReturned.ExecuteReader(CommandBehavior.CloseConnection);
// close conn after complete
// Load the result into a DataTable
if (readerNotReturned != null) someDataTable.Load(readerNotReturned);
}
}
After that you have a Datatable containing your data. Ofcourse you can afterwards search for records in the Datatable any way you like.
I just finished to make the add part of a quiz, the part where admin add questions for guest.
When I clicked next button I just see the last question I added. Here is the code:
SqlConnection con = new SqlConnection(#"Data Source=MARIA-PC;Initial Catalog=Account;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM [dbo].[QuestAdd] WHERE Class = '1'", con);
SqlDataReader reader = null;
reader = cmd.ExecuteReader();
while (reader.Read())
{
textBox2.Text = (reader["Question"].ToString());
textBox3.Text = (reader["R1"].ToString());
textBox4.Text = (reader["R2"].ToString());
textBox5.Text = (reader["R3"].ToString());
textBox6.Text = (reader["R4"].ToString());
if (textBox7.Text == (reader["R_correct"].ToString()))
point = point + 1;
}
con.Close();
My problem is That I don't know why I see just the last question althoug in the table I have more than one question.
The datareader is looping through all the results and overwriting the textbox values for each row in the query.
In the code above, every time you run this, only the final row retrieved will be displayed.
You might be better retrieving the data and storing in a data structure and recoding the next button to use this.
e.g.
//Set up datatable with all questions
DataTable dt=new DataTable();
dt.column.Add("Question",typeof(string));
dt.column.Add("R1",typeof(string));
dt.column.Add("R2",typeof(string));
dt.column.Add("R3",typeof(string));
dt.column.Add("R4",typeof(string));
dt.column.Add("R_correct",typeof(int));
SqlConnection con = new SqlConnection(#"Data Source=MARIA-PC;Initial Catalog=Account;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM [dbo].[QuestAdd] WHERE Class = '1'", con);
SqlDataReader reader = null;
reader = cmd.ExecuteReader();
while (reader.Read())
{
DataRow dr=dt.NewRow();
dr["Question"] = (reader["Question"].ToString());
dr["R1"] = (reader["R1"].ToString());
dr["R2"] = (reader["R2"].ToString());
dr["R3"] = (reader["R3"].ToString());
dr["R4"] = (reader["R4"].ToString());
dr["R_correct"] = (reader["R_correct"]);
dt.Rows.Add(dr);
}
con.Close();
I've used a datatable here but you could easily use a list of objects as well.
The code above just adds the data from the query into a datatable and you can then, in your next button, write code that changes the row number.
This is just a rough start but it should get you on the right track
I have the following:
String sql = "SELECT * FROM Temp WHERE Temp.collection = '" + Program.collection + "'";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sql, conn);
Program.defaultCollection = (String)cmd.ExecuteScalar();
And I want to get the second column after executing the statement. I know it will return only one row with two columns
I have read online that I will have to read each row of the result, is there any other way?
ExecuteScalar gets the first column from the first row of the result set. If you need access to more than that you'll need to take a different approach. Like this:
DataTable dt = new DataTable();
SqlDataAdapater sda = new SqlDataAdapter(sql, conn);
sda.Fill(dt);
Program.defaultCollection = dt.Rows[0]["defaultCollection"];
Now, I realize that the field name may not be defaultCollection, but you can fill that in.
From the MSDN documentation for ExecuteScalar:
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
Now, as a final bit of advice, please wrap all ADO.NET objects in a using statement. Like this:
using (SqlConnection conn = new SqlConnection(connString))
using (SqlDataAdapter sda = new SqlDataAdapter(sql, conn))
{
DataTable dt = new DataTable();
sda.Fill(dt);
// do something with `dt`
}
this will ensure they are properly disposed.
And I want to get the second column after executing the statement
It is not possible with execute scalar.
is there any other way
You have 2 options here either to use SqlDataAdapter or SqlDataReader.
For you using DataReader is a recommended approach as you don't need offline data or do other worh
by using SqlDataAdapter
using (SqlConnection c = new SqlConnection(
youconnectionstring))
{
c.Open();
/
using (SqlDataAdapter a = new SqlDataAdapter(sql, c))
{
DataTable t = new DataTable();
a.Fill(t);
if(t.Rows.Count > 0)
{
string text = t.Rows[0]["yourColumn"].ToString();
}
}
}
by using DataREader
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command =
new SqlCommand(sql, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//read data here
string text = reader.GetString(1)
}
reader.Close();
}
SqlCommand.ExecuteScalar() can be used only when the result have just one row and one column.
If you need more than one column to be returned, you should use something like this:
String sql = "SELECT * FROM Temp WHERE Temp.collection = '" + Program.collection + "'";
SqlConnection conn = new SqlConnection(connString);
using(SqlCommand cmd = new SqlCommand(sql, conn))
{
using(SqlDataReader rdr = cmd.ExecuteReader())
{
if(rdr.Read())
{
Program.defaultCollection = (String)rdr["Column1"];
Program.someOtherVar = (String)rdr["Column2"];
}
}
rdr.Close();
}
That will be the fastest way.
You can use a DataReader and read only the first column like:
IDataReader cReader = cmd.ExecuteReader();
if(cReader.Read())
{
string cText = cReader.GetString(1); // Second Column
}
ExecuteScalar only returns one value. You have to make sure your query only returns that value.
String sql = "SELECT temp.defaultCollection FROM Temp WHERE Temp.collection = '" + Program.collection + "'";
On a side note, read on SqlParameter. You don't want to concatenate values like that, you'll have a problem when the collection property contains a quote.
I have the following sql command:
SqlCommand cmd = new SqlCommand("SELECT * FROM tbl WHERE ID = 'john' ", con);
How can i output the results of the following command in C# to my webpage?
If you are looking for the introductory: "How to get data on a web page?" answer, then maybe this is a little more helpful:
Add a new page MyPage.aspx to your
web application
Add a GridView to that page
On Page_Load do the code
below
{
string strSQLconnection =
"Data Source=dbServer;Initial Catalog=yourDatabase;Integrated Security=True";
SqlConnection con = new SqlConnection(strSQLconnection);
SqlCommand sqlCommand =
new SqlCommand("SELECT * FROM tbl WHERE ID = 'john' ", con);
con.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
}
You will need to execute the SQL command, then iterate through the data. Assuming this query returns one row, your code might look like:
using (var reader = cmd.ExecuteReader()) {
if (!reader.HasRows) {
// User not found
}
else {
reader.Read(); // Advance to first row
// Sample data access
var name = reader["name"];
var otherColumnValue = reader["otherColumnName"];
}
}
I have got the following code from here to read an Excel file using C# .NET:
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Book1.xls;Extended Properties=""Excel 8.0;HDR=YES;""";
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
DbCommand command = connection.CreateCommand()
command.CommandText = "SELECT City,State FROM [Cities$]";
I want to select only 10 rows starting from the 4th row, how can I do that?
I'm no Excel querying expert, but this certainly works. Use TOP to limit the query to 13 rows. The first row is the header with column names so it may not count. Obviously change if I misunderstand. Then, keep track of a row ID and do stuff to rows on or after 4.
Hope this helps!
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Book1.xls;Extended Properties=""Excel 8.0;HDR=YES;""";
using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connectionString)) {
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT top 13 City,State FROM [Cities$]";
conn.Open();
System.Data.IDataReader dr = cmd.ExecuteReader();
int row = 2;
while (dr.Read()) {
if (row++ >= 4) {
// do stuff
Console.WriteLine("{0}, {1}", dr[0], dr[1]);
}
}
}