【问题标题】:how to set SelectedIndex in DataGridViewComboBoxColumn?如何在 DataGridViewComboBoxColumn 中设置 SelectedIndex?
【发布时间】:2022-02-24 01:56:07
【问题描述】:

我使用的是datagridview,因为我使用的是datagridviewcomboboxcolumn,comboboxcolumn 正在显示文本,但问题是我想默认选择comboboxcolumn 的第一项我该怎么做

DataGridViewComboBoxColumn dgvcb = (DataGridViewComboBoxColumn)grvPackingList.Columns["PackingUnits"];
Globals.G_ProductUtility G_Utility = new Globals.G_ProductUtility();
G_Utility.addUnittoComboDGV(dgvcb);
DataSet _ds = iRawMaterialsRequest.SelectBMR(bmr_ID, branch_ID, "PACKING");
grvPackingList.DataSource = _ds.Tables[0];
int i = 0;
foreach (DataRow dgvr in _ds.Tables[0].Rows)
{
    grvPackingList.Rows[i].Cells["Units"].Value = dgvr["Units"].ToString();
    i++;
}

【问题讨论】:

    标签: c# windows


    【解决方案1】:

    可以通过 items 属性访问组合框中的可用值

    row.Cells[col.Name].Value = (row.Cells[col.Name] as DataGridViewComboBoxCell).Items[0];
    

    【讨论】:

    • 我想在 gridview 的组合框中默认选择一个文本,这在这里不起作用
    • 用于循环遍历行并在网格的 DataBindingComplete 事件中设置
    • @V4Vendetta 能否帮助您提供DataBindingComplete event 示例代码。
    【解决方案2】:

    设置 datagridViewComboBoxCell 值的最佳方法是:

    DataTable dt = new DataTable();
    dt.Columns.Add("Item");
    dt.Columns.Add("Value");
    dt.Rows.Add("Item1", "0");
    dt.Rows.Add("Item1", "1");
    dt.Rows.Add("Item1", "2");
    dt.Rows.Add("Item1", "3");
    DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
    cmb.DefaultCellStyle.Font = new Font("Tahoma", 8, FontStyle.Bold);
    cmb.DefaultCellStyle.ForeColor = Color.BlueViolet;
    cmb.FlatStyle = FlatStyle.Flat;
    cmb.Name = "ComboColumnSample";
    cmb.HeaderText = "ComboColumnSample";
    cmb.DisplayMember = "Item";
    cmb.ValueMember = "Value";
    DatagridView dvg=new DataGridView();
    dvg.Columns.Add(cmb);
    cmb.DataSource = dt;
    for (int i = 0; i < dvg.Rows.Count; i++)
    {
    dvg.Rows[i].Cells["ComboColumnSample"].Value = (cmb.Items[0] as 
    DataRowView).Row[1].ToString();
    }
    

    它对我很有效

    【讨论】:

      【解决方案3】:

      如果我知道在这次活动中这样做,它会节省我几天的挖掘和
      尝试将其设置为 CellEnter 事件中的正确索引的尝试和错误。

      设置DataGridViewComboBox的索引是我一直在寻找的解决方案.....谢谢!!!

      在审查其他编码人员在尝试设置时遇到的所有问题
      DataGridViewComboBoxCell 内部的索引以及查看您的代码后,
      任何人真正需要的是:
      1. 建立用于“EditingControlShowing”事件的事件方法。
      2. 定义方法:
      一个。将事件控件强制转换为 ComboBox。
      湾。将“SelectedIndex”设置为您想要的值。
      在此示例中,我只是将其设置为“0”,但您可能希望在此处应用如此真实的逻辑。

      这是我使用的代码:

      private void InitEvents()
      {
      
          dgv4.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler( dgv4EditingControlShowing );
      
      }
      
      
      private void dgv4EditingControlShowing( object sender, DataGridViewEditingControlShowingEventArgs e )
      {
         ComboBox ocmb = e.Control as ComboBox;
         if ( ocmb != null )
         {
            ocmb.SelectedIndex = 0;
         }
      }
      

      【讨论】:

      • EditingControlShowing 只在编辑模式下被触发,所以这不是一个有效的解决方案。
      【解决方案4】:

      如果 DataGridViewComboBoxCell 已经存在:

      DataTable dt = new DataTable();
      dt.Columns.Add("Item");
      dt.Columns.Add("Value");
      dt.Rows.Add("Item 1", "0");
      dt.Rows.Add("Item 2", "1");
      dt.Rows.Add("Item 3", "2");
      dt.Rows.Add("Item 4", "3");
      
      for (int i = 0; i < dvg.Rows.Count; i++)
      {
          DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)dvg.Rows[i].Cells[1];
          comboCell.DisplayMember = "Item";
          comboCell.ValueMember = "Value";
          comboCell.DataSource = dt;
      };
      

      【讨论】:

        【解决方案5】:

        我在使用 DataGridViews 中的 ComboBoxes 时遇到了一些真正的问题,并且没有找到一种优雅的方式来选择第一个值。但是,这是我最终得到的结果:

        public static void InitDGVComboBoxColumn<T>(DataGridViewComboBoxCell cbx, List<T> dataSource, String displayMember, String valueMember)
        {
            cbx.DisplayMember = displayMember;
            cbx.ValueMember = valueMember;
            cbx.DataSource = dataSource;
            if (cbx.Value == null)
            {
                if(dataSource.Count > 0)
                {
                    T m = (T)cbx.Items[0];
                    FieldInfo fi = m.GetType().GetField(valueMember, BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
                    cbx.Value = fi.GetValue(m);
                }
            }
        }
        

        它基本上设置 DataGridViewComboBoxCell 的 .Display 和 .ValueMember 属性,并使用 List 作为 DataSource。然后它获取第一项,并使用反射来获取用作 ValueMember 的成员的值,并通过 .Value 设置选定的值

        像这样使用它:

        public class Customer
        {
            private String name;
            public String Name
            {
                get {return this.name; }
                set {this.name = value; }
            }
        
            private int id;
            public int Id
            {
                get {return this.id; }
                set {this.id = value; }
            }
        }
        
        public class CustomerCbx
        {
            private String display;
            public String Display
            {
                get {return this.display; }
                set {this.display = value; }
            }
        
            private Customer value;
            public Customer Value
            {
                get {return this.value; }
                set {this.value = value; }
            }
        }
        
        public class Form{
        private void Form_OnLoad(object sender, EventArgs e)
        {
                //init first row in the dgv
                if (this.dgv.RowCount > 0)
                {
                    DataGridViewRow row = this.dgv.Rows[0];
                    DataGridViewComboBoxCell cbx = (DataGridViewComboBoxCell)row.Cells[0];
        
                    Customer c1 = new Customer(){ Name = "Max Muster", ID=1 };
                    Customer c2 = new Customer(){ Name = "Peter Parker", ID=2 };
                    List<CustomerCbx> custList = new List<CustomerCbx>()
                    {
                        new CustomerCbx{ Display = c1.Name, Value = c1},
                        new CustomerCbx{ Display = c2.Name, Value = c2},
                    }
        
                    InitDGVComboBoxColumn<CustomerCbx>(cbx, custList, "display", "value");
                }
            }
        }
        }
        

        对我来说这似乎很 hacky,但到目前为止我找不到更好的方法(这也适用于复杂的对象,而不仅仅是字符串)。希望这将节省对其他人的搜索;)

        【讨论】:

          【解决方案6】:

          您需要为新单元格设置项目。这必须在从 UI 创建新行时由列自动完成。

           var cell = new DataGridViewComboBoxCell() { Value = "SomeText" };
           cell.Items.AddRange(new String[]{"SomeText", "Abcd", "123"});
          

          【讨论】:

            【解决方案7】:

            对我来说不同的事情我所做的就是在使用“userAddedRow”事件向用户添加新记录时简单地设置 dtataGridComboBox 的值。对于第一行,我使用了构造函数中的代码。

            public partial class pt_drug : PatientDatabase1_3._5.basic_templet
            {
                public pt_drug()
                {
                    InitializeComponent();
                    dataGridView_drugsDM.Rows[0].Cells[0].Value = "Tablet";
                }
            
                private void dataGridView_drugsDM_UserAddedRow(object sender, DataGridViewRowEventArgs e)
                {
                    dataGridView_drugsDM.Rows[dataGridView_drugsDM.RowCount - 1].Cells[0].Value = "Tablet";
                }
            
            
            }
            

            【讨论】:

              【解决方案8】:

              这是我找到的解决方案:选择您感兴趣的单元格,以便将其转换为组合框。

                    this.Invoke((MethodInvoker)delegate
                    {
                      this.dataGridView1.CurrentCell = dataGridView1.Rows[yourRowindex].Cells[yourColumnIndex];
                      this.dataGridView1.BeginEdit(true);
                      ComboBox comboBox = (ComboBox)this.dataGridView1.EditingControl;
                      comboBox.SelectedIndex += 1;
                    });
              

              【讨论】:

                猜你喜欢
                • 2011-07-19
                • 1970-01-01
                • 1970-01-01
                • 2014-01-31
                • 1970-01-01
                • 1970-01-01
                • 2016-08-20
                • 2018-03-17
                • 1970-01-01
                相关资源
                最近更新 更多