简体   繁体   English

C#如何将数据库值获取到Datagridview组合框

[英]C# How to get Database values to Datagridview Combo box

I have Datagridview and all these data is from my Database(SQL). 我有Datagridview,所有这些数据都来自我的Database(SQL)。 I have a column "Quantity" and I create a combo box in my datagrid which also "Quantity". 我有一列“数量”,并在我的数据网格中创建了一个“数量”组合框。 On run time Combo box is already there, but i can't get the values of "Quantity" (textbox) to my "Quantity" (Combo box). 在运行时,组合框已经存在,但是我无法将“数量”(文本框)的值添加到我的“数量”(组合框)中。 Here's my code 这是我的代码

private DataTable _products()
    {
        using (var con = SQLConnection.GetConnection())
        {
            var ds = new DataSet();
            var select = new SqlCommand("Select * from employee_product", con);
            var sda = new SqlDataAdapter();
            sda.SelectCommand = select;       
            sda.Fill(ds);
            dt = ds.Tables[0];


            return dt;             
        }
    }
    private void fillcombo()
    {
        var combo = new DataGridViewComboBoxColumn();
        ListProduct.Columns.Add(combo);
        combo.HeaderText = "Quantity";
        combo.Name = "combo";
        ArrayList row = new ArrayList();

        foreach (DataRow dr in dt.Rows)
        {
            row.Add(dr["Quantity"].ToString());
        }
        combo.Items.AddRange(row.ToArray());


    }

Below is a small example of what my comment describes. 以下是我的评论所描述的一个小例子。

Some pointers as what to expect when using a DataGridViewComboBoxColumn … First I recommend you wire up the grids DataError. 一些使用DataGridViewComboBoxColumn时所期望的指针…首先,我建议您连接网格DataError. If a value is in the grid that is NOT in the combo box, then the grid will throw a DataError exception. 如果组合框中的值DataError网格中,则网格将抛出DataError异常。 In addition, in most cases when this happen it will make your program non-functional as the grid will continue to throw this error whenever it gains focus or more data is added. 此外,在大多数情况下,发生这种情况将使您的程序无法正常运行,因为每当网格获得焦点或添加更多数据时,网格将继续引发此错误。 This is why you want to wire up the grids DataError … I can almost guarantee you will get this error if you are not careful making sure the combo box has ALL the values that are in the original data. 这就是为什么要连接网格DataError ……如果您不小心确保组合框具有原始数据中的所有值,我几乎可以保证会收到此错误。

It is convenient and fortunate that the posted code is filling the combo boxes will “only” the data that is actually in the DataTable. 方便和幸运的是,发布的代码填充了组合框,将“仅”存储DataTable.实际的DataTable. This makes sure that the combo boxes will be good when the data is loaded into the grid. 这样可以确保将数据加载到网格中时,组合框会很好。 Unfortunately, in the case of the “quantity” values as the code shows… ONLY the values in the DataTable will be in the combo box. 不幸的是,如代码所示,在“数量”值的情况下……只有DataTable的值才会出现在组合框中。 This may not always be the case or what you want… 并非总是如此,或者您想要的是……

From my small example below with only five (5) different “quantity” values in the data, when the code is run, each combo box only contains five (5) different values. 从下面的小示例中,数据中只有五(5)个不同的“数量”值,运行代码时,每个组合框仅包含五(5)个不同的值。 This may be a problem if the user wanted to change the value to “7.5.” That value is not in the original data and it won't be in the combo box for the user to select; 如果用户想要将该值更改为“ 7.5”,则可能会出现问题。该值不在原始数据中,也不会在组合框中供用户选择; therefore, this approach will possibly miss some needed values. 因此,这种方法可能会错过一些需要的值。

Using “quantity” as an example I would guess that you may want “quantity” to be values from 1 to 10 in .5 increments. 以“数量”为例,我想您可能希望“数量”是从1到10的值,以.5为增量。 This would be values 1, 1.5, 2, 2.5, 3, 3.5… etc. The limit of 10 is used as an example to demonstrate that often times the combo will contain values that “may” not be in the original data. 这将是值1、1.5、2、2.5、3、3.5…等。以10的限制为例说明,通常该组合将包含“可能”不在原始数据中的值。 Setting the combo box data table to these (default) values will display the values described above. 将组合框数据表设置为这些(默认)值将显示上述值。 However, looking at the original data in my example below, this will crash when it loads the data because there are values in the original data that are NOT in the combo box data table, namely 12.5, 33.5 and 22.5 since these values are greater than 10. 但是,在下面的示例中查看原始数据,这将在加载数据时崩溃,因为原始数据中的值不在组合框数据表中,即12.5、33.5和22.5,因为这些值大于10。

This is an “important” point. 这是一个“重要”点。 When ever you are using a data source on the grid and it has a combo box that is pre-filled with the data… you better make sure that the original data does NOT have a value that is NOT in the combo box. 每当您在网格上使用数据源时,它都有一个预先填充有数据的组合框……您最好确保原始数据的组合框中的值不存在。 Without this check the DataError will most likely pop up somewhere down the line. 没有此检查, DataError很可能会弹出一行。 So, it is something you would want to ALWAYS address/check for. 因此,这是您始终要查找/检查的内容。

Fortunately, the posted code is already doing this, In the GetComboColumn method below, the commented-out line GetFullComboDT will get ALL the values we want in the combo box. 幸运的是,发布的代码已经在执行此操作。在下面的GetComboColumn方法中,注释掉的行GetFullComboDT将在组合框中获取我们想要的所有值。 Now we have to make sure that the original data doesn't have any values that are NOT in the combo box. 现在,我们必须确保原始数据没有任何不在组合框中的值。 In my example below there are three (3) values that are NOT in the full combo box… 12.5, 33.5 and 22.5. 在下面的示例中,完整组合框中没有三(3)个值……12.5、33.5和22.5。 The loop will go ahead and “add” these values to the combo box. 循环将继续并将这些值“添加”到组合框。 This will almost guarantee that you will avoid getting the dreaded DataError. 这几乎可以保证您将避免遇到可怕的DataError.

I hope this makes sense and helps. 我希望这是有道理的,对您有所帮助。

public Form1() {
  InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e) {
  DataTable gridDT = GetGridTable();
  FillGridTable(gridDT);
  DataGridViewComboBoxColumn combocol = GetComboColumn(gridDT);
  dataGridView1.Columns.Add(combocol);
  dataGridView1.DataSource = gridDT;
}

private DataTable GetGridTable() {
  DataTable dt = new DataTable();
  dt.Columns.Add("Col1", typeof(string));
  dt.Columns.Add("Col2", typeof(string));
  dt.Columns.Add("Quantity", typeof(decimal));
  return dt;
}

private DataTable GetComboTable() {
  DataTable dt = new DataTable();
  dt.Columns.Add("index", typeof(int));
  dt.Columns.Add("Quantity", typeof(decimal));
  return dt;
}

private void FillGridTable(DataTable dt) {
  dt.Rows.Add("C0R0", "C1R0", 12.5);
  dt.Rows.Add("C0R1", "C1R1", 2);
  dt.Rows.Add("C0R2", "C1R2", 33.5);
  dt.Rows.Add("C0R3", "C1R3", 1);
  dt.Rows.Add("C0R4", "C1R4", 22.5);
  dt.Rows.Add("C0R5", "C1R5", 1);
  dt.Rows.Add("C0R6", "C1R6", 12.5);
}

private DataGridViewComboBoxColumn GetComboColumn(DataTable dt) {
  DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
  combo.HeaderText = "Quantity";
  combo.Name = "combo";
  combo.DataPropertyName = "Quantity";
  combo.DisplayMember = "Quantity";
  DataTable comboDT = GetComboTable();
  //DataTable comboDT = GetFullcomboDT();
  int index = 0;
  foreach (DataRow dr in dt.Rows) {
    if (NewValue((decimal)dr["Quantity"], comboDT)) {
      comboDT.Rows.Add(index, dr["Quantity"]);
    }
  }
  combo.DataSource = comboDT;
  return combo;
}

private bool NewValue(decimal value, DataTable dt) {
  foreach (DataRow row in dt.Rows) {
    if (((decimal)row["Quantity"]) == value) {
      return false;
    }
  }
  return true;
}

private DataTable GetFullcomboDT() {
  DataTable dt = new DataTable();
  dt.Columns.Add("index", typeof(int));
  dt.Columns.Add("Quantity", typeof(decimal));
  decimal currentValue = 1.0m;
  int index = 0;
  for (int i = 0; i < 20; i++) {
    dt.Rows.Add(index, currentValue);
    currentValue += 0.5m;
    index++;
  }
  return dt;
}

You have to manually add the values to the comboboxes and declare the type of them first. 您必须手动将值添加到组合框并首先声明它们的类型。 Something like that should do it: 这样的事情应该做到:

    DataGridViewComboBoxCell dgvcell;
    for (int x = 0; (x <= (DataGridView1.Rows.Count - 1)); x++) 
    {
    SQL_cmd.CommandText = "select something from somethingelse where something = @something ";
        sql_cmd.parameters.addwithvalue("@something", DataGridView1.Rows[x].Cells["something"].Value);
        SQL_reader = SQL_cmd.ExecuteReader;
        while (SQL_reader.Read) {
        dgvcell = ((DataGridViewComboBoxCell)(this.DataGridView1.Rows(x).Cells["something"]));
        dgvcell.Items.Add(SQL_reader("something"));
        }

        SQL_reader.Close();
    }

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

相关问题 C#:如何将查询结果设置为datagridview中的组合框 - C#: How to set query result to combo box in datagridview 从数据库获取多个值,并在索引更改C#时显示在组合框和不同的文本框中 - get multiple values form the database and show in combo box and different text boxes when the index change c# 如何在C#中获取数据库(sql)表名和列以组合和列表框 - how to get database (sql) table names and colums in C# to combo and list box 如何从SQL数据库获取数据以存储在组合框中-C# - How to get data from SQL database to store in combo box - C# 如何使用c#在组合框中从数据库获取所有表的名称 - How get the names of all the tables from a database in a combo box using c# 如何从SQL数据库中获取数据以存储到组合框中 - C# - How to get data from SQL database to store in to a combo box - C# 如何从C#中的数据gridview获取选定的行值到组合框 - How to get selected row values to combo box from data gridview in c# 如何从SQL数据库中获取数据到组合框 - C# - How to fetch data from SQL database to combo box - C# C#Windows窗体如何根据第一个组合框中的选择更改第二个组合框的值 - C# Windows Forms how to change values of second combo box based on selection in first combo box 如何使用组合框中的值在C#中进行计算 - How to use values from combo box to calculate in c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM