在文本字段中,用户可以键入名称,然后按下按钮,程序将在DataGridView上搜索名称并突出显示记录行
搜索和突出显示循环
For Each row In DataGrid.Rows
If row.Cells("userName").Value = userNameToSearch Then
row.Selected = True
Exit For
End If
Next
循环正常
然后我需要移动DataGridView的索引以匹配该行
如果我使用
Dim MyFindedIndex As Integer
MyFindedIndex = DataGrid.CurrentRow.Index
即使我知道匹配并突出显示的行是第7个例子,我也得到0。
如果我理解的话,还需要移动当前单元格的索引,因为当前单元格是确定索引值的单元格
我可以强制转移到索引号7
DataGrid.CurrentCell = DataGrid.Item(0, 7)
但我需要以编程方式执行此操作(找到“7”数字)
也许使用IndexOf或类似的东西?
解决方案
使用Fabio回答!
单元格的列需要可见,而我的DataGridView则不是这种情况,因为单元格包含用户不需要查看的主键编号
解决方案:一个用于搜索的单元格,一个用于位置的单元格(此一个可见)
For Each row In DataGrid.Rows
'Cell to search
Dim cell As DataGridViewCell = row.Cells("userNumber")
'Cell to position
Dim cell2 As DataGridViewCell = row.Cells("userName")
If cell.Value.ToString().Equals(userNumberToSearch) = True Then
DataGrid.CurrentCell = cell2
Exit For
End If
Next
如果单元格的列不可见VB抛出系统空引用
答案 0 :(得分:1)
对于DataGridView,您可以使用:
Datagridview.CurrentCell.RowIndex
答案 1 :(得分:1)
设置For Each row In DataGrid.Rows
Dim cell As DataGridViewCell = row.Cells("userName")
If cell.Value.ToString().Equals(userNameToSearch) = True Then
DataGrid.CurrentCell = cell
Exit For
End If
Next
就足够了。在搜索循环中执行此操作
static void Main(string[] args)
{
DataTable table = GetTable();
var result = table.AsEnumerable().GroupBy(r => r["CompanyId"]).Select(c => new
{ Company = c.Key, Totals = c.Select(t => new
{
Total1 = c.Select(t1 => new { Year = t1["Year"], Total1 = t1["Total1"] }).ToArray(),
Total2 = c.Select(t2 => new { Year = t2["Year"], Total2 = t2["Total2"] }).ToArray(),
Total3 = c.Select(t3 => new { Year = t3["Year"], Total3 = t3["Total3"] }).ToArray(),
}).ToArray()
}).ToArray();
//ToArray() simply to make it visually cleaner in the object browser
}
static DataTable GetTable() //Sample datatable I created
{
DataTable table = new DataTable();
table.Columns.Add("CompanyId", typeof(int));
table.Columns.Add("Year", typeof(int));
table.Columns.Add("Total1", typeof(decimal));
table.Columns.Add("Total2", typeof(decimal));
table.Columns.Add("Total3", typeof(decimal));
table.Rows.Add(3022, 2016, 36.7, 98.1, 10.4);
table.Rows.Add(3022, 2015, 77.3, 55.3, 98.4);
table.Rows.Add(3011, 2016, 73.1, 13.3, 11.6);
table.Rows.Add(3011, 2015, 33.6, 10.9, 8.1);
return table;
}