当用户单击该行的单元格时,如何选择完整的dataGridView行?

时间:2012-12-02 19:07:00

标签: c# .net winforms datagridview

我有dataGridView我需要当用户点击任何单元格时,也会选择包含此单元格的整行。 (它有多选的废弃) 我试着像这样currentRowIndex

 int Index = dataGridView1.CurrentCell.RowIndex;

但是,我不知道如何使用索引来选择该行。 试过这个和其他六种方法没有成功:

dataGridView1.Select(Index);

你知道我能做到这一点吗?

6 个答案:

答案 0 :(得分:85)

您需要将datagridview的SelectionMode设置为FullRowMode

注意:在使用.NET 4.5的Visual Studio 2013中,该属性称为FullRowSelect,请参阅https://msdn.microsoft.com/en-us/library/3c89df86(v=vs.110).aspx

答案 1 :(得分:8)

如果您希望以编程方式选择行,则可以使用datagridview的单元格单击事件:显示在VB.net和C#中

VB.Net

Private Sub dgvGrid_CellClick(sender as System.Object, e as System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvGrid.CellClick
    If e.RowIndex < 0 Then
        Exit Sub
    End If

    intIndex = e.RowIndex
    dgvGrid.Rows(intIndex).Selected = True
Exit Sub

C#

private void dgvRptTables_CellClick(System.Object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
{
    if (e.RowIndex < 0) {
        return;
    }

    int index = e.RowIndex;
    dgvGrid.Rows[index].Selected = true;
}

答案 2 :(得分:2)

在DataGridView属性中, 设置

  • MultiSelect - &gt;真
  • SelectionMode - &gt; FullRowSelect

答案 3 :(得分:1)

可以做这样的事情

protected override void Render(HtmlTextWriter writer)
{
    foreach (GridViewRow row in Results.Rows)
    {
        if (row.RowType == DataControlRowType.DataRow)
        {
            row.Attributes["onmouseover"] = "this.style.cursor='pointer';";
            row.CssClass = "rowHover";
            row.ToolTip = "Click row to view person's history";
            row.Attributes.Add("onclick", this.ClientScript.GetPostBackClientHyperlink(this.Results,"Select$" & r.RowIndex , true));
        }
    }

    base.Render(writer);
}

答案 4 :(得分:0)

//class to store ID (Pri. Key) value of selected row from DataGridView
public class Variables
{
   public static string StudentID;
}                                  

//This is the event call on cell click of the DataGridView
private void dataGridViewDisplay_CellClick(object sender, DataGridViewCellEventArgs e)
{
   Variables.StudentID =this.dataGridViewDisplay.CurrentRow.Cells[0].Value.ToString();
//textBoxName is my form field where I set the value of Name Column from the Selected row from my DataGridView 

   textBoxName.Text = this.dataGridViewDisplay.CurrentRow.Cells[1].Value.ToString();

   dateTimePickerDOB.Value = Convert.ToDateTime(this.dataGridViewDisplay.CurrentRow.Cells[2].Value.ToString());
}

Take a look at My DataGridView

答案 5 :(得分:0)

您可以这样做:也许可以为您提供帮助。

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex>0)
        {
            int rowindex = e.RowIndex;
            DataGridViewRow row= this.dataGridView1.Rows[rowindex];
        }
    }