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

s5a0g9ez  于 2023-03-09  发布在  .NET
关注(0)|答案(7)|浏览(173)

我有一个dataGridView,我需要当用户单击任何单元格时,包含此单元格的整行也被选中。(它已取消多选)我尝试这样获取currentRowIndex

int Index = dataGridView1.CurrentCell.RowIndex;

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

dataGridView1.Select(Index);

你知道我有什么办法吗?

busg9geu

busg9geu1#

您需要将数据网格视图的SelectionMode设置为FullRowMode
注意:在Visual Studio 2013和.NET 4.5中,该属性称为FullRowSelect

2jcobegt

2jcobegt2#

如果希望以编程方式选择行,则应使用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;
}
b09cbbtk

b09cbbtk3#

在DataGridView属性中,设置

  • 多选-〉真
  • 选择模式-〉整行选择

lsmd5eda

lsmd5eda4#

会做出这种事

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

kq4fsx7k5#

//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

oalqel3c

oalqel3c6#

您可以执行以下操作:也许它能帮助你。

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

mnowg1ta7#

只是为了给予另一个可能的答案,因为这些似乎都不适合我的情况,或者需要额外的事件回调,这是不必要的。

foreach (DataGridViewTextBoxCell item in NAMEOFDATAGRIDVIEW.SelectedCells)
        {
            item.OwningRow.Selected = true;
        }

相关问题