当前位置:   article > 正文

C#--DataGridView(干货版)_c# datagridview

c# datagridview

一、添加行列并获取信息

界面如下:

在这里插入图片描述
代码如下:

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 DataGridView
{
    public partial class Form1 : Form
    {
        int count = 0;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //根据Header和所有单元格的内容自动调整行的高度
            dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;  
            //添加三列
            for (int i = 0; i < 3; i++)
            {
                dataGridView1.Columns.Add(new DataGridViewTextBoxColumn());
                dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;  //设置所有列自适应宽度
            }
            //三列的标题
            dataGridView1.Columns[0].HeaderText = "序号";
            dataGridView1.Columns[1].HeaderText = "日期";
            dataGridView1.Columns[2].HeaderText = "说明";
            //设置对齐方式和字体
            dataGridView1.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView1.Font = new Font("宋体", 11);
        }
        //添加行
        private void button1_Click(object sender, EventArgs e)
        {
            int index = this.dataGridView1.Rows.Add();
            this.dataGridView1.Rows[index].Cells[0].Value = count++;
            this.dataGridView1.Rows[index].Cells[1].Value = "2";
            this.dataGridView1.Rows[index].Cells[2].Value = "监听";
        }
        //获取信息
        private void button2_Click(object sender, EventArgs e)
        {
            //获取当前活动单元格内容
            Console.WriteLine("当前活动单元格内容:" + dataGridView1.CurrentCell.Value);  
             //取得当前单元格的列Index
            Console.WriteLine("当前单元格的列Index:" + dataGridView1.CurrentCell.ColumnIndex); 
            //取得当前单元格的行Index
            Console.WriteLine("取得当前单元格的行Index:" + dataGridView1.CurrentCell.RowIndex);   
            // 设定 (1, 1) 为当前单元格 
            dataGridView1.CurrentCell = dataGridView1[1, 1];   
        }
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61

测试:
点击添加:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/419039
推荐阅读
  

闽ICP备14008679号