【问题标题】:How do I click on a Cell of a DataGridView programmatically?如何以编程方式单击 DataGridView 的单元格?
【发布时间】:2015-06-02 09:57:09
【问题描述】:

我有一个 datagridview_cellclick 方法,当我单击单元格时,它会将 dataGridView 中的所有内容放入变量中。 所以没有问题。

但我想在启动程序时自动单击同一个 DataGridView 的第一个单元格。不是自己用鼠标点击,而是像程序在创建带有 dataGridView 的表单时点击第一个单元格本身一样。

这个点击会调用上面的方法,所以即使我没有点击第一个单元格,我也会设置变量。 我不确定这是否清楚。 我怎样才能做到这一点?

【问题讨论】:

    标签: c# datagridview


    【解决方案1】:

    假设使用 Windows 窗体

    Pretty Naive 方法是调用带有所需参数集的函数:

    dataGridView1_CellClick(this.dataGridView1, new DataGridViewCellEventArgs(0, 0));
    

    虽然我不确定您在 CellClickEvent 中正在做什么,因为这可能会改变您想要访问单元格的方式(或对该单元格执行某些操作)。为了完整起见,我做了什么:

      public Form1()
        {
            InitializeComponent();
            dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[0];
            dataGridView1_CellClick(this.dataGridView1, new DataGridViewCellEventArgs(0, 0));
        }
    
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            MessageBox.Show("" + e.ColumnIndex + e.RowIndex);
        }
    

    【讨论】:

      【解决方案2】:

      datagridview_cellclick 中的逻辑重构为单独的函数,然后使用DataGridView.CurrentCell 设置单元格焦点。你可以设置在Form_Load

      if (DataGridView.Rows.Count >= 0)
      {
          // Set the first cell
          DataGridView.CurrentCell = DataGridView.Rows(0).Cells(0);
          // Cell logic
          UserSelectedCell(DataGridView.CurrentCell);
      }
      

      【讨论】:

        猜你喜欢
        • 2020-07-23
        • 1970-01-01
        • 2015-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多