在Datagridview上动态设置组合框值

时间:2019-02-13 18:56:35

标签: c# winforms

我正在尝试使用以下代码从查询中动态设置组合框值,并且只有在单击组合框列时才会显示该组合框值,如果不单击,该值会消失且未设置。

前5个值与用户相关,并且组合框上显示的值可能未设置到数据库中,因此如果不存在,或者键入“ A”或“ C”,则该值可能为null。

这是单击单元格之前的图像 enter image description here

此图像是在单击已加载数据的单元格后 enter image description here

此图像是在取消单击单元格并选择任何其他单元格后的

enter image description here

//This code is used to Build combobox column  after the data is binded 
var items = new[] { new Logica.Items { valor = "C", texto = "Creador" }, new Logica.Items { valor = "A", texto = "Aprobador" } };
DataGridViewComboBoxColumn cell = new DataGridViewComboBoxColumn();
cell.DataSource = items;
cell.ValueMember = "valor";
cell.DisplayMember = "texto";

this.dataGridView1.Columns.Insert(5, cell);
this.dataGridView1.Columns[5].HeaderText = "TipoUsuario";

for (int i = 0; i < this.dataGridView1.RowCount; i++)
{
    string valor = dataGridView1[0, i].Value.ToString();//get the first datagridview value
    if (valor != null || valor != "")
    {
        string orgv = string.Empty + this.dataGridView1[0, i].Value.ToString().ToUpper();//required to fill combobox conditions
        string veg = string.Empty + this.dataGridView1[1, i].Value.ToString().ToUpper();//required to fill combobox conditions
        string aprobador = string.Empty + this.dataGridView1[3, i].Value.ToString().ToUpper();//required to fill combobox conditions
        DataTable ds = cargarnodos("LLenaTipoUsuario"); // this query into db to get the combobox values if this exists, if not then it's null.
        foreach (DataRow datar in ds.Rows)
        {
            if (orgv == datar["VKORG"].ToString() && veg == datar["VTWEG"].ToString() && aprobador == datar["idAprobador"].ToString())
            {
                string seleccion = datar["TipoUsuario"].ToString().ToUpper();
                this.dataGridView1[5, i].Value = seleccion; // this changes value


                MessageBox.Show(dataGridView1[5, 0].Value.ToString());


                break;
            }
        }
    }

2 个答案:

答案 0 :(得分:0)

即使没有选择行,我也设法使行显示单元格中的数据。这是通过设置ComboBoxColumn的DataPropertyName完成的。

        cell.DataPropertyName = "valor"; //

应该是数据列,其对应于父级Datasource的{​​{1}}可用,并且它们的数据类型相同。

如果此列中的内容可以包含DataGridView,请添加以下行(如果允许用户选择/更改等)

null

答案 1 :(得分:0)

就我而言,在加载表单时无法设置组合框值。绑定datagridview后,需要使用以下命令根据先前的选择来编辑值。

dataGridView1.DataBindingComplete + =新的DataGridViewBindingCompleteEventHandler(selecciongv_DataBindingComplete); // selecciongv是执行相同过程的方法。

相关问题