Textbox displays value from access - c#

Hi I'm new to C# and I have a windows form with a textbox Barcode_txtBx and a button Search_btn which filters records in a Data Table dt to one record and have another textbox Manufacturer_txtBx to display the data table column Manufacturer. I can do the filtering but I can't find a way to display the relevant column in the textbox Manufacturer_txtBx. This is the code I have so far.
private void Search_btn_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "Select * from BookInTable where Barcode = '" + Barcode_txtBx.Text + "'";
OleDbDataReader reader = command.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
Manufacturer_txtBx.Text = "";
connection.Close();
}
At the moment Manufacturer_txtBx is displaying an empty string just so I don't get an error

This works to add the data to the TextBoxes
private void Search_btn_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "Select * from BookInTable where Barcode = '" + Barcode_txtBx.Text + "'";
OleDbDataReader reader = command.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
string data = dt.ToString();
Manufacturer_txtBx.Text = dt.Rows[0].ItemArray[5].ToString();
Type_txtBx.Text = dt.Rows[0].ItemArray[6].ToString();
Model_txtBx.Text = dt.Rows[0].ItemArray[7].ToString();
PartNumber_txtBx.Text = dt.Rows[0].ItemArray[8].ToString();
AdditionalDetails_txtBx.Text = dt.Rows[0].ItemArray[13].ToString();
connection.Close();
}
Crowcoder and Steve are right that this is not sanitised in any way and any working database should be.

Related

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

filter a listbox bound to a acces database using a textbox

I'm pretty new in c#, taking lessons but with what i'm trying to do i know that i'm way ahead of schedule.
I have a form with a listbox and a textbox.
this is how I populate the listbox
private void Centrale_Gegevens_Load(object sender, EventArgs e)
try
{
OleDbConnection verbinding = new OleDbConnection();
verbinding.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=E:\Het Vlaamse Kruis\Het Vlaamse Kruis\data\Patienten.accdb; Jet OLEDB:Database Password=internet;";
verbinding.Open();
OleDbCommand combo = new OleDbCommand();
combo.Connection = verbinding;
string query = "select NaamPatient from tbl_Patient";
combo.CommandText = query;
OleDbDataReader reader = combo.ExecuteReader();
while (reader.Read())
{
lstBox.Items.Add(reader["NaamPatient"]);
}
verbinding.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
the listbox is in that way populated with names of persons.
The textbox named textbox1 is what i want to use to filter the listbox.
This is what i got sofare, but it doesn't work.
private void textBox1_TextChanged(object sender, EventArgs e)
{
OleDbConnection verbinding = new OleDbConnection();
verbinding.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=E:\Het Vlaamse Kruis\Het Vlaamse Kruis\data\Patienten.accdb; Jet OLEDB:Database Password=internet;";
verbinding.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tbl_Patienten where NaamPatient like '" + textBox1.Text + "%' ";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
lstBox.DataSource = dt;
lstBox.DisplayMember = "NaamPatient";
verbinding.Close();
}
I have red almost everything I can find on the net about it, bus no mather what i do, I can't get it to work.
How can I get if I type A in the textbox that the listbox shows all the names beginning with A, And if I type AB that the listbox shows everything beginning with AB etc.
Thanks in advance
Firstly, in Centrale_Gegevens_Load, table's name is tbl_Patient but in textBox1_TextChanged, it is tbl_Patienten.
Secondly,Connection property has not been initialized.
you must insert this: cmd.Connection = verbinding; after initializing the cmd;
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = verbinding;
Sorry for my bad English.

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

Populate gridview from listbox such that first few rows become columns in gridview

protected void Button1_Click(object sender, EventArgs e)
{
string sqlstring;
OleDbConnection connection = new OleDbConnection("Provider=MSDAORA;Data Source=solaris;Password=medical;User ID=medical");
sqlstring = "select emp_name,decode(sex,null,null,'Self')rel,decode(dob,null,'Ad',floor(months_between(sysdate,dob)/12))age,decode(f_elg,'Y',f_name,null) f_name,decode(f_elg,'Y','Father',null) f_rel,decode(f_dob,null,'Ad',floor(months_between(sysdate,f_dob)/12)) f_age,decode(m_elg,'Y',m_name,null) m_name,decode(m_elg,'Y','Mother',null) m_rel,decode(m_dob,null,'Ad',floor(months_between(sysdate,m_dob)/12)) m_age,decode(s_elg,'Y',s_name,null) s_name,decode(s_elg,'Y',decode(s_sex,'M','Husband','F','Wife'),null) s_rel,decode(s_dob,null,'Ad',floor(months_between(sysdate,s_dob)/12)) s_age,decode(dep_elg1,'Y',dep_name1,null) dep_name1,decode(dep_sex1,'M','Son','F','Daughter',null) dep_rel1,decode(dep_dob1,null,null,floor(months_between(sysdate,dep_dob1)/12)) dep_age1,decode(dep_elg2,'Y',dep_name2,null) dep_name2,decode(dep_sex2,'M','Son','F','Daughter',null) dep_rel2,decode(dep_dob2,null,null,floor(months_between(sysdate,dep_dob2)/12)) dep_age2,decode(dep_elg3,'Y',dep_name3,null) dep_name3,decode(dep_sex3,'M','Son','F','Daughter',null) dep_rel3,decode(dep_dob3,null,null,floor(months_between(sysdate,dep_dob3)/12)) dep_age3,decode(dep_elg4,'Y',dep_name4,null) dep_name4,decode(dep_sex4,'M','Son','F','Daughter',null) dep_rel4,decode(dep_dob4,null,null,floor(months_between(sysdate,dep_dob4)/12)) dep_age4,decode(dep_elg5,'Y',dep_name5,null) dep_name5,decode(dep_sex5,'M','Son','F','Daughter',null) dep_rel5,decode(dep_dob5,null,null,floor(months_between(sysdate,dep_dob5)/12)) dep_age5,decode(dep_elg6,'Y',dep_name6,null) dep_name6,decode(dep_sex6,'M','Son','F','Daughter',null) dep_rel6,decode(dep_dob6,null,null,floor(months_between(sysdate,dep_dob6)/12)) dep_age6 from employee_mas where emp_no='" + TextBox1.Text + "'";
//sqlstring = "select COALESCE(emp_name,'') + ' ' + COALESCE(sex,'')as empinfo from employee_mas where emp_no='" + TextBox1.Text + "'";
OleDbCommand comm = new OleDbCommand(sqlstring, connection);
OleDbDataReader reader;
connection.Open();
reader = comm.ExecuteReader();
if (reader.Read())
{
ListBox1.Items.Add(reader.GetString(reader.GetOrdinal("emp_name")));
ListBox1.Items.Add(reader.GetString(reader.GetOrdinal("age")));
ListBox1.Items.Add(reader.GetString(reader.GetOrdinal("rel")));
ListBox1.Items.Add(reader.GetString(reader.GetOrdinal("f_name")));
ListBox1.Items.Add(reader.GetString(reader.GetOrdinal("f_age")));
ListBox1.Items.Add(reader.GetString(reader.GetOrdinal("f_rel")));
}
}
This is the code I have used to populate my listbox
Now I want that my gridview which is having 3 columns such as:
Name Age Rel
so first 3 values be inserted in the first row of the gridview
second 3 in the second and so on.
An help will be great.
You can use a DataTable to store the rows and then after reading all the records, you bind it to the GridView:
protected void Button1_Click(object sender, EventArgs e)
{
string sqlstring;
OleDbConnection connection = new OleDbConnection("Provider=MSDAORA;Data Source=solaris;Password=medical;User ID=medical");
sqlstring = "select emp_name,decode(sex,null,null,'Self')rel,decode(dob,null,'Ad',floor(months_between(sysdate,dob)/12))age,decode(f_elg,'Y',f_name,null) f_name,decode(f_elg,'Y','Father',null) f_rel,decode(f_dob,null,'Ad',floor(months_between(sysdate,f_dob)/12)) f_age,decode(m_elg,'Y',m_name,null) m_name,decode(m_elg,'Y','Mother',null) m_rel,decode(m_dob,null,'Ad',floor(months_between(sysdate,m_dob)/12)) m_age,decode(s_elg,'Y',s_name,null) s_name,decode(s_elg,'Y',decode(s_sex,'M','Husband','F','Wife'),null) s_rel,decode(s_dob,null,'Ad',floor(months_between(sysdate,s_dob)/12)) s_age,decode(dep_elg1,'Y',dep_name1,null) dep_name1,decode(dep_sex1,'M','Son','F','Daughter',null) dep_rel1,decode(dep_dob1,null,null,floor(months_between(sysdate,dep_dob1)/12)) dep_age1,decode(dep_elg2,'Y',dep_name2,null) dep_name2,decode(dep_sex2,'M','Son','F','Daughter',null) dep_rel2,decode(dep_dob2,null,null,floor(months_between(sysdate,dep_dob2)/12)) dep_age2,decode(dep_elg3,'Y',dep_name3,null) dep_name3,decode(dep_sex3,'M','Son','F','Daughter',null) dep_rel3,decode(dep_dob3,null,null,floor(months_between(sysdate,dep_dob3)/12)) dep_age3,decode(dep_elg4,'Y',dep_name4,null) dep_name4,decode(dep_sex4,'M','Son','F','Daughter',null) dep_rel4,decode(dep_dob4,null,null,floor(months_between(sysdate,dep_dob4)/12)) dep_age4,decode(dep_elg5,'Y',dep_name5,null) dep_name5,decode(dep_sex5,'M','Son','F','Daughter',null) dep_rel5,decode(dep_dob5,null,null,floor(months_between(sysdate,dep_dob5)/12)) dep_age5,decode(dep_elg6,'Y',dep_name6,null) dep_name6,decode(dep_sex6,'M','Son','F','Daughter',null) dep_rel6,decode(dep_dob6,null,null,floor(months_between(sysdate,dep_dob6)/12)) dep_age6 from employee_mas where emp_no='" + TextBox1.Text + "'";
//sqlstring = "select COALESCE(emp_name,'') + ' ' + COALESCE(sex,'')as empinfo from employee_mas where emp_no='" + TextBox1.Text + "'";
OleDbCommand comm = new OleDbCommand(sqlstring, connection);
OleDbDataReader reader;
connection.Open();
DataTable table = new DataTable();
table.Columns.Add("Name");
table.Columns.Add("Age");
table.Columns.Add("Rel");
reader = comm.ExecuteReader();
if (reader.Read())
{
string name = reader.GetString(reader.GetOrdinal("emp_name"));
string age = reader.GetString(reader.GetOrdinal("age"));
string rel = reader.GetString(reader.GetOrdinal("rel"));
ListBox1.Items.Add(name);
ListBox1.Items.Add(age);
ListBox1.Items.Add(rel);
ListBox1.Items.Add(reader.GetString(reader.GetOrdinal("f_name")));
ListBox1.Items.Add(reader.GetString(reader.GetOrdinal("f_age")));
ListBox1.Items.Add(reader.GetString(reader.GetOrdinal("f_rel")));
table.Rows.Add(name, age, rel);
}
GridView.DataSource = table;
GridView.DataBind();
}

Get value of combobox2 from combobox1

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

Categories