datagridview表格操作和自适应窗体

本文介绍了一种自适应窗体的设计方法,通过记录窗体及其控件的初始位置和大小,实现窗口大小变化时控件的自动调整。适用于包含复杂嵌套控件的窗体,如DataGridView,并确保美观和功能性的保持。

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

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

namespace 自适应窗体
{
    
    class AutoSizeormClass
    {
        //声明结构体,记录窗体和控件的初始位置和大小
        public struct controlRect
        {
            public int Left;
            public int Top;
            public int Width;
            public int Height;
        }

        public List<controlRect> oldCtrl = new List<controlRect>();
        int CtrlNo = 0;
        //创建2个函数,记录窗体和控件的初始位置和大小
        public void ControlInitSize(Control mForm)
        {
            controlRect cR;
            cR.Left = mForm.Left; cR.Top = mForm.Top; cR.Width = mForm.Width; cR.Height = mForm.Height;
            oldCtrl.Add(cR);//第一个为"窗体本身",只加入一次即可
            AddControl(mForm);//窗体内其余控件还可能嵌套控件(比如panel),要单独抽出,因为要递归调用
        }
        private void AddControl(Control ctl)
        {
            foreach (Control c in ctl.Controls)
            {  //**放在这里,是先记录控件的子控件,后记录控件本身
                //if (c.Controls.Count > 0)
                //    AddControl(c);//窗体内其余控件还可能嵌套控件(比如panel),要单独抽出,因为要递归调用
                controlRect objCtrl;
                objCtrl.Left = c.Left; objCtrl.Top = c.Top; objCtrl.Width = c.Width; objCtrl.Height = c.Height;
                oldCtrl.Add(objCtrl);
                //**放在这里,是先记录控件本身,后记录控件的子控件
                if (c.Controls.Count > 0)
                    AddControl(c);//窗体内其余控件还可能嵌套控件(比如panel),要单独抽出,因为要递归调用
            }
        }
        public void controlAutoSize(Control mForm)
        {
            if (CtrlNo == 0)
            { //*如果在窗体的Form1_Load中,记录控件原始的大小和位置,正常没有问题,但要加入皮肤就会出现问题,因为有些控件如dataGridView的的子控件还没有完成,个数少
              //*要在窗体的Form1_SizeChanged中,第一次改变大小时,记录控件原始的大小和位置,这里所有控件的子控件都已经形成
                controlRect cR;
              //  cR.Left = mForm.Left; cR.Top = mForm.Top; cR.Width = mForm.Width; cR.Height = mForm.Height;
                cR.Left = 0; cR.Top = 0; cR.Width = mForm.PreferredSize.Width; cR.Height = mForm.PreferredSize.Height;

                oldCtrl.Add(cR);//第一个为"窗体本身",只加入一次即可
                AddControl(mForm);//窗体内其余控件可能嵌套其它控件(比如panel),故单独抽出以便递归调用
            }
            float wScale = (float)mForm.Width / (float)oldCtrl[0].Width;//新旧窗体之间的比例,与最早的旧窗体
            float hScale = (float)mForm.Height / (float)oldCtrl[0].Height;//.Height;
            CtrlNo = 1;//进入=1,第0个为窗体本身,窗体内的控件,从序号1开始
            AutoScaleControl(mForm, wScale, hScale);//窗体内其余控件还可能嵌套控件(比如panel),要单独抽出,因为要递归调用
        }
        private void AutoScaleControl(Control ctl, float wScale, float hScale)
        {
            int ctrLeft0, ctrTop0, ctrWidth0, ctrHeight0;
            //int ctrlNo = 1;//第1个是窗体自身的 Left,Top,Width,Height,所以窗体控件从ctrlNo=1开始
            foreach (Control c in ctl.Controls)
            { //**放在这里,是先缩放控件的子控件,后缩放控件本身
                //if (c.Controls.Count > 0)
                //   AutoScaleControl(c, wScale, hScale);//窗体内其余控件还可能嵌套控件(比如panel),要单独抽出,因为要递归调用
                ctrLeft0 = oldCtrl[CtrlNo].Left;
                ctrTop0 = oldCtrl[CtrlNo].Top;
                ctrWidth0 = oldCtrl[CtrlNo].Width;
                ctrHeight0 = oldCtrl[CtrlNo].Height;
                //c.Left = (int)((ctrLeft0 - wLeft0) * wScale) + wLeft1;//新旧控件之间的线性比例
                //c.Top = (int)((ctrTop0 - wTop0) * h) + wTop1;
                c.Left = (int)((ctrLeft0) * wScale);//新旧控件之间的线性比例。控件位置只相对于窗体,所以不能加 + wLeft1
                c.Top = (int)((ctrTop0) * hScale);//
                c.Width = (int)(ctrWidth0 * wScale);//只与最初的大小相关,所以不能与现在的宽度相乘 (int)(c.Width * w);
                c.Height = (int)(ctrHeight0 * hScale);//
                CtrlNo++;//累加序号
                //**放在这里,是先缩放控件本身,后缩放控件的子控件
                if (c.Controls.Count > 0)
                    AutoScaleControl(c, wScale, hScale);//窗体内其余控件还可能嵌套控件(比如panel),要单独抽出,因为要递归调用
                
                if (ctl is DataGridView)
                {
                    DataGridView dgv = ctl as DataGridView;
                    Cursor.Current = Cursors.WaitCursor;

                    int widths = 0;
                    for (int i = 0; i < dgv.Columns.Count; i++)
                    {
                        dgv.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);  // 自动调整列宽  
                        widths += dgv.Columns[i].Width;   // 计算调整列后单元列的宽度和                       
                    }
                    if (widths >= ctl.Size.Width)  // 如果调整列的宽度大于设定列宽  
                        dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;  // 调整列的模式 自动  
                    else
                        dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;  // 如果小于 则填充  

                    Cursor.Current = Cursors.Default;
                }
            }
        }
    }
}

 

 

 

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 自适应窗体
{
    public partial class Form1 : Form
    {
        AutoSizeormClass asc = new AutoSizeormClass();

        int RowTotalCount = 0;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            asc.ControlInitSize(this);
            dataGridView1.TopLeftHeaderCell.Value = "序号";
            dataGridView1.AllowUserToAddRows = false;//不显示最下面的新行:
            dataGridView1.AllowUserToResizeColumns = false;// 禁止用户改变DataGridView1的所有列的列宽 
            dataGridView1.AllowUserToResizeRows = false;//禁止用户改变DataGridView1の所有行的行高 
            dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;


            dataGridView1.DefaultCellStyle.SelectionBackColor = Color.LightGray;
            dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Black;

            dataGridView1.TopLeftHeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView1.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
            int index = this.dataGridView1.Rows.Add();
            RowTotalCount++;
            dataGridView1.Rows[index].HeaderCell.Value = RowTotalCount.ToString();
            dataGridView1.Rows[index].MinimumHeight = 25;
            this.dataGridView1.Rows[index].Cells[0].Value = RowTotalCount.ToString();
            this.dataGridView1.Rows[index].Cells[1].Value = "2";
            this.dataGridView1.Rows[index].Cells[2].Value = "监听";
            this.dataGridView1.Rows[index].Cells[1].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            this.dataGridView1.Rows[index].Cells[2].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            this.dataGridView1.Rows[index].Cells[3].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            this.dataGridView1.Rows[index].Cells[4].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            this.dataGridView1.Rows[index].Cells[0].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            asc.controlAutoSize(this);

        }

        private void button1_Click(object sender, EventArgs e)
        {
           
            int index = this.dataGridView1.Rows.Add();
            RowTotalCount++;
            dataGridView1.Rows[index].HeaderCell.Value = RowTotalCount.ToString();
            dataGridView1.Rows[index].MinimumHeight = 25;
            this.dataGridView1.Rows[index].Cells[0].Value = RowTotalCount.ToString();
            this.dataGridView1.Rows[index].Cells[1].Value = "2";
            this.dataGridView1.Rows[index].Cells[2].Value = "监听";

            this.dataGridView1.Rows[index].Cells[1].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            this.dataGridView1.Rows[index].Cells[2].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            this.dataGridView1.Rows[index].Cells[3].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            this.dataGridView1.Rows[index].Cells[4].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            this.dataGridView1.Rows[index].Cells[0].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            RowTotalCount--;
            if (RowTotalCount==0)
            {
                MessageBox.Show("最后一行禁止删除","提示信息");
                return;
            }
            this.dataGridView1.Rows.RemoveAt(RowTotalCount);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            this.dataGridView1.RowHeadersVisible = true;

        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.dataGridView1.RowHeadersVisible = false;
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //int CIndex = e.ColumnIndex;
            //int insertRowIndex = dataGridView1.CurrentCell.RowIndex;
            //if (CIndex == 4)
            //{
            //    dataGridView1.Rows[insertRowIndex].DefaultCellStyle.BackColor = Color.LightGray;
            //    this.dataGridView1.Rows[insertRowIndex].Cells[4].Style.ForeColor = Color.Green;
            //    return;
            //}
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int CIndex = e.ColumnIndex;
            int insertRowIndex = dataGridView1.CurrentCell.RowIndex;
            if (CIndex == 4)
            {
                //dataGridView1.Rows[insertRowIndex].DefaultCellStyle.BackColor = Color.LightGray;
                (sender as DataGridView).ClearSelection();//很重要
                ColorDialog ColorForm = new ColorDialog();
                if (ColorForm.ShowDialog() == DialogResult.OK)
                {
                    Color GetColor = ColorForm.Color;
                    //GetColor就是用户选择的颜色,接下来就可以使用该颜色了
                    this.dataGridView1.Rows[insertRowIndex].Cells[4].Style.BackColor = GetColor;
                }

                return;
            }
  
        }

        private void dataGridView1_CellClick_1(object sender, DataGridViewCellEventArgs e)
        {
            int CIndex = e.ColumnIndex;
            int insertRowIndex = dataGridView1.CurrentCell.RowIndex;
            if (CIndex == -1)
            {
                //dataGridView1.Rows[insertRowIndex].DefaultCellStyle.BackColor = Color.LightGray;

                //(sender as DataGridView).ClearSelection();
                this.dataGridView1.Rows[insertRowIndex].Cells[0].Style.BackColor = Color.LightGray;
                this.dataGridView1.Rows[insertRowIndex].Cells[1].Style.BackColor = Color.LightGray;
                this.dataGridView1.Rows[insertRowIndex].Cells[2].Style.BackColor = Color.LightGray;

                this.dataGridView1.Rows[insertRowIndex].Cells[3].Style.BackColor = Color.LightGray;
              
               // this.dataGridView1.Rows[insertRowIndex].Cells[4].Style.BackColor = Color.Green;

                return;
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值