怎样选择DataGrid中的一行?

解决方案 »

  1.   

    在datagrid的mouseup事件里面加入: DataGrid.HitTestInfo hit = this.datagrid.HitTest(e.X,e.Y);
    if(hit.Type == DataGrid.HitTestType.Cell)
    {
    datagrid.Select(hit.Row);
    if(datagrid.DataSource != null)
    {
    tmpDS = (DataSet)datagrid.DataSource;
    DataRowView rowView = (DataRowView)datagrid.BindingContext[datagrid.DataSource,tmpDS.Tables[0].TableName].Current;
    }
    }
      

  2.   

    private void dataGrid1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
    {
    Point pt = new Point(e.X,e.Y);
    DataGrid.HitTestInfo hit = dataGrid1.HitTest(pt);
    if(hit.Type == DataGrid.HitTestType.Cell) 
    {
    dataGrid1.Select(hit.Row); 
    }
    }
      

  3.   

    Private Sub grdMoney_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles grdMoney.MouseDown
            Try
                '''处理
                If e.Button = MouseButtons.Left Then                            '左键点击
                    Me.gpbMoney.Focus()                                    '转移焦点
                    Dim objHitTest As System.Windows.Forms.DataGrid.HitTestInfo 'DataGrid的点击信息
                    objHitTest = Me.grdMoney.HitTest(e.X, e.Y)                  '取得鼠标点击信息(列号,行号)
                    M_intRowIndex = -1                                              '初始化为-1 
                    If objHitTest.Type <> DataGrid.HitTestType.None Then            '点击不是空白处
                        If objHitTest.Row <> -1 Then                                '有选中的行索引
                            M_intRowIndex = objHitTest.Row                          '存放选中的行索引
                        End If
                    ElseIf objHitTest.Type = DataGrid.HitTestType.None Then         '点击空白处
                        Me.grdMoney.UnSelect(Me.grdMoney.CurrentRowIndex)             '取消选中当前行
                    End If
                End If
                '''异常处理
            Catch ex As Exception
                ProjectException.ShowErrMsg(Me.Name, "grdMoney_MouseDown", ex.Message)
            End Try
        End Sub
        Private Sub grdMoney_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles grdMoney.MouseUp
            Try
                '''处理
                If e.Button = MouseButtons.Left Then      '左键UP
                    If M_intRowIndex >= 0 And M_intRowIndex <= Me.grdMoney.VisibleRowCount - 1 Then '索引在grdMoney是有效行索引
                        Me.grdMoney.Select(M_intRowIndex) '设置DataGride选中行
                    End If
                End If
                '''异常处理
            Catch ex As Exception
                ProjectException.ShowErrMsg(Me.Name, "grdMoney_MouseUp", ex.Message)
            End Try
        End Sub