15.3获取DataGridView的当前单元格的索引和内容

本文介绍了一个使用C#实现的Windows Forms应用程序案例,演示了如何在DataGridView控件中加载数据,并通过不同方式获取单元格被点击时的位置信息及内容。代码展示了四种获取行列索引的方法以及两种获取单元格内容的方法。

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

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _15._3DataGridView单元格
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: 这行代码将数据加载到表“csharpzxwDataSet.mytable001”中。您可以根据需要移动或删除它。
            this.mytable001TableAdapter.Fill(this.csharpzxwDataSet.mytable001);

        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //获取行列索引
            //第一种方式
            //int row = e.RowIndex + 1;
            //int col = e.ColumnIndex + 1;

            //第二种方式
            //int row = dataGridView1.CurrentCell.RowIndex + 1;
            //int col = dataGridView1.CurrentCell.ColumnIndex + 1;

            //第三种方式
            int col = dataGridView1.CurrentCellAddress.X+1;
            //int row = dataGridView1.CurrentCellAddress.Y+1;

            //第四种方式行的引用
            int row = dataGridView1.CurrentRow.Index+1;

            //获取单元格的内容
            //1种方法
            //string cell = dataGridView1.Rows[row-1].Cells[col-1].Value.ToString();
            //2种方法
            string cell = dataGridView1.CurrentCell.Value.ToString();



            MessageBox.Show("您点击的是:第"+row.ToString()+"行,第"+col.ToString()+"列,内容为:"+cell);
        }
    }
}

 

转载于:https://www.cnblogs.com/zqyo2000z/p/5365024.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值