getting value of combobox to textbox - c#

using query i have called two columns value from database into one column. the point is now i want to select a value form combobox and put one column value into textbox.
e.g
two column values from database into combobox below
10001 haider <------ when i select this index i want only haider to be viewed into the textbox
10002 fahad
10003 aitazaz
the snippet which i have used for calling the two colums value from database is:
public void account()
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT acc_no, acc_name FROM accounts_record";
MySqlDataAdapter adpt = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adpt.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
cbacc.Items.Add(ds.Tables[0].Rows[i][0] + " " + ds.Tables[0].Rows[i][1]);
}
con.Close();
}

You should be adding values and text to the combobox separately.
Here's an example ComboBox: Adding Text and Value to an Item (no Binding Source).
If you have to display the id in the text you have to do some parsing before putting the selected text into the textbox.

Use ComboBox.SelectedIndexChanged event of the combobox to populate the textbox accordingly. use http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectedindexchanged(v=vs.110).aspx

If you are able to get the 2 value text of the combo box on selection change then you can split it with space (" ") character and take the 2nd string and put it in textbox.
For example
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string[] splitedStr = comboBox1.SelectedText.Split(' ');
textBox1.Text = splitedStr[1];
}

You should use the code as below
private void Form1_Load(object sender, EventArgs e)
{
string conString = "Data Source=\\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT acc_no +'-' + acc_name as AccNoWithName , acc_no as ActNo FROM accounts_record";
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
DataSet dsn = new DataSet();
adpt.Fill(dsn);
con.Close();
comboBox1.DisplayMember = "AccNoWithName";
comboBox1.ValueMember = "ActNo";
comboBox1.DataSource = dsn.Tables[0];
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = comboBox1.SelectedValue.ToString();
}

Related

Combo box bound to a field required to show All before a selection is made on the Combo box

I have created a Combo box bound to "Clinics" field of a table. I wanted to show "All" on the first line of the Combo box list to show all activities of the clinics by default in a table. When a specific clinic is selected it shows the activities of the selected clinic.
My script looks like this:
[My Code looks like this]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["Myconn"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "select * from [dbo].[EC_HARS_DQ]";
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlconn.Open();
SqlDataAdapter sdr = new SqlDataAdapter(sqlcomm);
DataTable dt = new DataTable();
sdr.Fill(dt);
comboBox1.DisplayMember = "clinic";
comboBox1.DataSource = dt;
sqlconn.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["Myconn"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "select * from [dbo].[EC_HARS_DQ] where clinic='"+comboBox1.Text.ToString()+"'";
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlconn.Open();
SqlDataAdapter sdr = new SqlDataAdapter(sqlcomm);
DataTable dt = new DataTable();
sdr.Fill(dt);
dataGridView1.DataSource = dt;
sqlconn.Close();
}
}
}
First off, refrain from SELECT *, instead select only needed columns.
You can add All using a UNION.
In this example, table name is Categories with the intent to provide the primary key for use after a selection is made and description to display.
SELECT CategoryID, CategoryName FROM dbo.Categories;
Now using a SELECT with 0 in this case to represent an identifier and 'All` to display in the ComboBox then union for all rows in the table.
SELECT 0 AS CategoryID, 'All' AS CategoryName
UNION ALL SELECT CategoryID, CategoryName FROM dbo.Categories;
In code you can read the data into a DataTable, set DisplayMember, in this case to CategoryName and ValueMember to CategoryID.
When a selection is made check SelectedItem, if 0 All is the selection, else an existing primary key would be used for your business logic.

Binding Combobox with database

I have combobox in my form which display value from database. I want one default value so I use .text property also and on selected index changed event the label display the corresponding value of the database the code is not working
string cstr = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
private void AddStock_Load(object sender, EventArgs e)
{
bindcombo();
}
private void bindcombo()
{
SqlConnection con = new SqlConnection(cstr);
SqlDataAdapter da = new SqlDataAdapter("SELECT Dname FROM dealer", con);
DataTable dt = new DataTable();
da.Fill(dt);
cmbdealer.DataSource = dt;
cmbdealer.DisplayMember = "Dname";
cmbdealer.Text = "select-Dealer";
con.Close();
}
private void cmbdealer_SelectedIndexChanged(object sender, EventArgs e)
{
dealerdetails();
}
private void dealerdetails()
{
SqlConnection con = new SqlConnection(cstr);
SqlCommand cmd = new SqlCommand("select * from dealer where Dname='" + cmbdealer.Text + "'", con);
con.Open();
SqlDataReader re = cmd.ExecuteReader();
while (re.Read())
{
lbdl.Text = re["Ddlno"].ToString();
lbgst.Text = re["Dgstno"].ToString();
lbadd.Text = re["Daddress"].ToString();
}
}
the above code is working fine but when the form is load all the 3 label shows the database value of the first entry of my dealer table without selecting and value from combobox.

Displaying text in texbox from databse based on selected items from combobox

I have basically a combobox and a text box.
The combobox consists of subject code, whereas the textbox consists of a subject name which is stored in the database.
Is there any way that when an item from combobox is selected, it automatically displays the subject name based on the selected subject code, which will be from the database?
Below is my code, but it is not working.
private void Form1_Load(object sender, EventArgs e)
{
con.Open();
OleDbDataAdapter oda1 = new OleDbDataAdapter("select subject_code from subjectinfo", con);
DataTable dt1 = new DataTable();
oda1.Fill(dt1);
comboBoxSubjectCodeUpdate.DataSource = dt1;
comboBoxSubjectCodeUpdate.DisplayMember = "subject_code";
comboBoxSubjectCodeUpdate.SelectedIndex = -1;
con.Close();
}
private void comboBoxSubjectCodeUpdate_SelectedIndexChanged(object sender, EventArgs e)
{
string str = "select subject_abbreviation from subjectinfo where subject_code ='" + comboBoxSubjectCodeUpdate.Text + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr["subject_abbreviation"].ToString();//column name should be that you want to show on textbox
}
}

Assign Different Value and Text to Dropdown List Items

I am trying to populate a dropdown list on pageload with data from the batabase.
While populating I want the dropdown items (<option>) to have the display text which is different from 'value' of the <option>
For example: The dropdown list will show "Title" (column from db) as text on UI, but the 'value' of the <option> should be "ID" (column from db)
How do I achieve this?
Currently my code is like this: (drpReleaseTitle is the ID of the dropdown)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
con1.Open();
SqlCommand releaseTitlecmd = new SqlCommand("select Title from LWMDemo_ReleaseInfo order by ReleaseID", con1);
SqlDataReader releaseTitledr = releaseTitlecmd.ExecuteReader();
while (releaseTitledr.Read())
{
drpReleaseTitle.Items.Add(releaseTitledr.GetValue(0).ToString());
}
con1.Close();
}
}
Try this
drpReleaseTitle.Items.Add(new ListItem("yourtext", "yourvalue"));
It is better to Use Dataset Instead of Data Reader Because it use disconnected architecture so You can Use After Close the connection
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
con1.Open();
SqlCommand releaseTitlecmd = new SqlCommand("select Title from LWMDemo_ReleaseInfo order by ReleaseID", con1);
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = Cmd;
sda.Fill(ds);
if(ds!=null && ds.table.count>0){
if(ds.table[0]!=null && ds.table[0].rows.count>0){
drpReleaseTitle.DataSource=ds.table[0].Title; //Title Column
drpReleaseTitle.DataSourceID=ds.table[0].ID; //ID Column
}
}
con1.Close();
}
}
If you will try add a string to Items in drop down list, it will create a item, that will have text and value as your string. You need to add new ListItem. ListItem contains constructor with text and value as parameters. More about this class you can read here

how to trigger an event when an item is selected from combobox in c#.net

string Sql_type = "select property_type_id,type_name from lk_tb_property_type";
OleDbCommand cmd_type = new OleDbCommand(Sql_type, con);
OleDbDataReader DR_two = cmd_type.ExecuteReader();
DataTable table_two = new DataTable();
table_two.Load(DR_two);
//begin adding line
DataRow row_two = table_two.NewRow();
row_two["type_name"] = "Select Poperty Name";
row_two["property_type_id"] = 0;
table_two.Rows.InsertAt(row_two, 0);
//end adding a line
combo_type.DataSource = table_two;
combo_type.DisplayMember = "type_name";
combo_type.ValueMember = "property_type_id";
combo_type.Text = "Select Poperty Name";
with this code i am fetching values for a combobox from database.now suppose my combobx is having 2 items named A and B..I have one more combobox...now what i want is that when user chooses item A from combobox the second combobox should display data related to item A when user chooses item B then data related to item B should be displayed...sohow to achieve this...??
you can fetch the data and bind it to combobox2 on SelectedIndexChanged event of combobox1
private void combobox1_SelectedIndexChanged(object sender, EventArgs e)
{
var val = combobox1.SelectedValue;
// fetch data from database
// you need to set SQL parameter value form SelectedValue
combobox2.DataSource = ...; // set this value
combobox2.DisplayMember = .....; // set this value
combobox2.ValueMember = ....; // set this value
}
Please assign an event SelectedIndexChanged and AutoPostBack = true is this is a web Application in C#
In SelectedIndexChanged of combo box write your code. and make AutoPostBack = true of your combobox
You can do like these steps.
First, bind data to comboBox1 (I suppose that your first ComboBox named "comboBox1", and your form named "Form1"), please make sure that your SQL query command is correct for comboBox1
private void Form1_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
string Sql_cust_name = "select customer_name from tb_customer";
OleDbCommand cmd_cust_name = new OleDbCommand(Sql_cust_name, con);
OleDbDataReader DR_cust_name = cmd_cust_name.ExecuteReader();
DataTable table_cust_name = new DataTable();
table_cust_name.Load(DR_cust_name);
DataRow row_cust_name = table_cust_name.NewRow();
row_cust_name["customer_name"] = "Select Customer Name";
table_cust_name.Rows.InsertAt(row_cust_name, 0);
combo_cust_name.DataSource = table_cust_name;
combo_cust_name.DisplayMember = "customer_name";
combo_cust_name.ValueMember = "customer_name";
combo_cust_name.Text = "Select Customer Name";
con.Close();
}
Next, bind data to comboBox2 (I suppose that your second ComboBox named "comboBox2"), you have to get comboBox1.SelectedValue whenever it is changed, this value will be used in the filtering for data in comboBox2, so you have to handle SelectedIndexChanged event for comboBox1, please make sure that you have this code somewhere in your project: this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
To bind data to comboBox2 (I suppose that your second ComboBox named "comboBox2"), you have to get comboBox1.SelectedValue whenever it is changed
private void combo_cust_name_SelectedIndexChanged(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
string customerName = "";
if (combo_cust_name.SelectedValue.GetType() == typeof(DataRowView))
{
DataRowView selectedRow = (DataRowView)combo_cust_name.SelectedValue;
customerName = selectedRow["customer_name"].ToString();
}
else
{
customerName = combo_cust_name.SelectedValue.ToString();
}
string Sql2 = "SELECT customer_number FROM tb_customer WHERE customer_name = '" + customerName + "'";
OleDbCommand cmd_type = new OleDbCommand(Sql2, con);
OleDbDataReader DR_two = cmd_type.ExecuteReader();
DataTable table_two = new DataTable();
table_two.Load(DR_two);
DataRow row_two = table_two.NewRow();
row_two["customer_number"] = "Select Customer Number";
table_two.Rows.InsertAt(row_two, 0);
comboBox2.DataSource = table_two;
comboBox2.DisplayMember = "customer_number";
comboBox2.ValueMember = "customer_number";
comboBox2.Text = "Select Customer Number";
}
Please correct the SQL query command as you want, but don't forget to put a correct filter like my sample code above.

Categories