I have little problem I am trying to add sequenced numbers in front the data that I will retrieve from a SQL Server database as shown below.
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection(#"Server=.;database=test;integrated security=false;user id=sa;pwd=#admin00");
SqlCommand com = new SqlCommand();
SqlDataReader dr;
public Form1()
{
InitializeComponent();
com.CommandText = "select book_name from Table_book";
com.Connection = con;
con.Open();
dr = com.ExecuteReader();
while (dr.Read())
{
for (int i = 1; i <= dr.FieldCount; i++)
{
listBox1.Items.Add(i+"-"+dr[0].ToString());
i += i;
}
}
if (listBox1.Items.Count == 0)
{
MessageBox.Show("No Data Found");
}
dr.Close();
con.Close();
}
And the result will be like that:
TY all
I just use my server Id sequence to solve the problem like that:
SqlConnection con = new SqlConnection(#"server=.;database=test;integrated security=false;user id=sa;pwd=#admin00");
con.Open();
SqlCommand sqlcom = new SqlCommand("select book_id,book_name from Table_book", con);
SqlDataReader sqlDR=sqlcom.ExecuteReader();
while(sqlDR.Read())
{
listBox1.Items.Add(sqlDR["book_id"].ToString()+"-"+sqlDR["book_name"].ToString());
}
Add is capable of operating on objects, not just on strings.
Why?
class ModelClass {
// for use in algorithm, may be presented in GUI or not
int Sequence { get; set; }
string Description { get ; set ;}
// ... what You want, is is typical model class
override string ToString() {
// return what you want, is presented in GUI
return Descrition;
}
ModelClass( string n, int i ) ...
}
...
listBox.Items.Add( new ModelClass(i.ToString(), dr[...] // sequence )
Now you can check whatever you want from Items, because these are objects of ModelClass.
Code written by hand, non tested in IDE.
You're setting the "sequence number" to the number of fields returned in the results while iterating over each row with the dr.Read().
It's unnecessary for the for loop. What you should be doing is setting your counter variable outside of the dr.Read() and then incrementing it inside...
int i = 1;
while (dr.Read())
{
// set listbox item text
listBox1.Items.Add(i.ToString() + "-" + dr[0].ToString());
i+=1;
}
Related
This is the code i am using to select Maximum RollNo based on Class field value.
But when there is no data about Class Field in Table. Then Error is generated.
using (var conn = new OleDbConnection(DatabaseObjects.ConnectionString))
{
conn.Open();
command = new OleDbCommand("select max(RollNo) as Roll from Students where Class = '"+cmbClass.Text+"'", conn);
OleDbDataReader dr = command.ExecuteReader();
if (!dr.IsDBNull(0))
{
while (dr.Read())
{
i = Convert.ToInt32(dr["Roll"]);
}
}
InvalidOperation Exception is occurring. I want to get value of RollNo if data is available in Table. If data is not available in Table then what should I do?
you are inversing the steps :
open the connection;
check is there is comming data;
check if the value is not null;
read the data;
try this :
while (dr.Read())
{
if (!dr.IsDBNull(0))
{
i = Convert.ToInt32(dr["Roll"]);
}
}
while your are attending just single value, use executeScalar to get the value ;
conn.Open();
command = new OleDbCommand("select isnull(max(RollNo),-1) as Roll from Students where Class = '"+cmbClass.Text+"'", conn);
int rollNo = (int) command.ExecuteScallar();
if(rollno !=-1)
{
// TODO :
}
I was trying to add a combo box which could get all the product name but unfortunately I follow some tutorials and end up like this.
void fillCombo()
{
try
{
con.Open();
OleDbCommand command = new OleDbCommand("Select * from IblInventory");
command.Connection = con;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
String product = reader.GetString("ProductName"); // << invalid argument
cmbProduct.Items.Add(product);
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
What could possibly the reason?
From the documentation of OleDbDataReader.GetString you will notice that the argument required by the method is an integer representing the position of the column in the returned record not its name.
If you (rightly) prefer to use the column name then you need to take a detour and use the GetOrdinal method to retrieve the position of the column given the name.
while (reader.Read())
{
int pos = reader.GetOrdinal("ProductName");
String product = reader.GetString(pos);
cmbProduct.Items.Add(product);
}
Another example, practically identical to your situation, can be found in the documentation page on MSDN about OleDbDataReader.GetOrdinal
It is also a common practice to write an extension method that allows you to write code as yours hiding the details of the mapping between name and position. You just need a static class with
public static class ReaderExtensions
{
public string GetString(this OleDbDataReader reader, string colName)
{
string result = "";
if(!string.IsNullOrEmpty(colName))
{
int pos = reader.GetOrdinal(colName);
result = reader.GetString(pos);
}
return result;
}
... other extensions for Int, Decimals, DateTime etc...
}
Now with this class in place and accessible you can call
string product = reader.GetString("ProductName");
it is working in my project
First fill your data in to datatable see the below code
DataTable results = new DataTable();
using(OleDbConnection conn = new OleDbConnection(connString))
{
OleDbCommand cmd = new OleDbCommand("Select * from IblInventory", conn);
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(results);
}
Now
cmbProduct.DataSource = results ;
cmbProduct.DisplayMember = "ProductName";
cmbProduct.ValueMember = "Id feild of IblInventory table";
Only one time, thank you for help !
Public string panda(string lola = #"Server=.\SQLEXPRESS; DataBase=panda; Integrated Security=true;")
{
SqlConnection panda = new SqlConnection(lola);
panda.Open();
return lola;
}
public string Show_details(string Command = "Select name From panda")
{
SqlConnection cn = new SqlConnection(panda());
SqlCommand Show;
SqlDataReader read;
Show = new SqlCommand(Command, cn);
cn.Open();
read = Show.ExecuteReader();
while (read.Read())
{
listBox1.Items.Add(read["name"]);
}
return Command;
}
private void button3_Click(object sender, EventArgs e)
{
Show_details();
}
I'm looking for how to make the reader read data and post it in the listbox only one time !
If I understood your question correctly, you only want to go inside the reader loop once. 'While', no pun intended, there are more efficient ways to go about this, you could declare a bool flag to see if you've hit the loop yet. Once inside the loop, change it to false so when the next time while condition is evaluated, it will evaluate to false ending the loop. See below.
public string Show_details(string Command = "Select name From panda")
{
SqlConnection cn = new SqlConnection(panda());
SqlCommand Show;
SqlDataReader read;
Show = new SqlCommand(Command, cn);
cn.Open();
read = Show.ExecuteReader();
// Declare flag to see if you've hit the reader yet.
bool hasntYetRead = true;
// Add a second condition to determine if to cursor through again
while (read.Read() && hasntYetRead )
{
listBox1.Items.Add(read["name"]);
// Change the flag to false
hasntYetRead = false;
}
return Command;
}
You could use a counter if you want to be able to change the number or iterations in the future.
public string Show_details(string Command = "Select name From panda")
{
SqlConnection cn = new SqlConnection(panda());
SqlCommand Show;
SqlDataReader read;
Show = new SqlCommand(Command, cn);
cn.Open();
read = Show.ExecuteReader();
// declare counter
int counter = 0;
// Add a second condition to determine if to cursor through again
while (read.Read() && counter < 1) //could get counter to count to user input number
{
listBox1.Items.Add(read["name"]);
// Change the flag to false
counter++;
}
return Command;
}
I am trying to show number of rows from a grid view using a label. I used SQL Count statement but it doesn't work. The problem is I only get only number 1 shown in the label which is not matched with the number of rows I have in my table! I have posted similar question but unfortunately no body gave a clear answer!
My codes as:
Basket.ac
public int td()
{
int customers;
//I tried this select query but still gets number 1
//String sql = String.Format("SELECT COUNT(*) FROM dbo.Baskets");
string sql = string.Format("SELECT COUNT(*) FROM Baskets");
customers = Db.RunQuery(sql).Rows.Count;
//customers = Convert.ToInt32(Db.RunQuery(sql).Rows.Count);
return customers;
}
DataBaseConn.ac
public class DataBaseConn
{
SqlConnection conn;
SqlCommand cmd;
DataTable tbl;
private void Intialise(CommandType commandtype, string DataBase)
{
conn = new SqlConnection();
cmd = new SqlCommand();
//Requirements
conn.ConnectionString = ConfigurationManager.ConnectionStrings[1].ToString();
cmd.Connection = conn;
cmd.CommandType = commandtype;
cmd.CommandText = DataBase;
conn.Open();
}
public int RunProcedure(string Procedure, SortedList ParameterV)
{
Intialise(CommandType.StoredProcedure, Procedure);
for (int i = 0; i < ParameterV.Count; i++)
try
{
if (ParameterV.GetByIndex(i) != null)
cmd.Parameters.AddWithValue(ParameterV.GetKey(i).ToString(),
PrameterV.GetByIndex(i).ToString());
}
catch { ;}
return RunUpdate();
}
public int RunUpdate(string InsDelUpd)
{
Intialise(CommandType.Text, InsDelUpd);
return RunUpdate();
}
private int RunUpdate()
{
try
{
int x = cmd.ExecuteNonQuery();
conn.Close();
return x;
}
catch (SqlException ex)
{
conn.Close();
return ex.Number;
}
}
public DataTable RunQuery(string Select)
{
Intialise(CommandType.Text, Select);
tbl = new DataTable();
tbl.Load(cmd.ExecuteReader());
conn.Close();
return tbl;
}
public bool EData(string selection)
{
if (RunQuery(selection).Rows.Count > 0)
return true;
else
return false;
}
}
Basket.aspx
lblQueue.Text = _b.td().ToString();
You don't want to return the data table's .Rows.Count - this will always be 1 (as in 1 row(s) affected) for your count(*) query.
You should instead look at using ExecuteScalar to return the first column of the first row from your query
I'm not sure how you want to build this into your DataBaseConn data helper class, but the gist of it is you need the following sequence:
using (var conn = new SqlConnection(connectionStringHere))
using (var cmd = new SqlCommand(conn))
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT COUNT(*) FROM Baskets";
return (int)cmd.ExecuteScalar();
}
Edit
If you aren't able to extend your DataBaseConn helper with an ExecuteScalar, then I guess you'll be able to use the existing RunQuery method which returns a DataTable. Just scrape the first column of the first row like so:
return Db.RunQuery(sql).Rows[0].Field<int>(0);
As a side note, you might look at replacing your DataHelper entirely with the Microsoft Patterns and Practices Data Application Access Block (DAAB), or, if you prefer, look at using an ORM like Entity Framework. By upgrading to a mainstream Data Access encapsulation, you won't need to spend as much time debugging data access issues like this one :)
I'm using c# in a ASP.Net web application.I have the following query:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from personal,Intrebari where personal.cod_numeric_personal=#cnp AND Intrebari.id_intrebare=14 AND Intrebari.id_intrebare=15 ", con);
cmd.Parameters.AddWithValue("#cnp", Session["sesiune_cnp"]);
SqlDataReader rdr;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
lbl1.Text = rdr["Nume"].ToString();
intrebare6.Text = rdr["Intrebari"].ToString();
intrebare7.Text = rdr["Intrebari"].ToString();
}
I want those two values for id_intrebare=14 and 15 to assign it to those 2 labels.How can i refer to those?
In order to read stuff from the reader you need to include it in the select statement for you sql, it is better to select it explicitly rather than use select *.
but you are not currently going to get any results returned because id_intrebare cannot be both 14 and 15
you then need to read id_intreabare ratherr than Intreabari.
Try this, notice the try catch block, I also changed your SQL query.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);
string qry="select * from personal,Intrebari where personal.cod_numeric_personal=#cnp AND Intrebari.id_intrebare IN (14,15);
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#cnp", Session["sesiune_cnp"]);
try
{
con.Open();
SqlDataReader rdr= cmd.ExecuteReader();
if(rdr.HasRows)
{
while (rdr.Read())
{
lbl1.Text = rdr["Nume"].ToString();
intrebare6.Text = rdr["Intrebari"].ToString();
intrebare7.Text = rdr["Intrebari"].ToString();
}
}
}
catch(SQLException ex)
{
lblStatus.Text="An error occured"+ex.Message;
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
If you want to assign texts to different numbered lables in a loop, you can refer to the control id with FindControl of the current page
int numeOrdinal = reader.GetOrdinal("Nume");
int intrebariOrdinal = reader.GetOrdinal("Intrebari");
int i = 1;
while (rdr.Read()) {
// Nume (Romanian) = Name
page.FindControl("lbl" + i).Text = reader.IsDBNull(numeOrdinal)
? ""
: rdr.GetString(numeOrdinal);
// Intrebari (Romanian) = Question
page.FindControl("intrebari" + i + 5).Text = reader.IsDBNull(intrebariOrdinal)
? ""
: rdr.GetString(intrebariOrdinal);
i++;
}
Try using cmd.ExecuteScalar it will return the first reuslt it finds so you have to define your conditions well. Also it returns object type so you will have to cast the result