如何获取标题与某个字符串匹配的列索引

本文关键字:字符串 字符 串匹配 索引 何获取 获取 标题 | 更新日期: 2023-09-27 18:35:39

我需要获取标题文本与字符串"delete"匹配的DataGridViewRow的列索引。

  1. 你能给我一个提示吗?
  2. 我如何通过这个表达式来达到它:

    DataGridViewColumn c = new DataGridViewColumn();
    int index = Specialization_DataGridView.Columns.IndexOf(c.HeaderText.Where(/* dont know how to write expression where header text matches to "delete" */));
    

如何获取标题与某个字符串匹配的列索引

如果您将DataGridViewColumnNameHeaderText属性设置为相同,则获取索引很简单:

int index = Specialization_DataGridView.Columns["delete"].Index;

如果它们不同,请遍历列,直到找到它:

int index = -1;
foreach (DataGridViewColumn col in Specialization_DataGridView.Columns)
{
    if (col.HeaderText == "delete")
    {
        index = col.Index;
        break;
    }
}

尝试使用扩展:

<Extension>
    Public Sub DgvColumnNameByHeaderText(Dgv As DataGridView)
        Dim c As DataGridViewColumn
        With Dgv
            For Each c In Dgv.Columns
                c.Name = c.HeaderText
            Next
        End With
    End Sub
    ' Use: DataGridView1.DgvColumnNameByHeaderText()