我想运行这样的代码,但它总是跳过循环,所以我在控制台中看不到任何行。 这意味着selectedColumns为空。我的假设是我(或用户)从列中选择一个单元格,然后,selectedColummns为+1。但是看起来,它不起作用。然后我尝试设置selectionMode的proberties来选择完整列,但随后抛出异常:
“System.InvalidOperationException”附加信息:如果选择了完整的列选择,则SortMode不能是自动的。
我不知道SortMode是什么。
For Each col As DataGridViewColumn In datagridview2.SelectedColumns
Console.Write(datagridview2.SelectedColumns.Count)
Console.Write("1")
Next
任何想法如何将列添加到selectedColumns?
这里我的代码解决了我的问题,但我想这不是最聪明的:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim body As String = ""
Dim myWriter As New StreamWriter("H:\downloads\test.csv", True)
Dim list As List(Of Integer) = New List(Of Integer)
For Each cell As DataGridViewCell In datagridview2.SelectedCells
If list.Contains(cell.ColumnIndex) = False Then
list.Add(cell.ColumnIndex)
End If
Next
For i = 0 To datagridview2.Rows.Count - 1
For ix = 0 To datagridview2.Columns.Count - 1
If list.Contains(ix) Then
If datagridview2.Rows(i).Cells(ix).Value IsNot Nothing Then
body = body + datagridview2.Rows(i).Cells(ix).Value.ToString + ";"
Else
body = body + ";"
End If
End If
Next
myWriter.WriteLine(body)
body = ""
Next
myWriter.Close()
End Sub
答案 0 :(得分:0)
您需要在选定的已更改事件触发后执行此操作。 例如:
Private Sub Mydg_ColSelected(sender As Object, e As SelectionChangedEventArgs) Handles datagridview2.SelectionChanged
For Each col As DataGridViewColumn In datagridview2.SelectedColumns
Console.Write(datagridview2.SelectedColumns.Count)
Console.Write("1")
Next
End Sub
或者,如果这不是您所追求的,那么请尝试处理ColumnHeaderMouseClick事件。我不确定您使用的是什么技术,例如Winforms,WPF,silverlight