Hello all I am trying to populate some textboxes automatically when I select an item from a combobox dropdown list using Microsoft sql server with a usercontrol form. I have written the codes below, however I am getting the items in the combox dropdown list but when I select an item in the combobox dropdown list, nothing happens in the text boxes. the values are in a table called competitors. the columns are Institution, Region, FirstName, LastName and I want the values to display in the respective textboxes when I select the combox dropdown. I seek your assistance in solving this problem. thanks in advance
private void RabbitCare_Load(object sender, EventArgs e)
{
CBoxParishDdlist.Items.Clear();
SqlConnection connect = new SqlConnection(#"Data Source=ITSPECIALIST\SQLPROJECTS;Initial Catalog=EXPRORESULTS;Integrated Security=True ");
connect.Open();
SqlCommand cmd = connect.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select ParishName FROM Competitors WHERE CompetitiveEventName = 'Care and Management of Bees'";
cmd.ExecuteNonQuery();
DataTable dat = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter(cmd);
SDA.Fill(dat);
foreach (DataRow DAR in dat.Rows)
{
CBoxParishDdlist.Items.Add(DAR["ParishName"].ToString());
}
connect.Close();
}
private void CBoxParishDdlist_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection connect = new SqlConnection(#"Data Source=ITSPECIALIST\SQLPROJECTS;Initial Catalog=EXPRORESULTS;Integrated Security=True ");
connect.Open();
cmd = new SqlCommand("SELECT * FROM Competitors WHERE ParishName = '" + CBoxParishDdlist.Text + "'", connect);
cmd.ExecuteNonQuery();
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
string Institution = (string)dr["Institution"].ToString();
TxtBoxInstitution.Text = Institution;
string Region = (string)dr["Region"].ToString();
TxtBoxRegion.Text = Region;
string FirstName = (string)dr["FirstName"].ToString();
TxtBoxFname.Text = FirstName;
string LastName = (string)dr["LastName"].ToString();
TxtBoxLname.Text = LastName;
}
connect.Close();
I think this will solve your problem.
TxtBoxInstitution.Text = comboBoxName.SelectedItem.ToString();
Related
I am in the process of building a Drone Pilot logbook. In the logbook, on the Pilots page, you select from a comboBox at the top to choose your pilot. This data is taken from a SQL Server (.MDF) database file in the project. Once you have chosen the pilot, existing data from the database populates the rest of the form. The code I have below queries the SQL Server database file successfully and shows the FullName in the comboBox, but now I'm at a blank as far as how I get the rest of the form to fill out (i.e. FirstName, LastName, Address, City, etc.)
private void frmPilots_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Kevin\ownCloud\Programming\C# Projects\DroneLogbook\DroneLogbook\data.mdf;Integrated Security=True;Connect Timeout=30"))
{
SqlCommand sc = new SqlCommand("select Id,FullName from Pilots", conn);
conn.Open();
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(string));
dt.Columns.Add("FullName", typeof(string));
dt.Load(reader);
cmbExistingPilot.ValueMember = "Id";
cmbExistingPilot.DisplayMember = "FullName";
cmbExistingPilot.DataSource = dt;
conn.Close();
}
You need another select statement based on the selected value of your ComboBox and a SqlDataReader to fill out your TextBoxes. Something like this:
SqlCommand command = new SqlCommand(
"SELECT FirstName, LastName FROM Pilots where Id = #Id;",
connection);
command.Parameters.AddWithValue("#Id",cmbExistingPilot.SelectedValue.ToString());
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
txtFirstName.Text = reader.GetString(0);
txtLastName.Text = reader.GetString(1);
//and...
}
}
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";
}
}
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.
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();
}
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();