触发DataGridView的CellClick事件

本文介绍了一个使用C#实现的简单Windows Forms应用程序,该程序利用DataGridView控件显示了一个包含ID、姓名和年龄三列的数据表格。文章详细解释了如何在程序启动时填充数据,并实现了DataGridView的单元格点击事件,用于显示被点击单元格的行列位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Text;  
  7. using System.Windows.Forms;  
  8.   
  9.   
  10. namespace WindowsFormsApplication2  
  11. {  
  12.     public partial class Form1 : Form  
  13.     {  
  14.         public Form1()  
  15.         {  
  16.             InitializeComponent();  
  17.         }  
  18.   
  19.   
  20.         private void Form1_Load(object sender, EventArgs e)  
  21.         {  
  22.             DataTable dt = new DataTable();  
  23.             dt.Columns.Add("ID");  
  24.             dt.Columns.Add("Name");  
  25.             dt.Columns.Add("Age");  
  26.             for (int i = 0; i < 5; i++)  
  27.             {  
  28.                 dt.Rows.Add();  
  29.                 dt.Rows[i][0] = i;  
  30.                 dt.Rows[i][1] = i.ToString() + "Name";  
  31.                 dt.Rows[i][2] = (i + 1) * 5;  
  32.             }  
  33.   
  34.   
  35.             dataGridView1.DataSource = dt;  
  36.         }  
  37.   
  38.   
  39.         //第一个参数是第几列的意思,第二个参数是第几行的意思。    
  40.         //所有的参数是以0开始的。   
  41.         private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)  
  42.         {  
  43.             MessageBox.Show(e.RowIndex.ToString() + ":" + e.ColumnIndex.ToString());  
  44.         }  
  45.   
  46.   
  47.         private void button1_Click(object sender, EventArgs e)  
  48.         {  
  49.             //dataGridView1_CellClick(dataGridView1, new DataGridViewCellEventArgs(1, 2));  
  50.             dataGridView1_CellClick(dataGridView1, new DataGridViewCellEventArgs(dataGridView1.SelectedCells[0].ColumnIndex, dataGridView1.SelectedCells[0].RowIndex));  
  51.         }  
  52.     }  
  53. }  

转载于:https://www.cnblogs.com/YuanDong1314/p/9189767.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值