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

问题描述 投票:45回答:6

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

 int Index = dataGridView1.CurrentCell.RowIndex;

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

dataGridView1.Select(Index);

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

c# .net winforms datagridview
6个回答
85
投票

你需要将datagridview的SelectionMode设置为FullRowMode

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


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
投票

在DataGridView属性中,设置

  • MultiSelect - > True
  • SelectionMode - > FullRowSelect


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);
}

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


0
投票

你可以这样做:可能它可以帮助你。

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex>0)
        {
            int rowindex = e.RowIndex;
            DataGridViewRow row= this.dataGridView1.Rows[rowindex];
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.