当前位置: 首页 > news >正文

C# dataGridView 自动生成几行几列及手动输入整型字符

C# dataGridView生成12号4列的表格

private void Form1_Load(object sender, EventArgs e)
{
    // 清除默认列
    dataGridView1.Columns.Clear();
    
    // 添加4列(首列为序号列)
    dataGridView1.Columns.Add("ColIndex", "序号");
    dataGridView1.Columns.Add("Col2", "列2");
    dataGridView1.Columns.Add("Col3", "列3");
    dataGridView1.Columns.Add("Col4", "列4");

    // 添加12行数据
    for (int i = 0; i < 12; i++)
    {
        int rowIndex = dataGridView1.Rows.Add();
        dataGridView1.Rows[rowIndex].Cells[0]().Value = i + 1; // 首列填充1-12
    }
}

第一行的特殊处理

// 在循环中添加条件判断
if (rowIndex > 0) // 跳过第一行(索引0)
{
    dataGridView1.Rows[rowIndex].Cells[0]().Value = rowIndex; // 从1开始填充
}

自动生成行号(行头显示)

// 在RowPostPaint事件中绘制行号
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    var grid = sender as DataGridView;
    using (SolidBrush brush = new SolidBrush(grid.RowHeadersDefaultCellStyle.ForeColor))
    {
        // 行号位置微调
        e.Graphics.DrawString(
            (e.RowIndex + 1).ToString(),
            grid.DefaultCellStyle.Font,
            brush,
            new PointF(e.RowBounds.X + 20, e.RowBounds.Y + 4)
        );
    }
}

关键配置

禁止自动生成列:dataGridView1.AutoGenerateColumns = false;
禁止选中首行:dataGridView1.ClearSelection();
列宽自适应:

dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

手动输入整型字符

完整代码如下:

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 VMPro2024._08.WinForm
{
    public partial class CalibrationForm : Form
    {
        public CalibrationForm()
        {
            InitializeComponent();
            正极平台_dataGridView.CellValidating += 正极平台_dataGridView_CellValidating;

        }

        private void CalibrationForm_Load(object sender, EventArgs e)
        {
            //设置4列
            正极平台_dataGridView.ColumnCount = 4;
            正极像素_dataGridView.ColumnCount = 4;

            负极平台_dataGridView.ColumnCount = 4;
            负极像素_dataGridView.ColumnCount = 4;

            //添加12行空数据
            for (int i = 0; i < 12; i++)
            {
                int indexRow1 = 正极平台_dataGridView.Rows.Add();
                正极平台_dataGridView.Rows[i].Cells[0].Value = indexRow1 + 1;

                int indexRow2 = 正极像素_dataGridView.Rows.Add();
                正极像素_dataGridView.Rows[i].Cells[0].Value = indexRow2 + 1;

                int indexRow3 = 负极平台_dataGridView.Rows.Add();
                负极平台_dataGridView.Rows[i].Cells[0].Value = indexRow3 + 1;

                int indexRow4 = 负极像素_dataGridView.Rows.Add();
                负极像素_dataGridView.Rows[i].Cells[0].Value = indexRow4 + 1;
            }

            正极平台_dataGridView.RowHeadersWidth = 60;
            正极像素_dataGridView.RowHeadersWidth = 60;

            负极平台_dataGridView.RowHeadersWidth = 60;
            负极像素_dataGridView.RowHeadersWidth = 60;

            //允许直接编辑
            正极平台_dataGridView.EditMode = DataGridViewEditMode.EditOnKeystroke;
            正极像素_dataGridView.EditMode = DataGridViewEditMode.EditOnKeystroke;
            负极平台_dataGridView.EditMode = DataGridViewEditMode.EditOnKeystroke;
            负极像素_dataGridView.EditMode = DataGridViewEditMode.EditOnKeystroke;
            //强制取消第一列的只读属性
            正极平台_dataGridView.Columns[1].ReadOnly = false;
        }

        private void 负极平台_dataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {

        }

        private DataGridViewTextBoxEditingControl cellEdit;//声明编辑控件

        /// <summary>
        /// 通过事件限制输入类型
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 正极平台_dataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (正极平台_dataGridView.CurrentCell.ColumnIndex == 1
                || 正极平台_dataGridView.CurrentCell.ColumnIndex == 2 ||
                正极平台_dataGridView.CurrentCell.ColumnIndex == 3)
            {
                TextBox tb = e.Control as TextBox;
                if (tb != null)
                {
                    tb.KeyPress += new KeyPressEventHandler(Tb_KeyPress);
                }
            }
        }

        private void Tb_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '-' && e.KeyChar != (char)Keys.Back)
            {
                e.Handled = true;// 阻止无效输入 
                MessageBox.Show("仅允许输入整数!");
            }
            else
            {
                e.Handled = false;
                正极平台_dataGridView.Rows[正极平台_dataGridView.CurrentCell.RowIndex].ErrorText = "";
            }

            // 负号只能出现在首位
            if (e.KeyChar == '-' && ((TextBox)sender).SelectionStart != 0)
            {
                e.Handled = true;
            }
        }

        /// <summary>
        /// 在单元格结束编辑时验证输入内容是否为整数:
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 正极平台_dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (正极平台_dataGridView.IsCurrentCellInEditMode)
            {
                if (e.ColumnIndex == 1 || e.ColumnIndex == 2 || e.ColumnIndex == 3)
                {
                    //单元格值为空时触发
                    string input = e.FormattedValue.ToString();
                    if (!string.IsNullOrEmpty(input) && !int.TryParse(e.FormattedValue.ToString(), out _))
                    {
                        e.Cancel = true;
                        MessageBox.Show("输入内容必须为整数!");
                    }
                    else
                    {
                        e.Cancel = false;
                    }
                }
            }
        }

        private void 正极平台_dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (正极平台_dataGridView.EditingControl is TextBox tb)
            {
                tb.KeyPress -= Tb_KeyPress;
            }

            //清除错误提示
            正极平台_dataGridView.Rows[e.RowIndex].ErrorText = "";
        }       
    }
}

效果图:

1

相关文章:

  • nginx https配置
  • 【算法】并查集基础讲解
  • 每日c/c++题 备战蓝桥杯(全排列问题)
  • DEEPSEEK创业项目推荐:
  • pytorch中不同的mask方法:masked_fill, masked_select, masked_scatter
  • MySQL 当中的锁
  • 网络运维学习笔记(DeepSeek优化版)026 OSPF vlink(Virtual Link,虚链路)配置详解
  • 深度学习 Deep Learning 第13章 线性因子模型
  • PyQt6实例_批量下载pdf工具_批量pdf网址获取
  • 3.30学习总结 Java包装类+高精度算法+查找算法
  • 开发环境解决Secure Cookie导致302重定向
  • VUE实现框架搭建(纯手写)
  • 【Python爬虫神器】requests库常用操作详解 ,附实战案例
  • RocketMQ - 从消息可靠传输谈高可用
  • Cookie可以存哪些指?
  • 一区严选!挑战5天一篇脂质体组学 DAY1-5
  • Flink介绍——实时计算核心论文之S4论文详解
  • RS232转Profinet网关扫码器在西门子1200plc快速配置
  • MySQL中的CREATE TABLE LIKE和CREATE TABLE SELECT
  • 关于为什么使用redis锁,不使用zk锁的原因
  • 武汉手机网站建设公司哪家好/国内最新的新闻
  • 温州做网站哪家公司好/百度一下官网
  • 网站商城怎么做app/百度精准搜索
  • 网站在线布局/seo优化的主要内容
  • 西宁高端网站建设/爱站网长尾词挖掘
  • 做网站怎么添加背景图片/郑州网站运营