Get value of combobox2 from combobox1 - c#

I got 2 comboboxes on my form(in the form load event). First combobox gets a value from a select statement once the form loads. I want to use that value in my second combobox. Here is my code:
1ste Combobox = cbDelivery
OracleConnection conn = new OracleConnection();
conn.ConnectionString = "User Id=christob;Password=CHRISTOB;Host=poseidon;Pooling=true;Min Pool Size=0;Max Pool Size=100;Connection Lifetime=0;Port=1522;Sid=GLODCD";
conn.Open();
string query;
query = "select distinct dd.delivery_bay_code from dc_delivery dd, dc_grv dg where delivery_complete_datetime is null and dd.dc_delivery_id_no = dg.dc_delivery_id_no and dd.delivery_announce_datetime is null";
OracleCommand cmd = new OracleCommand(query, conn);
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cbDelivery.Items.Add(dr["delivery_bay_code"]);
}
dr.Close();
conn.Close();
2de Combobox = cbOrderNo
This combobox is in:
private void cbDelivery_SelectedIndexChanged(object sender, EventArgs
e)
so as soon as I select a value from 1ste combobox my 2nd combobox query must populate the 2nd combobox. See code:
OracleConnection conn = new OracleConnection();
conn.ConnectionString = "User Id=christob;Password=CHRISTOB;Host=poseidon;Pooling=true;Min Pool Size=0;Max Pool Size=100;Connection Lifetime=0;Port=1522;Sid=GLODCD";
conn.Open();
string query1;
query1 = "select distinct dg.order_no from dc_delivery dd, dc_grv dg where delivery_complete_datetime is null and dd.dc_delivery_id_no = dg.dc_delivery_id_no and dd.delivery_announce_datetime is null and dd.delivery_bay_code = " + cbDelivery.Text;
OracleCommand cmd1 = new OracleCommand(query1, conn);
OracleDataReader dr1 = cmd1.ExecuteReader();
while (dr1.Read())
{
cbOderNo.Items.Add(dr1["order_no"]);
}
dr1.Close();
conn.Close();
Note I'm using cbDelivery combobox in my second Select query.
Problem is:
As soon as I select a value from my first combobox the second gives an exception ""ORA-00904: "BAY1": Invalid Identifier.
Please help me sort this out or suggest a different method.
Thanks in Advance.

May be your query using some keyword of sql or oracle as column name or at some invalid place. in such cases this type of errors are possible. I am not sure about this solution. but atleast we can try once. so that we can make it sure if its correct or not?

FIXED!! This is how i did it:
private void populateDeliveryBayCodes()
{
conn.Open();
string query;
query = "select distinct dd.delivery_bay_code from dc_delivery dd, dc_grv dg where dd.delivery_complete_datetime is null and dd.dc_delivery_id_no = dg.dc_delivery_id_no and dd.delivery_announce_datetime is null";
OracleCommand cmd = new OracleCommand(query, conn);
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cbDelivery.Items.Add(dr["delivery_bay_code"]);
}
dr.Close();
conn.Close();
}
private void populateOrderNumbers()
{
conn.Open();
string query;
query = "select distinct dg.order_no from dc_delivery dd, dc_grv dg where dd.delivery_complete_datetime is null and dd.dc_delivery_id_no = dg.dc_delivery_id_no and dd.delivery_announce_datetime is null and dd.delivery_bay_code ='" + cbDelivery.Text + "' order by order_no";
OracleCommand cmd = new OracleCommand(query, conn);
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cbOderNo.Items.Add(dr["order_no"]);
}
dr.Close();
conn.Close();
}
and
private void frmBuiltPallet_Load(object sender, EventArgs e)
{
populateDeliveryBayCodes();
{
private void cbDelivery_SelectedIndexChanged(object sender, EventArgs e)
{
populateOrderNumbers();
}

Related

Filling Textbox, when combobox Selected Index Changed

In the code below, i just want to fill my textbox based on the selected combo box changed. but i get the following error.
'Conversion failed when converting the varchar value
'System.Data.DataRowViewConvert.ToString()' to data type int.'
i'd appreciate it if you help me.
SqlConnection objConnection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\UniversityDataBase.mdf;Integrated Security=True");
private void comboBox1_Click(object sender, EventArgs e)
{
string query = "SELECT *FROM TutorTable";
SqlDataAdapter SDA = new SqlDataAdapter(query, objConnection);
DataTable dt = new DataTable();
SDA.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "Tid";
objConnection.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string sqlQuery = "SELECT *FROM TutorTable where Tid = '"+comboBox1.Text+ "Convert.ToString()'";
SqlCommand objCommand = new SqlCommand(sqlQuery, objConnection);
objConnection.Open();
objCommand.ExecuteNonQuery();
SqlDataReader dr;
dr = objCommand.ExecuteReader();
while (dr.Read())
{
string Tname = (string)dr["Tname"].ToString();
textBox1.Text = Tname;
}
}
Why are you using the Convert.ToString() in this piece of code:
"SELECT * FROM TutorTable where Tid = '"+comboBox1.Text+ "Convert.ToString()'"
I think the correct way wolud be:
"SELECT * FROM TutorTable where Tid = '"+comboBox1.Text+ "'"
But consider using a store procedure to prevent sql injection or using an ORM.
I think that comboBox1.Text is already returning a string value. So if that, it is not necessary to put the Convert.ToString(comboBox.Text), just put comboBox1.Text
According to documentation, the Text property is a string
https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.text(v=vs.110).aspx
I found the Solution as follows:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\UniversityDataBase.mdf;Integrated Security=True");
string sqlQuery = "SELECT *FROM TutorTable WHERE Tid = '" + comboBox1.Text + "'";
SqlCommand objCommand = new SqlCommand(sqlQuery, con);
con.Open();
SqlDataReader dr;
dr = objCommand.ExecuteReader();
while (dr.Read())
{
string name = (string)dr["Tname"].ToString();
textBox1.Text = name;
}
}
You have got the answer already but few more things should be taken care of
Your code
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string sqlQuery = "SELECT *FROM TutorTable where Tid = '"+comboBox1.Text+ "Convert.ToString()'";
SqlCommand objCommand = new SqlCommand(sqlQuery, objConnection);
objConnection.Open();
objCommand.ExecuteNonQuery();
SqlDataReader dr;
dr = objCommand.ExecuteReader();
while (dr.Read())
{
string Tname = (string)dr["Tname"].ToString();
textBox1.Text = Tname;
}
}
Things to notice:
1) Use varabled instead of manipulating sql
e.g. SELECT *FROM TutorTable where Tid = #id and pass id into sqlCommand object
2) You dont need to call ExecuteNonQuery before SqlDataReader
3) you need to use if(dr.Read()) instead of while
4) You can directly assign value textbox.
e.g. texBox1.Text = dr["Tname"].ToString();
5) Close the objConnection

Updating data from combobox C#

What i am trying to do is when a user selects a company from a comboBox then clicks the button the different text boxes are supposed to show the different data from the database.
This is what i have but it doesnt seem to work.
Any suggestions?
private void Edit_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(str))
{
con.Open();
SqlDataAdapter adapt = new SqlDataAdapter("SELECT * FROM Companies", con);
DataTable dt = new DataTable();
adapt.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "Name";
}
}
private void button3_Click(object sender, EventArgs e)
{
String company = comboBox1.SelectedItem.ToString();
String check = #"SELECT * FROM Companies WHERE Name=#name";
using (SqlConnection con = new SqlConnection(str))
using (SqlCommand cmd = new SqlCommand(check, con))
{
con.Open();
cmd.Parameters.Add("#name", SqlDbType.VarChar).Value = company;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
textBox1.Text = (reader["Name"].ToString());
textBox2.Text = (reader["PhNo"].ToString());
textBox3.Text = (reader["Email"].ToString());
textBox4.Text = (reader["Acc"].ToString());
textBox5.Text = (reader["Address"].ToString());
textBox6.Text = (reader["Suburb"].ToString());
textBox7.Text = (reader["PostCode"].ToString());
textBox8.Text = (reader["State"].ToString());
}
}
}
Update: the output of comboBox1.SelectedItem.ToString(); is System.Data.DataRowView so it seems to not be registering what the selected item is. How do i resolve this?
When the DataSource of your combo box is a DataTable, then the object in SelectedItem is of type DataRowView.
So to get a field, you can cast selected item to DataRowView and extract the field value this way:
var name = ((DataRowView)comboBox1.SelectedItem)["Name"].ToString();
In fact ((DataRowView)comboBox1.SelectedItem)["FieldName"] is of type object and you should cast the field to the desired type.
Try this
String check = "SELECT * FROM Companies WHERE Name=#name";
using (SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=ABCD;Integrated Security=True"))
using (SqlCommand cmd = new SqlCommand(check, con))
{
con.Open();
cmd.Parameters.Add("#name", SqlDbType.VarChar).Value = comboBox1.SelectedItem.ToString();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
textBox1.Text = reader["Name"].ToString();
textBox2.Text = reader["PhNo"].ToString();
textBox3.Text = reader["Email"].ToString();
textBox4.Text = reader["Acc"].ToString();
textBox5.Text = reader["Address"].ToString();
textBox6.Text = reader["Suburb"].ToString();
textBox7.Text = reader["PostCode"].ToString();
textBox8.Text = reader["State"].ToString();
}
}
Make sure your connectionstring is proper. Also Have you checked value of comboBox1.SelectedItem.ToString() and same is present in db?
If you are populating drop down from database then refer this: System.Data.DataRowView in DropDownList
Updated:
private void ComboBoxBinding()
{
using (SqlConnection con = new SqlConnection(str))
{
con.Open();
SqlDataAdapter adapt = new SqlDataAdapter("SELECT Name,Id FROM Companies", con);
DataTable dt = new DataTable();
adapt.Fill(dt);
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Id";
comboBox1.DataSource = dt;
comboBox1.DataBind();
}
}
You can call this function either in page load or in class constructor.
Try the code below it will work,the thing that you are missing is you are not setting the ValueMember property of your combo box.
Suggestion :
1.Debug your code and make sure that your query is correct and your able to getting the value right values from data source.
2.Make sure that your columns names in your database table are exactly same as you are setting in your combo box display member and value member
using (SqlConnection connection = new SqlConnection("Data Source=.;Initial Catalog=\"Student Extended\";Integrated Security=True"))
{
SqlCommand command = new SqlCommand
{
Connection = connection,
CommandText = "SELECT DepartmentId,DepartmentName FROM dbo.TblDepartment"
};
SqlDataAdapter adpater = new SqlDataAdapter(command);
DataTable table = new DataTable();
adpater.Fill(table);
if (txtStdDeptName != null)
{
txtStdDeptName.DataSource = table;
txtStdDeptName.DisplayMember = "DepartmentName";
txtStdDeptName.ValueMember = "DepartmentId";
}
}

id getting inserted without selecting in c#.net

private void Form1_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand cmd = new OleDbCommand("select project_name, ID from tb_project", con);
con.Open();
OleDbDataReader DR = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(DR);
combo_status.DataSource = table;
combo_status.DisplayMember = "project_name";
combo_status.ValueMember = "ID";
combo_status.Text = "Select Project Name";
}
private void btnSave_Click_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
OleDbCommand cmd = new OleDbCommand("Insert Into tb1(name) Values (#name)", con);
cmd.Parameters.AddWithValue("name", combo_status.SelectedValue);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inserted sucessfully");
}
In the first class i have a combobox and i am fetching its value from database and i have shown "Select Project Name" on page load in combobox.I want to insert its value only when user selects option from dropdown and insert nothing if user did not choose any option.
Now the problem is that the first name in the dropdown gets inserted on button click.without choosing any option.I want that if user did not choose any name value from dropdown nothing should get inserted.
can anyone help me..?
Assuming that datatype of ID column is int:
private void Form1_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand cmd = new OleDbCommand("select project_name, ID from tb_project", con);
con.Open();
OleDbDataReader DR = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(DR);
//begin adding line
DataRow row = table.NewRow();
row["project_name"] = "Select Project Name";
row["ID"] = 0;
table.Rows.InsertAt(row, 0);
//end adding line
combo_status.DataSource = table;
combo_status.DisplayMember = "project_name";
combo_status.ValueMember = "ID";
combo_status.Text = "Select Project Name";
}
private void btnSave_Click_Click(object sender, EventArgs e)
{
if(combo_status.SelectedValue == 0)
{
return; //do nothing if user didn't select anything in combobox, you can change this line of code with whatever process you want
}
OleDbConnection con = new OleDbConnection(constr);
con.Open();
OleDbCommand cmd = new OleDbCommand("Insert Into tb1(name) Values (#name)", con);
cmd.Parameters.AddWithValue("name", combo_status.SelectedValue);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inserted sucessfully");
}
Hope this will help you

C# Add value to a texbox based on the Combobox selection

We have selected a value from a combobox and need the related information in the textbox.
The following code does not work for the same.
private void itemcode_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = (string)itemcode.SelectedItem;
SqlConnection conn3 = new SqlConnection(connString);
conn3.Open();
//For Redundency Checking Code of Supplier id.
string iname = "select Itemname from Items where Itemcode='" +
itemcode.SelectedItem.ToString() + "'";
SqlCommand cmdRedun1 = new SqlCommand(iname, conn3);
SqlDataReader dr1 = cmdRedun1.ExecuteReader();
dr1.Read();
itemname.Text = dr1["Itemname"].ToString();
dr1.Close();
}
First Check your Item Value Of Combo box , and then create your query with StringFormat
for example :
string iname = String.Format("select Itemname from Items where Itemcode='{0}'",
itemcode.SelectedItem.ToString()) ;
//-- then please check out below code :
SqlConnection SqlConn = new SqlConnection(this.ConnectionString);
SqlConn.Open();
SqlCommand SqlCmd = new SqlCommand(" Your Select....", SqlConn);
SqlCmd.CommandType = CommandType.Text;
SqlDataReader r = SqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
//----need this
while (r.Read())
itemname.Text = string.IsNullOrEmpty(r["Itemname"].ToString()) ?
string.Empty : r["Itemname"].ToString();
r.Close();
if (SqlConn.State != ConnectionState.Closed)
SqlConn.Close();
You can try ExecuteScalar instead of SqlDataReader.

C# drop downlist values not insert

i have written a code to load the data to drop down list, as i written it was loaded, but while trying to insert the value of drop down list, (i mean selectedItem.text) it will not insert, instead if thtat selectedIndex=0 alone has been inserted. please correct me.
//Load the name to Drop down list
public void name()
{
DropDownList1.Items.Clear();
ListItem i = new ListItem();
i.Text = "-Select-";
DropDownList1.Items.Add(i);
DropDownList1.SelectedIndex = 0;
Conhr.Open();
string s;
s = "select EmployeeName from tbl_EmploeeDetails where SiteName='" + Label5.Text + "' ";
SqlCommand cd = new SqlCommand(s, Conhr);
SqlDataReader dr;
dr = cd.ExecuteReader();
while (dr.Read())
{
ListItem m= new ListItem();
m.Text = dr["EmployeeName"].ToString().Trim();
DropDownList1.Items.Add(m);
}
dr.Close();
Conhr.Close();
}
//trying to insert the data for drop down list
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
string a;
a = "insert into tbl_KKSUser(EName,Uname,Password)values(#en,#un,#pas)";
SqlCommand cm = new SqlCommand(a, con);
SqlParameter paramName;
paramName = new SqlParameter("#en", SqlDbType.VarChar, 25);
paramName.Value = DropDownList1.SelectedItem.Text;
cm.Parameters.Add(paramName);
cm.ExecuteNonQuery();
con.close
}
answer will be like this in data base
1 -Select- dsad AGEAcwBkAGY=
2 -Select- da AGEAZA==
Every time we are working with DropDownlist the best approach is selectedvalue,
Try to use:
Set the DataSource to the reader and execute DataBind()
conn.Open();
SqlDataReader MyDataSet = cmd.ExecuteReader();
ddlClassList.DataSource = MyDataSet;
ddlClassList.DataTextField = "Field1";
ddlClassList.DataValueField = "Field2";
ddlClassList.DataBind();
MyDataSet.Close();
conn.Close();

Categories