【问题标题】:Find Column Index by referencing Column Name?通过引用列名查找列索引?
【发布时间】:2018-02-27 08:00:21
【问题描述】:

如何通过ColumnName 从DataGridView 获得Column 的ColumnIndex?

这是伪代码:

ColumnIndex = ColumnName("SampleName"); 

【问题讨论】:

  • 您的伪代码没有反映您的解释,请编辑您的帖子以使其更清晰

标签: c# .net winforms datagridview


【解决方案1】:

您可以使用IndexOf。像这样:

var dataGridViewColumn = dataGridView1.Columns[ColumnName];
if (dataGridViewColumn != null)
{
    int index = dataGridView1.Columns.IndexOf(dataGridViewColumn);
}

或者像这样使用Index 和Null-conditional 运算符(?.):

var index = dataGridView1.Columns[ColumnName]?.Index;

【讨论】:

    【解决方案2】:

    最简单的方法:

    myData.Columns.IndexOf(/*DataGridViewColumn*/)
    myData.Columns[/*ColumnName*/].Index
    

    或者:

    private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        int ColumnIndex= dataGridView.CurrentCell.ColumnIndex;       
    }
    

    【讨论】:

    • 这似乎回答了伪代码部分,但我不理解 OP 的解释。对我来说,当他知道列名时,他想获得索引。
    • 他想知道 column Index = column Name 这就是为什么我这样回答@Rafalon sir
    • 是我自己还是你的回答和你的评论不一致? OP想要获取索引,而您正在获取名称,我缺少什么吗? (我会写int columnIndex = e.ColumnIndex;)无论如何,您的解决方案只有在用户点击一个单元格时才有效,而且问题中的任何地方都没有提到这一点
    【解决方案3】:

    获取列的索引

    myDGV.Columns.IndexOf(myDGV.Columns["SampleColumn"];
    

    或者像你说的更简单

    myDGV.Columns["SampleColumn"].Index;
    

    【讨论】:

      猜你喜欢
      • 2018-09-22
      • 2014-07-06
      • 1970-01-01
      • 2019-11-27
      • 2016-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      相关资源
      最近更新 更多