【问题标题】:Getting the index of a ComboBox in in a DataGridView在 DataGridView 中获取 ComboBox 的索引
【发布时间】:2013-09-24 14:50:36
【问题描述】:

我有一个System.Windows.Forms.DataGridView,其中一列只有组合框。当 ComboBox 发生变化时,我需要知道新项目是什么,以及发生事件的 ComboBox 的行索引。后者给我带来了麻烦。我有以下内容:

class MyForm : Form
{
    private System.Windows.Forms.DataGridView m_GridView;
    private System.Windows.Forms.DataGridViewComboBoxColumn m_ComboBoxColumn;

    public MyForm () 
    {
      /* ... lots of initialisation stuf...*/
      this.m_GridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
                                       this.m_ComboBoxColumn});
    }

    private void m_GridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        ComboBox comboBox = e.Control as ComboBox;
        if (comboBox != null)
        {
            comboBox.SelectedIndexChanged -= new EventHandler(m_ComboBoxColumn_SelectedIndexChanged);
            comboBox.SelectedIndexChanged += new EventHandler(m_ComboBoxColumn_SelectedIndexChanged);
        }
    }

    private void m_ComboBoxColumn_SelectedIndexChanged(object sender, EventArgs e)
    {
        ComboBox comboBox = (ComboBox) sender;
        string item = comboBox.Text;
        if (item != null)
        {
            System.Diagnostics.Debug.WriteLine(item); // This is the new item text
            // Now I need the row index of this ComboBox in 'm_GridView' (or 'm_ComboBoxColumn')
        }
    }
}

如何在最后一种方法中找到DataGridViewComboBoxColumn 中ComboBox 的行索引?

【问题讨论】:

  • var index = comboBox.SelectedIndex;
  • 您能否更清楚地说明row indexitem index?当您说row index 时,它确实意味着包含当前组合框的DataGridViewRowindex
  • 对,所以我不是指ComboBox中选中项的索引,我需要DataGridView中ComboBox的行索引。
  • @Yellow 现在很清楚,请参阅我的解决方案答案

标签: c# winforms datagridview combobox


【解决方案1】:

您应该将其转换为DataGridViewComboBoxEditingControl 并访问EditingControlRowIndex 以获得这样的行索引:

var comboBox = (DataGridViewComboBoxEditingControl)sender;
int rowIndex = comboBox.EditingControlRowIndex;

【讨论】:

  • 当我们在这里的时候:如果您有多个带有 ComboBoxes 的列,是否有等效的方法以相同的方式查找列索引?我注意到没有 EditingControlColumnIndex 这样的东西。
  • @Yellow 我不确定,但实际上你可以检查DataGridViewCurrentCell.ColumnIndexCurrentCellAddress.X
【解决方案2】:

您可以通过 ComboBox 的 SelectedIndex 属性获取它 - http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectedindex.aspx

var index = comboBox.SelectedIndex;

【讨论】:

  • 不,我不是这个意思。我的意思是 DataGridView 中 ComboBox 本身的行索引。我更新了这个问题,试图让它更清楚一点。
猜你喜欢
  • 1970-01-01
  • 2011-11-12
  • 1970-01-01
  • 2015-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-08
  • 1970-01-01
相关资源
最近更新 更多