When filling a combobox with data in database, the first row in database was missing.
con = new SqlConnection(cs.connetionString);
con.Open();
Sql = "SELECT * FROM ItemRate";
command = new SqlCommand(Sql, con);
SqlDataReader reader = command.ExecuteReader();
reader.Read();
while (reader.Read())
{
string cat = reader["RateOfInt"].ToString();
comboBox4.Items.Add(cat);
}
Calling reader.Read() advances one row, so the first time you call it before the while loop it already lands on the first row, but then you call it again in the while condition, so it advances to the second row, just remove the call before the condition.
con = new SqlConnection(cs.connetionString);
con.Open();
Sql = "SELECT * FROM ItemRate";
command = new SqlCommand(Sql, con);
SqlDataReader reader = command.ExecuteReader();
// remove this line
// reader.Read();
while (reader.Read())
{
string cat = reader["RateOfInt"].ToString();
comboBox4.Items.Add(cat);
}
Edit: Here is the example from the Docs
con = new SqlConnection(cs.connetionString);
con.Open();
Sql = "SELECT * FROM ItemRate";
command = new SqlCommand(Sql, con);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string cat = reader["RateOfInt"].ToString();
comboBox4.Items.Add(cat);
}
Related
I have the following code:
string myConnection = "server=localhost;database=test;uid=test;password=test";
string query = "SELECT label_type, label, quantity FROM system_printserver WHERE print=0";
try
{
MySqlConnection myConn = new MySqlConnection(myConnection);
myConn.Open();
MySqlCommand command = new MySqlCommand(query, myConn);
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
DataTable data = new DataTable();
adapter.Fill(data);
dataGridView1.DataSource = data;
printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
MySqlDataReader myReader;
myReader = command.ExecuteReader();
while (myReader.Read()) {
orderNumber = myReader.GetString(1);
myReader.Close();
string queryOrder = "SELECT id_order, id_carrier FROM ps_orders WHERE id_order=28329";
MySqlCommand commandOrder = new MySqlCommand(queryOrder, myConn);
MySqlDataReader myReaderOrder;
myReaderOrder = commandOrder.ExecuteReader();
idCarrier = myReaderOrder.GetString(1);
printDocument1.Print();
}
I have a problem because the second query string queryOrder doesn't work. The query is Ok but variable "idCarrier" doesn't accept any value.
I don't believe you can attach another reader to a connection, when one is already open and processing records. You must retrieve all your records first, i.e. ToList() or Dataset, or use a secondary connection for the second reader.
To make your life easier, consider using Dapper or Linq2Db, two awesome micro-ORMs.
Try it like this:
using(var connection = new MySqlConnection("server=localhost;database=test;uid=test;password=test") {
connection.Open();
int orderNumber = 0;
using (var command = connection.CreateCommand()) {
command.CommandText = #"SELECT label_type, label, quantity FROM system_printserver WHERE print=0";
DataTable data = new DataTable();
adapter.Fill(data);
dataGridView1.DataSource = data;
var reader = command.ExecuteReader();
printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
if(reader.Read()) {
orderNumber = Convert.ToInt32(reader.GetString(1));
}
}
using(var command = connection.CreateCommand()) {
command.CommandText = string.format(#"SELECT id_order, id_carrier FROM ps_orders WHERE id_order={0}",orderNumber);
var reader = command.ExecuteReader();
if(reader.Read()){
printDocument1.Print();
return reader.GetString(1);
}
}
}
I have a SQL query. Just i want to check query returning a values or not using c#. Can any one help on this to fix it. Thanks in advance.
Sqlcommand cmd = new Sqlcomman("select Name from Engdetails",con)
if (query != 0)
{
some coding..
}
else
{
coding...
}
SqlCommand cmd = new SqlCommand("select Name from Engdetails",con)
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
// The command returns Row(s)
}
else
{
// No Row has been returned.
}
There are a number of ways to work with sqlCommand; some examples:
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
...
or
using (SqlCommand cmd = new SqlCommand(query, connection))
{
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(data);
}
if it has data, the data will be in data.Tables
SqlCommand cmd = new SqlCommand("select Name from Engdetails", con);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
// somecoding
}
else
{
// somecoding
}
a example in this case rdr.GetString is Name value of the query.
using (MySqlConnection conn = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand())
{
MySqlDataReader rdr = null;
string[] dados_bd = new string[2];
conn.Open();
cmd.Connection = conn;
cmd.CommandText = sql;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
if (estado == 1)
{
dados_bd[0] = rdr.GetString(0);
cmd.ExecuteNonQuery();
For the UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the SQL statement.
For all other types of statements, the return value is -1.
I'd really appreciate if someone could help me figure out how to fill two comboboxes data from two different tables. The code below doesn't seem to be working for me.
string command = "SELECT * FROM [Course]";
string command2 = "SELECT * FROM [Module]";
dbConnection db = new dbConnection();
SqlDataReader reader = db.commandExecute(command);
SqlDataReader reader2 = db.commandExecute(command2);
while (reader.Read())
{
comboBox2.Items.Add(reader["CourseID"].ToString());
}
while (reader2.Read())
{
comboBox1.Items.Add(reader["ModuleID"].ToString());
}
reader.Close();
reader2.Close();
db.connectionEnd();
Instead of using two queries you can try like this
string command = "SELECT * FROM [Course] UNION ALL SELECT * FROM [Module]";
If you have columns mismatch problem while joining query use NULL as Column1 for extra column
Eg-:
string command = "SELECT CUSTID AS ID FROM [Course] UNION ALL SELECT ModuleID AS ID FROM [Module]";
dbConnection db = new dbConnection();
SqlDataReader reader = db.commandExecute(command);
while (reader.Read())
{
comboBox2.Items.Add(reader["ID"].ToString());
}
reader.Close();
db.connectionEnd();
Update
I thought that you are going to add two table values in same comboxbox that's why posted above code.
Can you try this code it worked for me
SqlConnection con = new SqlConnection("Data Source=pcname;Initial Catalog=database;Persist Security Info=True;User ID=sa;Password=123");
SqlCommand cmd = new SqlCommand("SELECT * FROM [Course]", con);
SqlCommand cmd1 = new SqlCommand("SELECT * FROM [Module]", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
ComboBox1.Items.Add(dr(0).ToString);
}
}
dr.Close();
SqlDataReader dr1 = cmd1.ExecuteReader;
if (dr1.HasRows)
{
while (dr1.Read)
{
ComboBox2.Items.Add(dr1(0).ToString);
}
}
dr1.close();
con.close();
Hope this help you
Change your code
while (reader2.Read())
{
comboBox1.Items.Add(reader["ModuleID"].ToString());
}
with
while (reader2.Read())
{
// Change here the name of reader
comboBox1.Items.Add(reader2["ModuleID"].ToString());
}
I have created an Entity Framework application to retrieve Database values but i want to show them in individual labels instead of a gridview??
EmployEntities2 fd = new EmployEntities2();
int idToupdate = Convert.ToInt32(TextBox1.Text);
var jj = (from bn in fd.Contacts
where bn.Id == idToupdate
select bn);
GridView1.DataSource = jj;
GridView1.DataBind();
Established a connection
SqlConnection con = new SqlConnection("CONNECTION_STRING);
SqlCommand cmd = new SqlCommand();
and then,
cmd.CommandText = "select * from table where Condition ;
cmd.Connection = con
Label1.text = ((string)cmd.ExecuteScalar());
Try this one..
You should use SQLDataReader class. Base on what type of data you have in structure you should call a different method of the SQLDataReader object. For example, if you need to retrieve an integer value and display it in a label, this is the code sinppet to do it:
string queryString = "SELECT integer_value FROM table_name";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
label1.Text = reader.getSqlInt32(0).ToString();
}
reader.close();
}
This is the best I can do since you didn't provide additional info.
Check out this link for info on SqlDataReader class: SqlDataReader reference
int a ;
SqlCommand cmd = new SqlCommand (" Select * From items order by ItemID ", conn );
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
a = reader.GetInt32(0);
if (reader.HasRows == false)
{
dataGridView1.Visible = false;
}
else
{
dataGridView1.Visible = true;
DataTable dt = null;
dt = new DataTable();
dt.Load(reader);
dataGridView1.DataSource = dt;
if (reader.IsClosed == true)
{
break;
}
}
I want to ask that is the reader closed automatically, because here am not using reader.Close() and still it is closed? also , in my items table i have the first record as
ItemId | ItemName
1 Bag
2 Laptop
8 Weighing Machine
But, when this data is displayed in the datagridview then the row 1 , that is, the itemname "BAG" is not displayed. why so?
By calling Read(), you have already "claimed" the first row (hence why Bag isn't showing - because you aren't doing anything with it); and yet dt.Load is also going to do a while(reader.Read()). I expect you want (note I'm not calling Read here, and have no while loop):
if(reader.HasRows)
{
// load via dt.Load() and show
}
else
{
// hide
}
The reason it is exiting is that once you've called Load you've already read all the data, so there is nothing else to read. I honestly don't know whether getting to the end of the TDS stream implicitly closes the reader, but you should be using:
using(var cmd = new SqlCommand (" Select * From items order by ItemID ", conn))
using(var reader = cmd.ExecuteReader())
{
// everything else in here
}
You are loading the reader into the DataTable so the while(reader.Read()) loop is not required.
The first record is not displaying because reader.Read() has taken the first record and dt.Load() is starting from the second record.
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "SELECT * FROM teams";
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
dataGridView.Visible = true;
DataTable dt = new DataTable();
dt.Load(reader);
dataGridView.DataSource = dt;
}
else
{
dataGridView.Visible = false;
}
}
}
}
Even this too works fine for me
string strcon = ConfigurationSettings.AppSettings["Constring"].ToString();
MySqlConnection conn = new MySqlConnection(strcon);
MySqlCommand cmd = new MySqlCommand("Select * From items order by ItemID", conn);
conn.Open();
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
dataGridView1.Visible = true;
DataTable dt = null;
dt = new DataTable();
dt.Load(reader);
dataGridView1.DataSource = dt;
}