Put content of access database into two listboxs - c#

Hi I have a database with two tables: 1.) Country (Table name: 2.) Website
Every country has 1 or more websites.
I am trying to make a C# WindowsForm Application where I want the User first to select a country from the first listbox1 and then all the Websites will in the second listbox2 based on the database.. I somehow can't display all the countries in the first textbox using a select statement: the code is the following
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT CountryName FROM Countries ";
//whenever you want to get some data from the database
using (OleDbDataReader reader = command.ExecuteReader())
{
listBox.Items.Add(reader);
}
//OleDbDataReader reader = command.ExecuteReader();
connection.Close();
}
catch(Exception l)
{
MessageBox.Show("Error:" + l);
}
This code doesn't show the items in the listbox.
Can someone please advise ?

You probably want to get your data from the reader and convert it to an object before you put it in the listbox. You can get the value for each column by reader["columnname"]. Dont forget that you also need to convert each value to its proper type, you will probably find all types of conversion you need in System.Convert.
With your scenario in mind you should be able to do
using (OleDbDataReader reader = command.ExecuteReader())
{
while(reader.Read())
{
listBox.Items.Add(reader["CountryName"].ToString());
}
}

You are trying to add the OleDbDataReader as a listbox item instead of using it to read the data, here is an example of how to use it :
try
{
connection.Open();
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = connection;
command.CommandText = "SELECT CountryName FROM Countries ";
//whenever you want to get some data from the database
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.NextResult())
{
listBox.Items.Add(reader.GetString(0));
}
}
}
}
catch (Exception l)
{
MessageBox.Show("Error:" + l);
}
finally
{
connection.Close();
}

Related

SQL Ntext Items Only Having the First Two Chars Read in

I am currently programming a C# program that lets students log into an interface, check grades, etc.. Admins can create new users. The student IDs are 9-digit codes that all begin with "95." When an admin is creating a new user, I want to go through the database to make sure that the ID number they have entered isn't already taken.
To do this, I have the following code:
connection.Open();
readerUsers = commandUsers.ExecuteReader();
while (readerUsers.Read())
{
MessageBox.Show(readerUsers[2].ToString());
if(readerUsers[2].ToString() == IDNum)
{
userAlreadyExists = true;
break;
}
}
connection.Close();
And in my Users table, which readerUsers and commandUsers are connected to, I have the following:
IDuser Username 95Number Password Active Admin
-------------------------------------------------------------
1 sward 951619984 uo99lb True True
... ... ... ... ... ...
Now, when I went to test my code by creating a user with the ID number of 951619984 (a number already entered in the database), userAlreadyExists would still remain false. So I made the program show a message box of each item in the 95Number column (which is of type Ntext). Every time, the message box would only show "95".
I am very new to programming with databases, so I apologize if this is a very newby question, but I'm not sure what to do to get the whole string from this ntext column. Could someone explain what I'm doing wrong? Thank you for your time.
Here is a better way of doing that:
var connstr = ConfigurationManager.ConnectionStrings["your key"].ConnectionString;
var sql = "SELECT COUNT(*) FROM Users WHERE [95number]=#num";
using (var conn = new SqlConnection(connstr))
using (var cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add("num",SqlDbType.Int).Value = IDNum;
conn.Open();
var result = cmd.ExecuteScalar();
userAlreadyExists = result > 0;
}
I did mines this way.
string Qstring = "Select 95number where 95number = '95#########'";
using (SqlConnection Con = new SqlConnection(Form1.ConnectionStringGen))
using (SqlCommand Com = con.CreateCommand())
{
Com.CommandText = Qstring;
con.Open();
using (SqlDataReader Reader = Com.ExecuteReader())
{
if(Reader.Read())
{
string 95Numb = Reader["95Number"].ToString();
Messagebox.show(95Numb);
userAlreadyExists = true;
//meaning if the reader reads an item it will prompt
}
else
{
userAlreadyExists = false;
}
}
con.Close();
}
}
catch (Exception)
{
throw;
}

make many mysql command in one connection in c# visual studio & unknown column in where clause

I have mySql database contains ID, projectName, companyName, projectNum, .. etc
I need to create Combobox that display projectName (project name isn't unique)
when I try to execute this the following error appears:
"Unknown column 'proj2' in where clause"
even though when I try to print this value it prints successfully in my code.
so I changed to display ID in Combobox and works well
now I need if I choose one ID to fill some fields (projectName, companyName, projectNum) then display values in other Combobox (e.g Combobox2) it has item number which is not unique and it
depend on projectName field.
I try to make one connection and two connection but both of them didn't work.
nothing appears in Combobox2
when I try to choose ID from first Combobox the same error appears:
"Unknown column 'proj2' in where clause"
I don't know if should I change the design of the database.
again I should mention that project name, company name, project number may be repeated in more than 50 records.
below is the code
first function to fill the first Combobox:
private void Form2_Load(object sender, EventArgs e)
{
try
{
// String getQuery = "Select projectName From ubc.BOQ_Table Group By projectName";
String getQuery = "Select ID From ubc.BOQ_Table";
connection.Open();
MySqlCommand command = new MySqlCommand(getQuery, connection);
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
comboBox1.Items.Add(reader.GetString("ID"));
}
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
}
second function to fill fields depend on choosing ID:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
//get vaalue of selected project
selectedProject = comboBox1.SelectedItem.ToString();
String selectQuery = "Select * From ubc.BOQ_Table where ID=" + selectedProject;
connection.Open();
MySqlCommand command = new MySqlCommand(selectQuery, connection);
MySqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
projectNameText.Text = reader.GetString("projectName");
projectName = projectNameText.Text;
companyNameText.Text = reader.GetString("companyName");
projectNumber.Text = reader.GetInt32("projectNumber").ToString();
reader.Close();
}
command.CommandText = "Select itemNum From ubc.BOQ_Table where projectName=" + projectName;
command.ExecuteNonQuery();
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
comboBox2.Items.Add(reader.GetString("itemNum"));
}
}
reader.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
}
This line of code is causing the problem:
command.CommandText = "Select itemNum From ubc.BOQ_Table where projectName=" + projectName;
As commenters have mentioned, concatenating strings is causing both the syntax error and makes your code vulnerable to SQL injection attacks. The solution is to use "parameterized queries" by putting the variable in a MySqlParameter object.
command.CommandText = "Select itemNum From ubc.BOQ_Table where projectName=#projectName;";
command.Parameters.AddWithValue("#projectName", projectName);
using (var reader = command.ExecuteReader())
{
// ...
(You may find some people saying "don't use AddWithValue", but that's an objection that applies just to SqlCommand; there's no good reason to avoid using it with MySqlCommand.)

C# SQL multiple query results into diffrent textbox

So I'm having this :
Conn.Open();
SqlCommand Comm3 = new SqlCommand("SELECT answer" + " FROM answers" + " WHERE id_answer=5" , Conn);
SqlDataReader DR3 = Comm3.ExecuteReader();
And there is multiple results,how can I now move each of them in diffrent textbox (i already created textboxes? Till now i only managed to get same result into them.
this is normally how i do it....
SqlConnection cn = new SqlConnection("my connection string");
cn.Open();
string sql = "select * from table where column = whatever";
using (SqlCommand cmd = new SqlCommand(sql,cn))
{
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
myTextBox1.Text = (string)dr["Column1"];
myTextBox2.Text = (string)dr["Column2"];
myTextBox3.Text = (string)dr["Column3"];
}
dr.Close();
}
cn.Close();
just make sure you are aiming the right column name while looping through them, and cast correctly.
You need to loop through each of the item in the Database table. Think of a foreach loop, where you simply just go through each item and work on it similarly.
Here is a sample for that,
// Create new SqlDataReader object and read data from the command.
using (SqlDataReader reader = command.ExecuteReader())
{
// while there is another record present
while (reader.Read())
{
// write the data on to the screen
textBox.Text = reader[0];
}
}
This will add the value of reader's first column (answer) to the textBox. Now make sure you're calling correct textBox to add the value to.
http://www.codeproject.com/Articles/823854/How-to-connect-SQL-Database-to-your-Csharp-program Do give this article a read.

MySql "Select Where" and C#

How can i read the return value from "Select Where" statement , every time i run no return value appear in the label, and no syntax error.
command.CommandText = "select product_price from product where product_name='"+x+"';";
connection.Open();
Reader = command.ExecuteReader();
while(Reader.Read()){
Price_label.Content = "" + Reader.GetString(0);
}
connection.Close();
If the product_price column is not of type TEXT in MySQL, the Reader.GetString(0) will (depending on how the reader was implemented by Oracle) throw an Exception or return an empty string. I would think the latter is happening.
Retrieving the value through a DataReader requires you to know the data type. You can not simply read a string for every type of field. For example, if the field in the database is an Integer, you need to use GetInt32(...). If it is a DateTime use GetDateTime(...). Using GetString on a DateTime field won't work.
EDIT
This is how I'd write this query:
using (MySqlConnection connection = new MySqlConnection(...))
{
connection.Open();
using (MySqlCommand cmd = new MySqlCommand("select product_price from product where product_name='#pname';", connection))
{
cmd.Parameters.AddWithValue("#pname", x);
using (MySqlDataReader reader = cmd.ExecuteReader())
{
StringBuilder sb = new StringBuilder();
while (reader.Read())
sb.Append(reader.GetInt32(0).ToString());
Price_label.Content = sb.ToString();
}
}
}
To append to my comment, your approach has three problems which are not part of your problem:
SQL-Injection, always use parameterized queries.
Leaking resources, IDisposable-Objects need to be treated properly.
Bad habits, "" + string for casting is...uhhh...not good and not necessary.
So, a more correct version for your code would look like this:
// using utilizes the IDisposable-Interface, whcih exists to limit the lifetime
// of certain objects, especially those which use native resources which
// otherwise might be floating around.
using(YourConnectionType connection = new YourConnectionType("connectionstring"))
{
connection.Open(); // You might want to have this in a try{}catch()-block.
using(YourCommandType command = connection.CreateCommand())
{
command.CommandText = "select product_price from product where product_name=#NAME;";
command.Parameters.Add("NAME", YourTypes.VarChar);
command.Parameters[0].Value = x; // For your own sanity sake, rename that variable!
using(YourReaderType reader = command.ExecuteReader())
{
while(reader.Read()) // If you're expecting only one line, change this to if(reader.Read()).
{
Price_label.Content = reader.GetString(0);
}
}
}
} // No need to close the conenction explicit, at this point connection.Dispose()
// will be called, which is the same as connection.Close().
you have to create a variable of your reader
command.CommandText = "select product_price from product where product_name='"+x+"';";
try {
connection.Open();
SqlReader reader = command.ExecuteReader();
while(reader.Read()){
Price_label.Content = "" + Reader.GetString(0);
}
} catch (Exception) {}
finally {
connection.Close();
}
You should write #pname without '' otherwise it won't work.
instead of:
select product_price from product where product_name='#pname'
you should write like this:
select product_price from product where product_name=#pname

Get SQL data And show it in a text box?

In the last few days I am trying to get data from my SQL table and get it into my textbox.
The table name : "check".
The code I am using :
SqlDataReader myReader = null;
connection = new SqlConnection(System.Configuration.ConfigurationManager
.ConnectionStrings["ConnectionString"].ConnectionString);
connection.Open();
var command = new SqlCommand("SELECT * FROM [check]", connection);
myReader = command.ExecuteReader();
while (myReader.Read())
{
TextBox1.Text = myReader.ToString();
}
connection.Close();
I am getting nothing as a result. Anyone know why? Maybe I am not calling the SQL correctly?
using (var connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT ColumnName FROM [check]";
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
TextBox1.Text = reader["ColumnName"].ToString();
}
}
Some comments:
don't use *, specify only those fields that you need
use using - less code, guaranteed disposal
I assume this is a test program, otherwise it does not make sense to reset Text to a in the loop
TextBox1.Text = myReader["fieldname"].ToString();
also I think you can change while with if because for every row from your table you'll overwrite textbox text!
Try this:
TextBox1.AppendText(myReader["columnname"].ToString());

Categories