简体   繁体   中英

How to Add a value from combox to data grid view in C#

I have data in combo box retrieved from database.

How do I add that data to Data Grid View when value are selected from combo box?

SqlConnection conn = new SqlConnection(conStr);
        string query = "select * from products";
        SqlCommand cmd = new SqlCommand(query, conn);

        conn.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        while (rdr.Read())
        {
            comboBox3.Items.Add(rdr[0]+"-\t"+rdr[1]+"-"+"Exp Date\t"+rdr[4]);
        }

        conn.Close();

above is my code that retrieve data to combo box,

So you should save records on a list, array etc for example:

List<string> LstProductos = new List<string>;

Then

while (rdr.Read())
{
   LstProductos.Add(rdr[0]+"-\t"+rdr[1]+"-"+"Exp Date\t"+rdr[4])
}

For load Combobox:

foreach(string str in LstProductos)
{
   ComboBox.items.add(str);
}

Finally on your SelectedIndexChanged event of your combobox:

private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    string YourItem = comboBox1.Text;

    //If you only want to add selected item
    DataGridView.Add(YourItem);

    //or add all
    foreach (string str in LstProductos)
    {
           DataGridView.Rows.Add(str);
    }
}

There are two ways to solve your problem according to following setups If you just want to add only single row for your dataGridView then you only have to use the concept of list according to following Method(1).

But If you want to add more rows upon select from ComboBox then you would use DataTable Method(2). Note that DataTable also include primaryKey for your productID Column in GridView that selected from ComboBox.

If you want to remove Primary Key Comment the code of primary key in Method(2).

Method(1):

public class GridviewData
{
    public string ProductId{set;get;}
    public string ProductName { set; get; }
    public string ExpireDate { set; get; }
}
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string selectedItem = comboBox1.SelectedItem.ToString();
        List<string> dataList = selectedItem.Split('-').ToList();
        GridviewData data = new GridviewData();
        data.ProductId = dataList[0];
        data.ProductName = dataList[1];
        data.ExpireDate = dataList[2];
        List<GridviewData> gridviewList = new List<GridviewData>();
        gridviewList.Add(data);
        dataGridView1.DataSource = gridviewList;
    }
}

Method(2):

public partial class Form1 : Form
{
    DataTable dt = new DataTable();
    public Form1()
    {
        InitializeComponent();
        DataColumn productID = new DataColumn();
        productID.ColumnName = "Product ID";
        dt.Columns.Add(productID);
        dt.Columns.Add("Product Name");
        dt.Columns.Add("Expire Date");
        dt.PrimaryKey = new DataColumn[] {productID };//if you want to set primary key for dataTable upon productID
    }
    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            string selectedItem = comboBox1.SelectedItem.ToString();
            List<string> data = selectedItem.Split('-').ToList();
            dt.Rows.Add(new object[] { data[0], data[1], data[2] });
            dataGridView1.DataSource = dt;
        }
        catch(Exception er)
        {
            MessageBox.Show(er.Message);
        }
    }
}

If you want to remove PrimaryKey then comment following code,

//dt.PrimaryKey = new DataColumn[] {productID };

Stay blessed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM