控件:DataGridView列类型

  DataGridView的列的类型提供有多种,包括有:

(1)DataGridViewTextBoxColumn(文本列,默认的情况下就是这种) 
(2)DataGridViewComboBoxColumn(组合框列,名字瞎起的,就是这个功能要用到的列) 
(3)DataGridViewLinkColumn(链接列) 
(4)DataGridViewButtonColumn(按钮列) 
(5)DataGridViewCheckBoxColumn(打钩列) 

一、DataGridViewComboBoxColumn

  实例:

                DataTable dt = DBServiceHelper.businessDbHelper.Fill(UserInfo, "select  a.code,a.Name  from  tequip_ini a where a.equip_type in (1,6) ");
                if (dt != null)
                {
                    dataGridViewTextBoxColumn3.DataPropertyName = "code";
                    dataGridViewTextBoxColumn3.DisplayMember = "name";
                    dataGridViewTextBoxColumn3.ValueMember = "code";
                    dataGridViewTextBoxColumn3.DataSource = dt;
                } 

          GrdReadRecord2.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(GrdReadRecord2_EditingControlShowing);

 
   

  实现每一行的该单元格具有不同的ComboBox项:  

        private void GrdReadRecord2_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            try
            {
                if (GrdReadRecord2.CurrentCell.ColumnIndex == 5)
                {
                    ComboBox cb = e.Control as ComboBox; 
                    if (cb != null)
                    {
                        DataTable dt = DBServiceHelper.businessDbHelper.Fill(UserInfo, " select  cast(0 as varchar(200)) as code ,'' as Name  UNION ALL    select  a.code,a.Name  from  tequip_ini a "+
                            " left join CardPosItem b on a.PosItem=b.id where   a.equip_type in(1,6) and  b.id= " + this.GrdReadRecord2.CurrentRow.Cells["ColPostItemID"].Value.ToString()); 
                        cb.DataSource = dt;
                        if (dt != null && dt.Rows.Count > 0)
                            cb.SelectedIndex = 0;
                    }
                }
            }
            catch (Exception ex)
            {
                ListBoxAdd(lHint2, "异常:" + ex.Message.ToString());
            }
        }

  值得注意的是:

    每一行单元格绑定的数据必须要存在列的Item内,即是在EditingControlShowing前要先设置DataPropertyName、DisplayMember、ValueMember、DataSource,EditingControlShowing查出的数据必须是DataSource的子集。不然就会认为是错误值,报错。

  获取选取值:

    获取ValueMember:GrdReadRecord2.Rows[e.RowIndex].Cells[5].Value.ToString();

    获取DisplayMember:GrdReadRecord2.Rows[e.RowIndex].Cells[5].EditedFormattedValue.ToString();

  

转载于:https://www.cnblogs.com/qi123/p/8972147.html

你可能感兴趣的:(控件:DataGridView列类型)