I have a winform project with an access file as a database.
In one of my forms I want the user to choose a company from a combobox.
(the list of campanies is in the access table)
How do I set the company name column to be combobox dropdown values ?
Try this
string qr1 = "select companyname from table1";
SqlCommand cmd1 = new SqlCommand(qr1, con);
con.Open();
SqlDataReader dr1 = cmd1.ExecuteReader();
cmbcat.Items.Clear();
while (dr1.Read())
{
cmbcat.Items.Add(dr1[0].ToString());
}
con.Close();
to Nimi
is this oledbcommand?
my solutions is ....
public void make_cbDispatch()
{
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;"
+ "Data Source=I:\\Projects\\project.accdb;"
+ "Persist Security Info=False;";
string qr1 = "SELECT DISTINCT object "
+ "FROM tList "
+ "ORDER BY object ";
OleDbConnection con = new OleDbConnection(ConnectionString);
OleDbCommand cmd1 = new OleDbCommand(qr1, con);
con.Open();
OleDbDataReader dr1 = cmd1.ExecuteReader();
cbDispatch.Items.Clear();
while (dr1.Read())
{
cbDispatch.Items.Add(dr1[0].ToString());
}
con.Close();
}
Related
Two ComboBoxes - cmbSupplier and cmbProduct
I want to fill cmbSupplier with supplier names from a table
when I select a value from cmbSupplier
depending on the name selected
Products with the supplier name should fill cmbProduct
private void frmAddOrder_Load(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("SELECT sup_name from tbl_supplier",con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
cmbSupplier.Items.Add(dr["sup_name"].ToString());
}
dr.Close();
}
this is the code I use to fill cmbSupplier
I tried using this code to fill cmbProducts but all I get is an error
private void cmbSupplier_SelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("SELECT Product_Name from tbl_SupplierItems WHERE supplier_name'" + cmbSupplier.Text + "%'", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
cmbProduct.Items.Add(dr["Product_Name"].ToString());
}
dr.Close();
}
The query is not correct.
Instead of
SqlCommand cmd = new SqlCommand("SELECT Product_Name from tbl_SupplierItems WHERE supplier_name'" + cmbSupplier.Text + "%'", con);
You should write
SqlCommand cmd = new SqlCommand("SELECT Product_Name from tbl_SupplierItems WHERE supplier_name = '" + cmbSupplier.Text + "%'", con);
I am trying to populate my textbox after selecting a value from my comboBox.
My code is running fine, I don't have any errors when I run it but when I select a value from my comboBox, it's not populating my textbox. See my code below.
private OleDbConnection connection = new OleDbConnection();
public Form1()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ASUS\Documents\appointment2.accdb";
}
private void Lastname_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string query = "select * from appointments where patientNo = '" + Lastname.Text + "' ";
command.CommandText = query;
Firstname.Text = reader["firstName"].ToString();
patientNum.Text = reader["patientNo"].ToString();
contactNum.Text = reader["contactNo"].ToString();
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
Two immediate issues that I see:
You are populating the CommandText property of the OleDbCommand object after issuing the ExecuteReader method, meaning there is no SQL statement being evaluated.
The SQL statement should be populated before the ExecuteReader method is issued, i.e.:
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * from appointments where patientNo = '" + Lastname.Text + "' ";
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Firstname.Text = reader["firstName"].ToString();
patientNum.Text = reader["patientNo"].ToString();
contactNum.Text = reader["contactNo"].ToString();
}
connection.Close();
The where clause of your SQL statement assumes that patientNo contains string data, which could be incorrect given the name of this field.
Just found out the issue. Had the wrong value to compare my Lastname.Text with and fixed the code's arrangement. Thanks for all your help everyone.
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * from appointments where lastName = '" + Lastname.Text + "' ";
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Firstname.Text = reader["firstName"].ToString();
patientNum.Text = reader["patientNo"].ToString();
contactNum.Text = reader["contactNo"].ToString();
}
connection.Close();
I am stuck on collecting 2 column values from a database row.
this method is only working to retrieve one value, not for 2. I need to save values from cells to Different variables then I will use these variables to populate another database.
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
using (var con2 = new SqlConnection(connectionString))
{
try
{
con2.Open();
SqlCommand command = new SqlCommand();
command.Connection = con2;
command.CommandText = string.Format("update Inventory set Quantity= Quantity - {0} WHERE id='"+tbItemid.Text+"'", Convert.ToInt32(tbQuantity.Text));
command.ExecuteNonQuery();
con2.Close();
Data();
DData();
con2.Open();
int x = int.Parse(tbQuantity.Text);
SqlCommand cmd1 = new SqlCommand("SELECT Model from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
modelRdr = cmd1.ExecuteReader();
string model = modelRdr["model"].ToString();
con2.Close();
con.Open();
int y = int.Parse(tbQuantity.Text);
SqlCommand cmd2 = new SqlCommand("SELECT Price from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader pricerdr = null;
pricerdr = cmd2.ExecuteReader();
pricerdr.Read();
int price = int.Parse(pricerdr["Price"].ToString());
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Bill values (" + tbItemid.Text + ",'" +model.ToString()+ "',"+price.ToString()+",'"+tbQuantity.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
Data();
}
catch
{
MessageBox.Show("Enter Catagory and Product ID");
}
}
First thing first you should use Parameterized Queries instead of Concatenations. These kind of queries are prone to SQL Injection. You can read both the columns in one command
SqlCommand cmd1 = new SqlCommand("SELECT Model, Price from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
modelRdr = cmd1.ExecuteReader();
string model = modelRdr["model"].ToString();
int price = int.Parse(modelRdr["Price"].ToString());
The complete code with Parameters would look like
string model=String.Empty;
int price = 0;
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(connectionString))
{
try
{
con2.Open();
using(SqlCommand command = new SqlCommand())
{
command.Connection = con2;
command.CommandText = string.Format("update Inventory set Quantity = Quantity - #qty WHERE id=#id";
command.Parameters.AddWithValue("#id", tbItemid.Text);
command.Parameters.AddWithValue("#qty", Convert.ToInt32(tbQuantity.Text)));
command.ExecuteNonQuery();
Data();
DData();
int x = int.Parse(tbQuantity.Text);
using(SqlCommand cmd1 = new SqlCommand("SELECT Model, Price from Inventory WHERE id=#id"))
{
cmd1.Parameters.AddWithValue("#id", tbItemid.Text);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
model = modelRdr["model"].ToString();
price = int.Parse(modelRdr["Price"].ToString());
}
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Bill values (#id,#model,#price,#qty)";.
cmd.Parameters.AddWithValue("#id", tbItemid.Text);
cmd.Parameters.AddWithValue("#model", model);
cmd.Parameters.AddWithValue("#price", price);
cmd.Parameters.AddWithValue("#qty", tbQuantity.Text);
cmd.ExecuteNonQuery();
}
Data();
}
catch
{
MessageBox.Show("Enter Catagory and Product ID");
}
}
}
My program will not update my SQL Server database after executing. When I run my program my DataGridView updates when I insert my information, but it will not update itself in the dataTable.
private void button1_Click(object sender, EventArgs e)
{
string query = "INSERT INTO dbo.dataTable(Id,Name,Age) VALUES('" + idTextBox.Text + "','" + nameTextBox.Text + "','" + ageTextBox.Text + "')";
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\employee.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd;
conn.Open();
cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
this.dataTableTableAdapter.Fill(this.employeeDataSet1.dataTable);
conn.Close();
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataTable data = new DataTable();
conn.Open();
adapt.Update(data);
conn.Close();
dataTableDataGridView.DataSource = data;
}
If you created your DataGridView using the designer which added a dataset, bindingsource, and tableadapter, then your DataGridView should be configured correctly out of the box. Try commented out these lines:
//SqlDataAdapter adapt = new SqlDataAdapter(cmd);
//DataTable data = new DataTable();
//conn.Open();
//adapt.Update(data);
//conn.Close();
//dataGridView1.DataSource = data;
I replicated your button_click code and it works locally for me using Sql Express.
Based on your comment i assume the cause is the missing conversion. Using Int32.TryParse you can convert the string to int. Be aware that the ' have to go as well
int id, age;
bool idIsInt = false, ageIsInt = false;
idIsInt = Int32.TryParse(idTextBox.Text, out id);
ageIsInt = Int32.TryParse(ageTextBox.Text, out age);
if(idIsInt && ageIsInt)
{
string query = "INSERT INTO dbo.dataTable(Id,Name,Age) VALUES("
+ id + ",'" + nameTextBox.Text + "',"
+ age + ")";
SqlConnection conn =
new SqlConnection(#"Data Source(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\employee.mdf
;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd;
conn.Open();
cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
}
I am a new member. Also, I am trying to add a record into 2 different tables (customerinfo & studentinfo). My code is below but it only records the textbox fields into the StudentInfo Table only. How should I go about it putting the record into 2 tables simultaneously?
Thanks
protected void btnRegister_Click(object sender, EventArgs e)
{
OleDbConnection mDB = new OleDbConnection();
mDB.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0;Data source="
+ Server.MapPath("~/App_Data/webBase.accdb");
mDB.Open();
Type csType = this.GetType();
//check to ensure that UserId keyed in is not being used by other Customers
OleDbCommand cmd;
OleDbCommand cmd1;
OleDbDataReader rdr;
OleDbDataReader rdr1;
string strSQLSelect = "SELECT sUserId FROM studentInfo ORDER BY sUserId";
string strSQLSelect1 = "SELECT cUserId FROM customerInfo ORDER BY cUserId";
cmd1 = new OleDbCommand(strSQLSelect1, mDB);
cmd = new OleDbCommand(strSQLSelect, mDB);
rdr = cmd.ExecuteReader();
rdr1 = cmd1.ExecuteReader();
this.txtPassword.Attributes.Add("value", this.txtPassword.Text);
// insert new record
string strSQLInsert = "INSERT INTO "
+ "studentInfo (sUserId,sPassword,sName,sAddress,sTel,sEmail,sLevel, sLevel2)"
+ "VALUES(#uid,#pw,#name,#addr,#em,#tel,#lvl,#lvl2)";
ClientScript.RegisterStartupScript(csType, "Successful!", scriptSuccessNewAccount);
cmd = new OleDbCommand(strSQLInsert, mDB);
cmd.Parameters.AddWithValue("#uid", txtUserId.Text);
cmd.Parameters.AddWithValue("#pw", txtPassword.Text);
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#addr", txtAddress.Text);
cmd.Parameters.AddWithValue("#em", txtEmail.Text);
cmd.Parameters.AddWithValue("#tel", txtTel.Text);
cmd.Parameters.AddWithValue("#lvl", DropDownList1.Text);
cmd.Parameters.AddWithValue("#lvl2", DropDownList2.Text);
string strSQLInsert1 = "INSERT INTO "
+ "customerInfo (cUserId,cPassword,cName,cAddress,cEmail,cTel,cCountry)"
+ "VALUES(#uid,#pw,#name,#addr,#em,#tel,#country)";
ClientScript.RegisterStartupScript(csType, "Successful!", scriptSuccessNewAccount);
cmd1 = new OleDbCommand(strSQLInsert1, mDB);
cmd1.Parameters.AddWithValue("#uid", txtUserId.Text);
cmd1.Parameters.AddWithValue("#pw", txtPassword.Text);
cmd1.Parameters.AddWithValue("#name", txtName.Text);
cmd1.Parameters.AddWithValue("#addr", txtAddress.Text);
cmd1.Parameters.AddWithValue("#em", txtEmail.Text);
cmd1.Parameters.AddWithValue("#tel", txtTel.Text);
cmd1.Parameters.AddWithValue("#country", txtCountry.Text);
cmd.ExecuteNonQuery();
mDB.Close();
It looks like you're missing
cmd1.ExecuteNonQuery()
for the other table.