在 winform 中 DataGrid 中实现点击任一单元格都选中当前行
先需要重写一个方法: C#:
internal
class
DataGridNoActiveCellColumn : System.Windows.Forms.DataGridTextBoxColumn
{ //重载DataGridTextBoxColumn类的Edit方法,以便使点击DataGrid中任一单元格都选中当前行 protected override void Edit(CurrencyManager source, int rowNum, Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible) { int SelectedRow = rowNum; this.DataGridTableStyle.DataGrid.Select(SelectedRow); } }
vb.net :
Friend
Class DataGridNoActiveCellColumn
Class DataGridNoActiveCellColumn Inherits System.Windows.Forms.DataGridTextBoxColumn '重载DataGridTextBoxColumn类的Edit方法,以便使点击DataGrid中任一单元格都选中当前行 Protected Overloads Overrides Sub Edit()Sub Edit(ByVal [source] As CurrencyManager, ByVal rowNum As Integer, ByVal bounds As Rectangle, ByVal [readOnly] As Boolean, ByVal instantText As String, ByVal cellIsVisible As Boolean) Dim SelectedRow As Integer = rowNum Me.DataGridTableStyle.DataGrid.Select(SelectedRow) End Sub End Class
设置datagrid样式:
Private
Sub Button1_Click()
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim tab As New DataTable("mytab") For i As Int32 = 0 To 1 tab.Columns.Add(New DataColumn("A" & i, Type.GetType("System.Decimal"))) Next tab.Columns(1).Expression = "Avg(a0)" Dim r As DataRow For i As Int32 = 0 To 10 r = tab.NewRow r("A0") = 5 + i tab.Rows.Add(r) Next Me.DataGrid1.DataSource = tab Dim tabStyle As New DataGridTableStyle Dim rCell As New DataGridNoActiveCellColumn rCell.MappingName = tab.Columns(0).ColumnName rCell.HeaderText = tab.Columns(0).ColumnName tabStyle.GridColumnStyles.Add(rCell) rCell.MappingName = tab.Columns(1).ColumnName rCell.HeaderText = tab.Columns(1).ColumnName rCell.Width = 100 tabStyle.GridColumnStyles.Add(rCell) tabStyle.MappingName = tab.TableName Me.DataGrid1.TableStyles.Add(tabStyle) End Sub