I am new in c# and I have a question.
I want to select a value from a combobox and it should show in a label it's age.
What I do is this:
public void FillCombo()
{
SqlDataAdapter adap = new SqlDataAdapter("Select * from customers",con);
DataTable dt = new DataTable();
adap.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "name";
comboBox1.ValueMember = "id";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd1 = new SqlCommand("Select * from customers where name=#name ", con);
cmd1.Parameters.AddWithValue("#name",comboBox1.SelectedItem));
int i= cmd1.ExecuteNonQuery();
if (i > 0)
{
SqlDataReader sqlrdr = cmd1.ExecuteReader();
while (sqlrdr.Read())
{
String age= sqlrdr["age"].ToString();
label1.Text = age;
}
}
else{
MessageBox.Show("no value");
}
con.Close();
}
It shows no value message , even if i have values in database. What can I do?
When you set the DataSource to a DataTable then every item in the combobox is a DataRowView. So you already have the info about the age of the current customer in the combobox. No need to make another call to the database.
You just need to use the SelectedItem property to retrieve the info about the age field or any other field present in the DataSource
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView rv = l.SelectedItem as DataRowView;
// For safety, always check for null.
// It is possible that SelectedIndexChanged
// will be called even when there is no selection in the combobox
if(rv != null)
{
label1.Text = rv["age"].ToString();
....
}
}
Try this to obtain index,value and selected name:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
int selectedIndex = cmb.SelectedIndex;
int selectedValue = (int)cmb.SelectedValue;
ComboboxItem selectedName = (ComboboxItem)cmb.SelectedItem;
}
Related
FORM IMAGE
I have two tables in my database
datatable
kar
datatable have two columns Product, Producttype. kar table also have two columns type, tax.
In my form I have a Datagridview with 3 columns Productname, type, tax.
Productname column is datagridviewcomboboxcolumn which display all the product from datatable. `
public Form5()
{
InitializeComponent();
}
private void Form5_Load(object sender, EventArgs e)
{
this.datatableTableAdapter.Fill(this.myBillDataSet.datatable);
dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);
}
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox combo = e.Control as ComboBox;
if (combo != null)
{
combo.SelectedIndexChanged -= new EventHandler(ComboBox_SelectedIndexChanged);
combo.SelectedIndexChanged += new EventHandler(ComboBox_SelectedIndexChanged);
}
}
string item = null;
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=ZEE-PC\SQLEXPRESS;Initial Catalog=MyBill;Integrated Security=True");
ComboBox cb = (ComboBox)sender;
item = cb.Text;
if (item != null)
{
SqlCommand cmd = new SqlCommand("select Producttype from datatable where product=#pro", con);
cmd.Parameters.AddWithValue("#pro", item);
con.Open();
string val = cmd.ExecuteScalar().ToString();
con.Close();
SqlCommand cmd2 = new SqlCommand("select tax from kar where type=#pro2", con);
cmd2.Parameters.AddWithValue("#pro2", val);
con.Open();
string val2 = cmd2.ExecuteScalar().ToString();
con.Close();
}
}
when user select any product from dropdown the type and tax column will display the value. I am getting the values but not able to display in gridview cell
You can directly insert value in your cells inside ComboBox_SelectedIndexChanged event using column index
dataGridView1.Rows[e.RowIndex].Cells[YourCellindex] = val;
dataGridView1.Rows[e.RowIndex].Cells[YourSecondCellindex] = val2;
dataGridView1.BeginEdit(true);
dataGridView1.EndEdit();
Hope It helps
I have a dropdownlist in a gridview and when the textbox is changed, I would like the selected value in the dropdownlists (three separate ones in total) to match the data in the database. The code in the textbox changed event is below:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
DropDownList ddl = new DropDownList();
string connectionString = ConfigurationManager.ConnectionStrings["*******"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
string query = "SELECT one, two, three FROM table WHERE id = " + TextBox1.Text;
SqlDataAdapter sda = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
int num = sda.Fill(ds);
if (num > 0)
{
GridView1.Visible = true;
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
if (num == 0)
{
GridView1.Visible = false;
}
else
{
BindGrid();
}
}
}
Try using the RowDataBound event. For this to work, the drop-down-lists must already be populated with values, and in the event, the SelectedValue will be assigned.
protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// this assumes the drop-down-list columns are the first, second, and third columns (ordinal positions 0, 1, and 2)
DropDownList ddl1, ddl2, ddl3;
ddl1 = (DropDownList)e.Row.Cells[0].Controls[0];
ddl2 = (DropDownList)e.Row.Cells[1].Controls[0];
ddl3 = (DropDownList)e.Row.Cells[2].Controls[0];
DataRow currentRow = (DataRow)e.Row.DataItem;
ddl1.SelectedValue = currentRow[0].ToString();
ddl2.SelectedValue = currentRow[1].ToString();
ddl3.SelectedValue = currentRow[2].ToString();
}
}
im making a wpf wherein one combobox populates depending on another combobox. however, only one combobox populated.
this is my code below.
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
this.Load += Form4_Load;
}
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
private void Form4_Load(object sender, EventArgs e)
{
string query = "SELECT * FROM data_organsystem";
fillCombo(comboBox3, query, "name", "id");
comboBox3_SelectedIndexChanged(null, null);
}
private void fillCombo(ComboBox combo, string query, string displayMember, string valueMember)
{
NpgsqlConnection conn = new NpgsqlConnection(connstring);
NpgsqlCommand cmd = new NpgsqlCommand(query, conn);
NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
combo.DataSource = dt;
combo.DisplayMember = displayMember;
combo.ValueMember = valueMember;
}
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
int val;
Int32.TryParse(comboBox3.SelectedValue.ToString(), out val);
string query = "SELECT * FROM data_symptom WHERE organ_system_id = " + val;
fillCombo(comboBox4, query, "name", "id");
}
}
}
if you have any idea on how to edit this code, it would be a big help. thanks!
You will get error when you executing method comboBox3_SelectedIndexChanged àt the line
Int32.TryParse(comboBox3.SelectedValue.ToString(), out val);
Because comboBox3.SelectedValue is null if no item selected in the ComboBox, I didn't see in your code that you selected some items before calling comboBox3_SelectedIndexChanged first time.
Because method comboBox3_SelectedIndexChanged executed inside Form.Load eventhandler exception wasn't shown. Check this: https://stackoverflow.com/a/3209813/1565525.
That is why you didn't get any errors
You need to check SelectedValue for null before using it
If(this.comboBox3.SelectedValue is null)
{
this.comboBox4.DataSource = null; //Remove all items if nothing selected
}
else
{
Int32 val= (Int32)this.ComboBox3.SelectedValue;
string query = "SELECT id, name FROM data_symptom WHERE organ_system_id = " + val;
fillCombo(this.comboBox4, query, "name", "id");
}
Because you using DataBinding when filling ComboBox with items it will be logically to use SelectedValueChanged event handler
private void comboBox3_SelectedValueChanged(object sender, EventsArgs e)
{
//same code
}
You never add comboBox4 to your form. comboBox3 is added via constructor but comboBox4 is created and added to nowhere.
I'm new in this and I'm a little lost.
Trying to show the values of my database in textbox by selecting in the combobox. But I can't.
Please help me. This is my code:
private void CargarDatos()
{
string consulta = "SELECT * FROM [dbo].[alumno]";
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(Properties.Settings.Default.conexion);
SqlCommand cmd = new SqlCommand(consulta, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
con.Open();
da.Fill(dt);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
this.dataGridView1.DataSource = dt;
cbalumno.DataSource = dt;
cbalumno.DisplayMember="Nombre";
cbalumno.ValueMember="Id";
}
private void Form1_Load(object sender, EventArgs e)
{
CargarDatos();
}
private void cbalumno_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
The parameters that i want to show are "Name" "Surname" and "DNI" of the table alumno.
Any ideas to how can I do that??
You can use DataRowView to get the record being bound with current SelectedItem. The Row property of DataRowView object will give you data row. Using this row you can get the columns being bound to it.
private void cbalumno_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView vrow = (DataRowView)cbalumno.SelectedItem;
string sValue = vrow.Row["Name"].ToString();
}
You already have placed the event cbalumno_SelectedIndexChanged in your code and now you have to use it.
Inside that event, just use the Text peroperty of that textbox and assign the value of the selected item in your combo box like this :
private void cbalumno_SelectedIndexChanged(object sender, EventArgs e)
{
yourTextBoxID.Text = comboBoxID.Text;
}
Hope this helps.
private void tabControl1_Selected(object sender, TabControlEventArgs e)
{
if (e.TabPage.Name == tabPage2.Name)
{
table = Items.Get();
comboBox1.DataSource = table;
comboBox1.DisplayMember = "Item_ID";
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable temp = new DataTable();
string text = comboBox1.SelectedItem.ToString();
temp = Color.Get(text);
comboBox2.DataSource = temp;
comboBox2.DisplayMember = "Color_Name";
comboBox2.ValueMember = "Color_ID";
}
I am trying to populate the comboBox1 as the tabpage open and then populate the comboBox2 based on the selectedText of comboBox1.
comboBox_SelectedIndexChange runs 2 times when tab changes but returns null every times.
Note: I have already appended event handler as the form initializes like,
public Form1()
{
InitializeComponent();
tabControl1.Selected += new TabControlEventHandler(tabControl1_Selected);
comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
table = new DataTable();
s = new Stock();
}
First there is a bug in
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable temp = new DataTable();
string text = comboBox1.SelectedItem.ToString();
temp = Color.Get(text);
comboBox2.DataSource = temp;
comboBox2.DisplayMember = "Color_Name";
comboBox2.ValueMember = "Color_ID";
}
code. You override value for datasource in line
temp = Color.Get(text);
I think it should be like:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable temp = new DataTable();
string text = comboBox1.SelectedItem.ToString();
selectedColor = Color.Get(text);
comboBox2.DataSource = temp;
comboBox2.DisplayMember = "Color_Name";
comboBox2.ValueMember = "Color_ID";
comboBox2.SelectedItem = selectedColor;
}
I don't know contents of DataTable so instead of comboBox2.SelectedItem you may need to set SelectedItem, SelectedText or SelectedValue properties of comboBox2.
Suspicious line here:
string text = comboBox1.SelectedItem.ToString();
You will get text variable filled with "YourNamespace.DataTable". If your function Color.Get(text) is expecting Item_ID of selected item as parameter, then you should change that line of code above to:
string text = ((DataTable)comboBox1.SelectedItem).Item_ID;
I assumed that DataTable is an object that have Item_ID property.
private void tabControl1_Selected(object sender, TabControlEventArgs e)
{
if (e.TabPage.Name == tabPage2.Name)
{
table = Items.Get();
if (table.Rows.Count > 0)
{
//Update comboBox1 using table
comboBox1.DataSource = table;
comboBox1.DisplayMember = "Item_ID";
//Using 1st row and 1st coloumn in function argument to get colors
//Color.Get(string itemID) returns dataTable, which I used for comboBox2 DataSource
comboBox2.DataSource = Color.Get(table.Rows[0].ItemArray[0].ToString());
comboBox2.ValueMember = "Color_ID";
comboBox2.DisplayMember = "Color_Name";
}
}
}