【问题标题】:DataGridView selecting a specific row and retrieving its valuesDataGridView 选择特定行并检索其值
【发布时间】:2012-11-20 00:20:57
【问题描述】:

我应该在DataGridView 中使用什么事件,因为DataGridView 充满了数据,当我自动单击一行数据时,我想检索所有数据。我尝试使用事件CellContentClick,但它仅在我选择列数据而不是行时才会激活

private void dtSearch_CellContentClick(object sender, DataGridViewCellEventArgs e)
{

}

【问题讨论】:

    标签: c# datagridview


    【解决方案1】:

    我已经使用了以下效果。我为DataGridView 处理MouseDown 事件,并将整行设置为突出显示,以便很明显它已被选中(当然,除非您已经选择了整行)。

        private void dtSearch_MouseDown(object sender, MouseEventArgs e)
        {
            // Get the cell that was clicked from the location of the mouse pointer
    
            DataGridView.HitTestInfo htiSelectedCell = dtSearch.HitTest(e.X, e.Y);
    
            if (e.Button == MouseButtons.Left)
            {
                // Make sure that a cell was clicked, and not the column or row headers
                // or the empty area outside the cells. If it is a cell,
                // then select the entire row, set the current cell (to move the arrow to
                // the current row)
    
                //if (htiSelectedCell.Type == DataGridViewHitTestType.Cell)
                if (htiSelectedCell.Type == DataGridViewHitTestType.RowHeader)
                {
                    // do stuff here
                }
            }
        }
    

    【讨论】:

    • 我没有测试过这个,但我认为你可以测试htiSelectedCell.Type == DataGridViewHitTestType.RowHeader,而不是DataGridViewHitTestType.Cell
    • 一个错误。它说。 "索引超出范围。必须为非负数且小于集合的大小。参数名称:索引"
    • 由于您似乎只对通过单击行标题进行选择感兴趣,因此我更改了答案以反映这一点。但是我想说@Colin Pear 可能是更好的,因为我已经删除了基于单击的单元格突出显示整行的代码。
    • @SidHolland 在我的情况下,DataGridView 应该只显示一列,即 StudentName。但是当我在 DataGridView 上选择记录时,我应该使用其他输出控件来显示所有详细信息。像名称、RollNo、Class、Address 等。但在数据库表中包含所有详细信息。帮帮我,我怎样才能得到这个?
    • @Sanjeev4evr 我建议你开始一个新的问题帖子,提供更多细节。仅通过评论,我无法轻松理解您遇到的问题。此外,还会有更多人可以帮助您。
    【解决方案2】:

    RowHeaderMouseClick 怎么样。

    【讨论】:

      【解决方案3】:

      尝试使用 CellClick 事件,并遍历列以检索您想要的行值:

              private void Form1_Load(object sender, EventArgs e)
          {
              this.dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick);
          }
      
          public void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
          {
              List<object> values = new List<object>();
      
              int cols = this.dataGridView1.Columns.Count;
      
              for (int col = 0; col < cols; col++)
              {               
      
                  values.Add(this.dataGridView1[col, e.RowIndex].Value);
              }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-12
        • 1970-01-01
        • 2017-08-11
        • 1970-01-01
        • 2021-12-11
        • 1970-01-01
        相关资源
        最近更新 更多