How to add items to a comboBox in C# from two tables? - c#

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());
}

Related

Autocomplete combobox with SQL Server database

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);
}

How to add items in ComboBox from database

Im trying to add items in the comboBox (cmbInstructor) namely the last names (instructorLN) however, my code does not seem to work. Any ideas on where I went wrong?
private void cmbInstructor_SelectedIndexChanged(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection(mycon);
MySqlCommand cmd = new MySqlCommand("SELECT * FROM instructor WHERE instructorType ='" + labelClass.Text + "'", conn);
string instructorLN = "";
conn.Open();
MySqlDataReader myReader = null;
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
instructorLN = myReader["instructorLN"].ToString();
}
cmbInstructor.Items.Add(instructorLN);
}
As far as I can see, you are adding only last value that your SELECT returns.
Move your
cmbInstructor.Items.Add(instructorLN);
line into to the while statement as;
while (myReader.Read())
{
cmbInstructor.Items.Add(myReader["instructorLN"].ToString());
}
By the way, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your connection and command and reader automatically.
using(var conn = new MySqlConnection(mycon))
using(var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM instructor WHERE instructorType = #type";
cmd.Parameters.Add("#type", labelClass.Text);
conn.Open();
using(var myReader = cmd.ExecuteReader())
{
while (myReader.Read())
{
cmbInstructor.Items.Add(myReader["instructorLN"].ToString());
}
}
}

Populate textbox with selected items from database

private void fillProduct() {
SqlConnection conn = new SqlConnection("Data Source=STATION21\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=true");
conn.Open();
string query = "Select prodID from product";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0) {
cmbPCode.DataSource = dt;
cmbPCode.DisplayMember = "prodID";
cmbPCode.ValueMember = "prodID";
}
private void cmbPCode_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=STATION21\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=true");
con.Open();
string query = "Select * from product where prodID = '"+cmbPCode.Text+"'".ToString();
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read()) {
tbdc.Text = dr["prodDescription"].ToString();
}
}
i am having trouble with getting my items from the database according to the selected index i get this error
Conversion failed when converting the varchar value
'System.Data.DataRowView' to data type int
can someone please help me how to convert SqlDataReader to String. because i notice that when i retrieve a column with varchar/string datatype i am not having this kind error but if i retrieve a column with int datatype i get this error.
Replace This:
string query = "Select * from product where prodID = '"+cmbPCode.Text+
"'".ToString();
With This:
string query = "Select * from product where prodID = "+cmbPCode.Text;
Suggestion: Your query is open to SQL Injection i would suggest you to use parameterised queries to avoid them.
Using Parameterised Queries:
string query = "Select * from product where prodID = #ID";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#ID",cmbPCode.Text);

Retrieving values from DB to Label in C#

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

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..

Categories