通过传递列和行名填充datagridview

问题描述:

我有DataGridView下面,我需要根据收到的一些文件检查单元格,我正在寻找最好的方法来做到这一点,我认为这将是可能的插入由列的名称,并在单元格中值的行通过传递列和行名填充datagridview

enter image description here

的位置是

enter image description here

如果我想纪念位置0,0我会的名称看f或31 - SEGUROS(列的名称),并(行的名称),然后它会被标记细胞0,0

这是可能的吗?

DataGridView具有包含RowIndex和ColumnIndex的CurrentCell属性。

还有CellEnter事件,其中DataGridViewCellEventArgs包含RowIndex和ColumnIndex。

存在具有重载接受索引或名称的行和列属性。但是,列的名称和列标题之间存在差异。在你的情况下,“31 - SEGUROS”是列的标题,而不是它的名称。每个Column对象都有一个HeaderText属性。

如果没有选择列或行,其索引将为-1。

你在寻找行列索引吗?我看了你的问题,三次,还是它看起来像它...

VB.NET:

Dim MyVal = 1234 
    Dim ColIdx = 5 
    Dim RowIdx = 10 
    Me.DataGridView1.Rows(RowIdx).Cells(ColIdx).Value = MyVal 

C#:

Dynamic MyVal = 1234; 
    Dynamic ColIdx = 5; 
    Dynamic RowIdx = 10; 
    this.DataGridView1.Rows(RowIdx).Cells(ColIdx).Value = MyVal; 

您还可以通过他们的名字解决行和单元格,只需将他们的名字放在双引号中即可。

按列名获取列索引(在标题不是文本):

VB.NET:

Private Function GetColIdx(MyStringName As String) 
    Dim ColIdx As Int16 
    For ic = 0 To Me.DataGridView1.Columns.Count - 1 
     Dim dc As DataGridViewColumn = Me.DataGridView1.Rows(ic) 
     If dc.Name = MyStringName Then 
      ColIdx = ic 
      Exit For 
     End If 
    Next 
    Return ColIdx 
End Function 

C#:

Private Object GetColIdx(String MyStringName) 
{ 
    Int16 ColIdx = default(Int16); 
    For (ic = 0; ic <= this.DataGridView1.Columns.Count - 1; ic++) { 
     DataGridViewColumn dc = this.DataGridView1.Rows(ic); 
     If (dc.Name == MyStringName) { 
      ColIdx = ic; 
      break; 
     } 
    } 
    Return ColIdx; 
} 

要获得列索引,您只需调用(C#)函数,其名称为

GetColIdx("SEGUROS") 

类似的功能可以按名称获取行。尽管使用行名很不常见,但这是可能的。它也可以修改为匹配标题中的文本,但名称更安全。