【C#语言】DataGridView隐藏行列

这篇博客探讨了在C#编程中如何通过设置DataGridView的Visible属性来隐藏表格的行列,以满足特定的显示需求。
该文章已生成可运行项目,

        在实践中,有时需要将表中数据隐藏。

        属性:

        获取或设置一个值,指示该列是否可见。

         public override bool Visible { get; set; }

 

 

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

namespace Test_DataGridView
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            dataGridView1.DataSource = Source();
        }

        //数据表资源
        private DataTable Source()
        {
            DataTable mydt = new DataTable();
            mydt.Columns.Add("姓名");
            mydt.Columns.Add("年龄");
            mydt.Columns.Add("分数");
            String[,] str = new String[,] { { "张三", "21", "90" }, { "李四", "22", "93" }, { "王五", "23", "99" } };

            for (int i = 0; i < 3; i++)
            {
                DataRow dr = mydt.NewRow();
                dr[0] = str[i, 0];
                dr[1] = str[i, 1];
                dr[2] = str[i, 2];
                mydt.Rows.Add(dr);
            }
            return mydt;

        }

        //获取单元格信息
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //获取单元格坐标
            int col = dataGridView1.CurrentCellAddress.X + 1;
            int row = dataGridView1.CurrentCellAddress.Y + 1;

            //获取单元格内容
            String content = dataGridView1.CurrentCell.Value.ToString();

            MessageBox.Show("行:" + row.ToString() + "   列:" + col.ToString() + "      内容:" + content);

        }

        //隐藏年龄
        private void button1_Click(object sender, EventArgs e)
        {
            String bts = button1.Text;
            if (bts == "隐藏年龄")
            {
                dataGridView1.Columns[1].Visible = false;
                bts = "显示年龄";
                button1.Text = bts;
            }
            else
            {
                dataGridView1.Columns[1].Visible = true;
                bts = "隐藏年龄";
                button1.Text = bts;
            }

        }


    }
}



本文章已经生成可运行项目
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值