55

我有一个dataGridView并且我需要当用户单击任何单元格时,包含该单元格的整行也会被选中。(它已禁用多选)我试着得到currentRowIndex这样的

 int Index = dataGridView1.CurrentCell.RowIndex;

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

dataGridView1.Select(Index);

你知道我可以做到这一点的方法吗?

4

6 回答 6

108

您需要将 datagridview 设置SelectionModeFullRowMode.

注意:在带有 .NET 4.5 的 Visual Studio 2013 中,该属性称为FullRowSelect.

于 2012-12-02T19:11:14.877 回答
9

如果您希望以编程方式选择行,您将使用 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;
}
于 2012-12-03T10:53:33.973 回答
5

在 DataGridView 属性中,设置

  • 多选 -> 真
  • SelectionMode -> FullRowSelect

于 2017-11-09T20:21:26.993 回答
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);
}
于 2016-10-11T13:15:03.253 回答
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());
}

看看我的 DataGridView

于 2018-08-16T14:30:09.357 回答
0

你可以这样做:也许它可以帮助你。

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex>0)
        {
            int rowindex = e.RowIndex;
            DataGridViewRow row= this.dataGridView1.Rows[rowindex];
        }
    }
于 2018-09-06T10:55:50.783 回答