LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

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

admin
2025年4月22日 21:32 本文热度 30

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 = "";
        }       
    }
}

效果图:


阅读原文:原文链接


该文章在 2025/4/23 10:52:51 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2025 ClickSun All Rights Reserved