How to make combo box fill my database? - c#

I have code like that to fill that combo box fill my database
but cant .getString("NameCompany") error why ? the full code is here
private void FillCombobox()
{
cmd = new SqlCommand("Select * From Penawaran", con);
SqlDataReader dr;
string sName = dr.GetString("NameCustomer");
cbxNamaCustomer.Items.Add(sName);
}

First of all, you need to obtain your reader via the command, and assign it to the data reader. Once you've done so, iterate through each record. The connection you're passing through the SqlCommand constructor isn't defined anywhere. This will result in a NullReferenceException being thrown.
private void FillCombobox()
{
cmd = new SqlCommand("Select * From Penawaran", con);
SqlDataReader dr = cmd.ExecuteReader();
while(dr.read())
{
string sName = dr.GetString(0); // this should be the ordinal for the column you're trying to obtain.
cbxNamaCustomer.Items.Add(sName);
}
}

Related

C# Query MS-Access Table and place read values from column in a text box

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.

Fill combobox with only 1 kind of data

Assuming that i have the database items:
Hello
Hello
Hello
I just want to display only one "Hello"
Here is my code....
OleDbCommand cmd = new OleDbCommand("Select *from login", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
combo1.Items.Add(dr["dtlogin"].ToString());
}
var value = dr["dtlogin"].ToString();
if (!combo1.Items.Contains(value))
{
combo1.Items.Add(value);
}
Check for the item before adding using Contains
if(!combo1.Items.Contains(dr["dtlogin"].ToString()))
{
combo1.Items.Add(dr["dtlogin"].ToString());
}
If you r looking for distinct value's to be bind to ur combobox then use this.
OleDbCommand cmd = new OleDbCommand("Select distinct * from login", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
combo1.Items.Add(dr["dtlogin"].ToString());
}
You can just use ExecuteScalar to get first column of the first row. Other rows are ignored.
I assume they are string, you can do;
using(OleDbCommand cmd = new OleDbCommand("Select dtlogin from login", con);)
{
string s = (string)cmd.ExecuteScalar();
combo1.Items.Add(s);
}
Also use using statement to dispose your OleDbCommand and con.

Search and display certain table element

I'm trying to search my local database table and simply display all it's columns.
I start my sending in
SearchID("1234");
My code so far:
private static void SearchID(string CostumerID)
{
string conStr = #"Data Source = C:\Users\secwp_000\documents\visual studio 2012\Projects\Module5\Module5\Orderdatabase.sdf";
DataSet ds = new DataSet();
SqlCeConnection con = new SqlCeConnection(conStr);
SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM [Order]", con);
SqlCeDataReader dr = cmd.ExecuteReader();
SqlCeDataAdapter adapt = new SqlCeDataAdapter(cmd);
adapt.Fill(ds, "Order");
while (dr.Read())
{
string str = (string)dr[1];
if (str == CostumerID)
{
Console.WriteLine(str);
}
}
}
Where am I thinking wrong?
It stops on
SqlCeDataReader dr = cmd.ExecuteReader();
saying i don't have a connection. But just sounds wierd, because I've just had connection..
You have to open connection using
If(con.state.toString()=="closed")
con.open();
I observe a fault in your query why are you compare your result after fetch from database.you can directly filter in SQL query
Select * from order where table.customer_Id = customerId
You have a connection but you haven't opened it yet:
con.Open();
adapt.Fill(ds, "Order");
con.Close();
In addition you should use using statements for disposable objects like SqlConnection and SqlCommand to make sure they will be disposed properly:
using(SqlCeConnection con = new SqlCeConnection(conStr))
using(SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM [Order]", con))
{
}
I feel so stupid for not seeing this, haha. And it worked! But it wont display anything from the table,
while (dr.Read())
{
string str = (string)dr[1];
if (str == CostumerID)
{
Console.WriteLine(str);
}
}
Following instructions given to me, there is nothing wrong with this code, and it could display Order with costumerID 1234.

How to populate data from SQL Server database columns to textboxes

I want to populate data from a SQL Server database from many columns to many textboxes .. I have a code to populate just one box .. can someone edit my code... I want to pull data and show it in Name, Address, Telephone No and Date ... plz help .. this code works for only one textbox..
Thanks in advance
SqlConnection Conn = new SqlConnection(#"Data Source=rex;Initial Catalog=PersonalDetails;Integrated Security=True");
SqlCommand Comm1 = new SqlCommand("Select * From PersonalUsers ", Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
if (DR1.Read())
{
Name.Text = DR1.GetValue(0).ToString();
}
while (DR1.Read())
{
if(DR1.GetName() == "YourSQLColumnName")
{
YourTextBox.Text = (string) DR1["YourSQLColumnName"];
}
// Your Other textboxes and columns which you want to match should follow as this template
}
SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, _conn);
SqlDataReader rdr = cmd.ExecuteReader();
System.Data.DataTable tbl = new System.Data.DataTable("Results");
tbl.Load(rdr);
if (tbl.Rows.Count > 0)
Name.Text = tbl.Rows[0]["column_name"].ToString();
string cs=System.Configuration.ConfigurationManager.ConnectionString["DBCS"].ConnectionString;
using(OracleConnection con=new OracleConnection(cs))
{
sql="select empname from Emp where empno='"+empno+"'";
OracleCommand cmd = new System.Data.OracleClient.OracleCommand(sql,con);
con.Open();
OracleDataReader rdr = cmd.ExecuteReader();
if(rdr.Read())
{
EmpName.Text=Convert.ToString(rd["empname"]);
}
}
I assume that you would like to take care of both more rows and more columns.
Try to specify the columns. It works without, but the performance is better if you do so.
I assume you have a class called PersonalUser with the specifed properties.
It is also nice to have it in an sorted order, so I added that
public List<PersonalUser> FetchMyData()
{
SqlConnection Conn = new SqlConnection(#"Data Source=rex;Initial Catalog=PersonalDetails;Integrated Security=True");
SqlCommand Comm1 = new SqlCommand("Select Name, Address, TelephoneNo,Date From PersonalUsers order by Name", Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
var result = new List<PersonalUser>();
while (DR1.Read())
{
result.Add(new PersonalUser {
Name = DR1.GetString(0);
Address= DR1.GetString(1);
TelephoneNo = DR1.GetString(2);
Date = DR1.GetString(3)
}
);
}
return result;
}
I would also, if the need is getting much complex than this, conidering using Entity Framwork..

DataReader error - "no data exist for the row/column" - when data exists?

I need some help in understanding my error. I want to read data from table, however I get error such as "no data exist for the row/column". I dont understand it, since I actually have rows and columns in there. WinForms. Thanks!
//this is how i insert data into table, works fine
public void b1_Click(object sender, EventArgs e)
{
SqlCeCommand command = new SqlCeCommand("INSERT INTO tbl1(Name, LastName) VALUES (#Name, #LastName)", conn);
command.Parameters.AddWithValue("#Name", l1.Text);
command.ExecuteNonQuery();
}
//this is how i try to read data from the same table
public void b2_Click(object sender, EventArgs e)
{
SqlCeConnection conn = new SqlCeConnection(#"Data Source=C:test.sdf");
conn.Open();
SqlCeCommand command = new SqlCeCommand("SELECT * FROM tbl1", conn);
SqlCeDataReader reader = command.ExecuteReader();
//error here
string Name = reader.GetString(0);
label.Text = Name;
}
Problem is with your results' loading.
SqlCeDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string Name = reader.GetString(0);
}
So you use the Read method to iterate through the results. Or, if you just have one result then you can also use the ExecuteScalar
string Name = reader.ExecuteScalar().ToString();
In this sequence
SqlCeCommand command = new SqlCeCommand("INSERT INTO tbl1(Name, LastName) VALUES (#Name, #LastName)", conn);
command.Parameters.AddWithValue("#Name", l1.Text);
command.ExecuteNonQuery();
You're not setting the 2nd parameter #LastName so it should have failed. If you didn't previously have records in the table, you would have nothing to select from.
That, and the fact that you are not calling reader.Read()

Categories