简体   繁体   English

如何从combox向C#中的数据网格视图添加值

[英]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: 最后,在组合框的SelectedIndexChanged事件上:

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). 根据以下设置,有两种方法可以解决问题:如果只想为dataGridView添加单行,则只需按照以下Method(1)使用列表的概念。

But If you want to add more rows upon select from ComboBox then you would use DataTable Method(2). 但是,如果要从ComboBox中选择添加更多行,则可以使用DataTable Method(2)。 Note that DataTable also include primaryKey for your productID Column in GridView that selected from ComboBox. 请注意,DataTable还包括从ComboBox中选择的GridView中productID列的primaryKey。

If you want to remove Primary Key Comment the code of primary key in Method(2). 如果要删除主键,请注释Method(2)中的主键代码。

Method(1): 方法(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): 方法(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, 如果要删除PrimaryKey,请注释以下代码,

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

Stay blessed 祝好运

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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