0

the actual problem is i want to populate data grid view depending upon combo box value but i want to hold the value in grid view when i click a value in combo box. but in my code when i select a value from combo box it shows into grid view but i click next value it shows next value but older one does not remain in grid view, am new so please guide me thoroughly Tnanks

     private void Display_Load(object sender, EventArgs e)
       {   
    string str = "SELECT i_id, i_name FROM sales";         
    comboBox1.DataSource = getData(str);     
    comboBox1.DisplayMember = "i_name";   
    comboBox1.ValueMember = "i_id"; 
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    int val;
    Int32.TryParse(comboBox1.SelectedValue.ToString(), out val);
    string str = "SELECT i_id, i_name, qty, rate,discount  FROM sales WHERE i_id = " + val;
    dataGridView1.DataSource = getData(str);
}
ehsanulhaq
  • 11
  • 3
  • Possible duplicate of [Add rows wise data in data grid view depending on the value of cmbo box.](http://stackoverflow.com/questions/36469076/add-rows-wise-data-in-data-grid-view-depending-on-the-value-of-cmbo-box) – Panda Apr 07 '16 at 07:31

1 Answers1

0

In the line

dataGridView1.DataSource = getData(str);

You are replacing the DataSource of your DataGrid.

You have to replace this line with adding the result of the getData method into the DataSource - Add a Row After Setting DataSource to Datagridview.

Something like this:

public partial class MyWindow
{
    BindingList<Data_Type> list = new BindingList<Data_Type>();

    private void Display_Load(object sender, EventArgs e)
    {
        string str = "SELECT i_id, i_name FROM sales";
        comboBox1.DataSource = getData(str);
        comboBox1.DisplayMember = "i_name";
        comboBox1.ValueMember = "i_id";

        dataGridView1.DataSource = list;
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        int val;
        Int32.TryParse(comboBox1.SelectedValue.ToString(), out val);
        string str = "SELECT i_id, i_name, qty, rate,discount  FROM sales WHERE i_id = " + val;

        var newData = getData(str);
        foreach (var line in newData)
        {
            list.Add(line);
        }
    }
}

As that uses a BindingList<T> depending on the control you are using, this should just add the new data into the already shown items.

Community
  • 1
  • 1
Petr Vávro
  • 1,506
  • 1
  • 10
  • 12