WinForms中,`DataGridView`的`CellContentClick`事件和 `CellClick`事件

在WinForms中,`DataGridView`的`CellContentClick`事件只有在点击单元格内容时才会触发。如果你希望在点击单元格的任何部分(包括空白区域)时都能显示所在行的`plc.Name`,可以使用`CellClick`事件。

以下是修改后的代码:

```csharp
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace Winform和Wpf的本质不同
{
    public partial class Form1 : Form
    {
        private List<PlcModel> plcModels = new List<PlcModel>();

        public Form1()
        {
            InitializeComponent();
            InitializeDataGridView();
        }

        private void InitializeDataGridView()
        {
            for (int i = 0; i < 20; i++)
            {
                plcModels.Add(new PlcModel
                {
                    Id = i + 1,
                    Name = $"名字{i}",
                    PlcValue = $"{i}",
                    Description = $"描述{i}"
                });
            }

            this.dataGridView1.ReadOnly = true;
            this.dataGridView1.DataSource = plcModels;
            this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            this.dataGridView1.CellClick += dataGridView1_CellClick; // 使用CellClick事件
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.RowIndex < dataGridView1.Rows.Count)
            {
                DataGridViewRow selectedRow = dataGridView1.Rows[e.RowIndex];
                var o = selectedRow.DataBoundItem;
                if (o is PlcModel plc)
                {
                    this.label1.Text = plc.Name;
                }
            }
        }
    }

    public class PlcModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string PlcValue { get; set; }
        public string Description { get; set; }
    }
}
```

在这个修改后的代码中,我们将`dataGridView1_CellContentClick`事件替换为`dataGridView1_CellClick`事件,并在`InitializeDataGridView`方法中添加了对`CellClick`事件的订阅。这样,无论点击单元格的哪个部分,都会触发`dataGridView1_CellClick`事件,从而显示所在行的`plc.Name`。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值