populate combobox depending on another combobox - c#

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.

Related

selected index value in C# with combobox with database

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

How can I show the combobox selected value in a text box‎ C#?

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.

listbox datasource update ms access winform

i create a winform application with a listbox datasource that come from ms access database. the problem is when i click the Update button the listbox is not getting update. example i change the "ITEM1" to ITEM2", its just not working but the database do because i execute a command that will update the database. i need to reload(re-open) my application then on that time i will see my modification. how do i update the listbox? i've read something about this problem before but i dont understand about it clearly..i wish someone could help me out..
private BindingList<PRODUCTLIST> _productlist;
public Form1()
{
InitializeComponent();
}
public class PRODUCTLIST
{
public string ID { get; set; }
public string ITEM { get; set; }
public string ITEM_DESC { get; set; }
}
private static OleDbConnection GetConnection()
{
OleDbConnection mdbConn = new OleDbConnection();
try
{
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=shop.mdb;Jet OLEDB:Database Password=xxxxx;";
mdbConn = new OleDbConnection(connectionString);
mdbConn.Open();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
return mdbConn;
}
private void Form1_Load(object sender, EventArgs e)
{
// make ID textbox un editable
textBoxID.Enabled = false;
_productlist = new BindingList<PRODUCTLIST>();
string strSQL = "SELECT * FROM Item ORDER BY ITEM";
OleDbDataAdapter myCmd = new OleDbDataAdapter(strSQL, GetConnection());
DataSet dtSet = new DataSet();
myCmd.Fill(dtSet, "Item");
DataTable dTable = dtSet.Tables[0];
foreach (DataRow dtRow in dTable.Rows)
{
_productlist.Add(new PRODUCTLIST() { ID = dtRow["ID"].ToString(), ITEM = dtRow["ITEM"].ToString(), ITEM_DESC = dtRow["ITEM_DESC"].ToString() });
}
listBox1.DisplayMember = "ITEM";
listBox1.DataSource = _productlist;
//listBox1.DataBindings = _productlist;
listBox1.ValueMember = "ID";
// set the textbox binding and DataSourceUpdateMode to Never because i have other button to add the new item
textBoxID.DataBindings.Add("Text", _productlist, "ID", false, DataSourceUpdateMode.Never);
textBoxITEM.DataBindings.Add("Text", _productlist, "ITEM", false, DataSourceUpdateMode.Never);
textBoxITEMDESC.DataBindings.Add("Text", _productlist, "ITEM_DESC", false, DataSourceUpdateMode.Never);
}
private void buttonUpdate_Click(object sender, EventArgs e)
{
// update data on database
OleDbCommand cmd = new OleDbCommand("UPDATE Item SET ITEM = #ITEM, ITEM_DESC = #ITEM_DESC WHERE ID = #ID", GetConnection());
cmd.Parameters.AddWithValue("#ITEM", textBoxITEM.Text);
cmd.Parameters.AddWithValue("#ITEM_DESC", textBoxITEMDESC.Text);
cmd.Parameters.AddWithValue("#ID", Convert.ToInt32(textBoxID.Text));
cmd.ExecuteNonQuery();
// make the listbox datasource update
//listBox1.Refresh();
//listBox1.DataSource = null;
//listBox1.DataSource = _productlist;
//_productlist = new BindingList<PRODUCTLIST>();
//string strSQL = "SELECT * FROM Item ORDER BY ITEM";
//OleDbDataAdapter myCmd = new OleDbDataAdapter(strSQL, GetConnection());
//DataSet dtSet = new DataSet();
//myCmd.Fill(dtSet, "Item");
//DataTable dTable = dtSet.Tables[0];
//foreach (DataRow dtRow in dTable.Rows)
//{
// _productlist.Add(new PRODUCTLIST() { ID = dtRow["ID"].ToString(), ITEM = dtRow["ITEM"].ToString(), ITEM_DESC = dtRow["ITEM_DESC"].ToString() });
//}
//listBox1.DisplayMember = "ITEM";
//listBox1.DataSource = _productlist;
////listBox1.DataBindings = _productlist;
//listBox1.ValueMember = "ID";
}
The way you are doing it you need to clear and repopulate your list box.
You should extract that code as a method from the FormLoad event handler and call it after you run the update query.
It's hard to tell which way you want to go. Based on what you are asking.
What you should be doing is making your products data table a private property. Creating and open it up and bind to the list box.
Then your update function should be changing the datatable. Then you'd see the changes in your list box. The thing to appreciate though is until you flush the changes (ApplyChanges method) you have made to the datatable back to the database server all you've done is change a local copy of the data.
That can be good and bad. Depends on what you want to do with multiple users updating products at the same time.
So you've got datatable with a local copy and shown it.
Then you've updated the table you copied, and now your copy is out of step.
Exactly the same problem you would have, if you ran up another copy of your app and changed one of the records you'd already shown in the first one.

"System.Data.DataRowView" in form load using combobox in C#

Every time my forms loads/open it will prompt "System.Data.DataRowView", How can I possibly remove this?
Here is my code:
{
InitializeComponent();
GetProcessorCardTypes();
}
private void GetProcessorCardTypes()
{
cn.Open();
MySqlCommand cmd = new MySqlCommand("call GetProcessorMethod(1)", cn);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
cmbProcessorMethods.DataSource = dt;
cmbProcessorMethods.ValueMember = "method_id";
cmbProcessorMethods.DisplayMember = "method_name";
}
private void cmbProcessorMethods_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show(cmbProcessorMethods.SelectedValue.ToString());
}
If you want to completely remove message box, then remove cmbProcessorMethods_SelectedIndexChanged event handler. Or you can change it to display method_name of selected row:
private void cmbProcessorMethods_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView row = (DataRowView)cmbProcessorMethods.SelectedItem;
MessageBox.Show(row["method_name"].ToString());
}
As Derek pointed, just set DisplayMember and ValueMember properties before assigning data source and your original code will work:
cmbProcessorMethods.ValueMember = "method_id";
cmbProcessorMethods.DisplayMember = "method_name";
cmbProcessorMethods.DataSource = dt;

How to transfer data contained in a textbox to a datagridview?

I have 4 textboxes in a windows form application and a gridview and button called 'Add'. All I want is, the data entered in 4 textboxes should be gone to the datagridview's four different columns in the same row as i click Add button. If i clear the text boxes, fill them again and click the Add button again then the data should go to the 2nd row of the gridview.
create a class like the following somewhere in your app
public class MyClass
{
public string field1 { get; set; }
public string field2 { get; set; }
public string field3 { get; set; }
public string field4 { get; set; }
}
inside your form.cs write this,
public static List<MyClass> lst = new List<MyClass>();
in the click event of your add button do this
private void btnAdd_Click(object sender, EventArgs e)
{
MyClass obj = new MyClass();
obj.field1 = txt1.Text.Trim();
obj.field2 = txt2.Text.Trim();
obj.field3 = txt3.Text.Trim();
obj.field4 = txt4.Text.Trim();
lst.Add(obj);
dataGridView1.DataSource = lst;
}
use this code:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Dataset;Integrated Security=True");
SqlDataAdapter ds1 = new SqlDataAdapter();
BindingSource bd = new BindingSource();
public Form1()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
ds1.InsertCommand = new SqlCommand("INSERT INTO Employee VALUES(#FirstName,#LastName)", con);
ds1.InsertCommand.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
ds1.InsertCommand.Parameters.Add("#LastName", SqlDbType.VarChar).Value = txtLastName.Text;
con.Open();
ds1.InsertCommand.ExecuteNonQuery();
con.Close();
}
private void btndisplay_Click(object sender, EventArgs e)
{
ds1.SelectCommand = new SqlCommand("Select * from Employee", con);
ds.Clear();
ds1.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
bd.DataSource = ds.Tables[0];
//txtFirstName.DataBindings.Add("Text", bd, "FirstName");
//txtLastName.DataBindings.Add("Text", bd, "LastName");
}
private void btnPervious_Click(object sender, EventArgs e)
{
bd.MovePrevious();
update();
records();
}
private void btnNext_Click(object sender, EventArgs e)
{
bd.MoveNext();
update();
records();
}
private void btnFirst_Click(object sender, EventArgs e)
{
bd.MoveFirst();
update();
records();
}
private void btnLast_Click(object sender, EventArgs e)
{
bd.MoveLast();
update();
records();
}
private void update()
{
dataGridView1.ClearSelection();
dataGridView1.Rows[bd.Position].Selected = true;
records();
}
private void records()
{
label1.Text = "records" + bd.Position + " of " + (bd.Count - 1);
}
dont forget to markup this answer
Steps to follow:
1) Upon Binding the DataGrid View, save the DataSource in a Viewstate Variable
2) Define Click event for Add Button
In the click event, recall the Viewstate Variable that has the datasource, Cast it as a DataTable. Make a new row of that datatable, assign values to the cells of the new row. Add this new row to the Datatable, Save the dataTable in ViewSate again, Bind the datasource to the DataGrid
That's All~
Thanks to Mr. SHAKIR SHABBIR first of all, but as i think there is no viewstate in windows form application...
i suggest to use static collection types...
you can define a class for your entry form and foreach textbox a variable, when you click the add button create object of the class, setting all its values with your textboxes, inserting row in grid, and saving all rows data(object of class per gridview row) in a List
you can also use a static datatable... you have to create columns for each of your textfield..
adding row to datatable.. selecting the datasource of your grid...
if you need further help, i am alway here to help you..

Categories