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";
}
}
Related
private void button1_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["Test_Evaluate"].ConnectionString;
using(SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("select * from Applicant_Details where ApplicantID like #ApplicantID", con);
cmd.Parameters.AddWithValue("#ApplicantID", RetrieveRecord_txt + "%");
con.Open();
SqlDataReader rd = cmd.ExecuteReader();
BindingSource source = new BindingSource();
source.DataSource = rd;
dataGridView1.DataSource = source;
}
}
I think your problem is that you're calling the ID and not the Text property. Assuming your form contains the Text box field with ID "RetrieveRecord_txt", then:
this:
cmd.Parameters.AddWithValue("#ApplicantID", RetrieveRecord_txt + "%");
Should be
cmd.Parameters.AddWithValue("#ApplicantID", RetrieveRecord_txt.Text + "%");
I am trying to Fill Combobox2 on combobox1 selectedText changed from the same table in windows form application. I am using sql serevr 2008 database. I am unable to fill combobox2 on combobox selected text changed.
Here is what i have tried:
private void Purchase_Load(object sender, EventArgs e)
{
fillName();
comboBoxName.SelectedIndex = -1;
}
private void comboBoxName_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBoxName.SelectedText != "")
{
fillMake();
}
}
private void fillName()
{
SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True");
con.Open();
string str = "Select Item_Name from Item";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
cmd.ExecuteNonQuery();
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Name";
comboBoxName.ValueMember = "Item_Make";
}
private void fillMake()
{
SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True");
con.Open();
string str = "Select Item_Make from Item Where Item_Name='" + comboBoxName.SelectedText + "'";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
cmd.ExecuteNonQuery();
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Make";
comboBoxName.ValueMember = "Item_Name";
comboBoxName.SelectedIndex = -1;
comboBoxName.Text = "Select";
}
Sql server table for Items
Item_Code Item_Name Item_Make Item_Price UnitofMeasurement
Cable anchor 45.0000 meter
Cable polycab 30.0000 meter
Button anchor 15.0000 unit
Button havells 20.0000 unit
Switch cona 70.0000 unit
I have searched for solution but was unfortunate.
please help me out.
Thanks in advance.
It's a little difficult to figure out what you're trying to do, but it sounds like you are trying to populate a second combo box (comboBoxMake?) depending on what is selected in comboBoxName. I am basing this answer on that assumption. Apologies if I have this wrong.
There are lot of things that need attention in this code. Let's look at fillName() first.
private void fillName()
{
SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True");
con.Open();
string str = "Select Item_Name from Item";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
cmd.ExecuteNonQuery();
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Name";
comboBoxName.ValueMember = "Item_Make";
}
You need to Dispose() your database objects. This can be accomplished pretty cleanly with using { .. } blocks.
You don't need to manually open the connection; filling the table with the data adapter
does this automatically.
You don't need the call to ExecuteNonQuery().
You should use the SqlDataAdapter constructor overload that takes a command object, since you have already manually created the command.
Finally, based on my assumption of your goal I have added a distinct to your query so it only gets the unique Item_Names.
private void fillName()
{
string str = "Select distinct Item_Name from Item";
using (SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(str, con))
{
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Name";
comboBoxName.ValueMember = "Item_Name";
}
}
}
}
On to fillMake(). The same suggestions apply that I noted above. Additionally:
Parameterize your SQL. Parameterize your SQL. Not only is this far, far safer than concatenating your SQL together, it is much cleaner. Seriously, read about SQL injection: http://en.wikipedia.org/wiki/SQL_injection
The fillMake() method in your original post seems to be repopulating comboBoxName. Is this correct? You mention two combo boxes but your code only references one. I am assuming you mean to populate another combo box (comboBoxMake?) here:
private void fillMake()
{
string str = "Select Item_Make from Item Where Item_Name = #item_name";
using (SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(str, con))
{
cmd.Parameters.AddWithValue("#item_name", comboBoxName.Text);
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
comboBoxMake.DataSource = dtItem;
comboBoxMake.DisplayMember = "Item_Make";
comboBoxMake.ValueMember = "Item_Make";
comboBoxMake.SelectedIndex = -1;
comboBoxMake.Text = "Select";
}
}
}
}
Lastly, change the code in the event handler so it looks at the Text rather than the SelectedText property:
private void comboBoxName_SelectedIndexChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBoxName.Text)) // Text instead of SelectedText
{
fillMake();
}
}
I using below code but it's not showing name in textbox.\
private void AllotLeaves_Load(object sender, EventArgs e)
{
display();
}
private void display()
{
SqlConnection conn = new SqlConnection(#"Data Source=.......");
conn.Open();
SqlDataAdapter ad = new SqlDataAdapter("select *from Emp_Details", conn);
DataSet ds = new DataSet();
ad.Fill(ds, "Emp_Details");
cballotid.DataSource = ds.Tables["Emp_Details"].DefaultView;
cballotid.DisplayMember = "ID";
cballotid.ValueMember = "ID";
}
private void cballotid_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=......");
conn.Open();
SqlCommand command = new SqlCommand("select Name from Emp_Details where ID=#ID", conn);
command.Parameters.AddWithValue("#ID", cballotid.Text);
Object temp = command.ExecuteScalar(); // this returns the first value of the select statement.
if (temp != null)
txtallotname.Text = temp.ToString();
conn.Close();
}
Try this
cballotid.DisplayMember = "Name";
cballotid.ValueMember = "ID";
cballotid.BindingContext = this.BindingContext;
Reference: ListControl.DisplayMember Property
You have to change this
cballotid.DisplayMember = "ID";
cballotid.ValueMember = "ID";
to
cballotid.DisplayMember = "name of field youd like to display";
cballotid.ValueMember = "ID";
Change this line as below:-
command.Parameters.AddWithValue("#ID", cballotid.SelectedValue);
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
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();