C#读写应用程序配置文件App.exe.config,使用Panel增加滚动条

25 篇文章 1 订阅

上一篇我们使用GroupBox读写应用程序配置文件App.exe.config。

C#读写应用程序配置文件App.exe.config,并在界面上显示_斯内科的博客-CSDN博客

发现数据项多时,无法全部显示配置内容,我们使用Panel可以设置滚动条。在原来的项目中增加窗体FormSaveXmlConfigUsePanel,并使用Panel代替GroupBox控件。

窗体 FormSaveXmlConfigUsePanel主要程序如下:

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

namespace SaveDefaultXmlConfigDemo
{
    public partial class FormSaveXmlConfigUsePanel : Form
    {
        public FormSaveXmlConfigUsePanel()
        {
            InitializeComponent();
            //考虑到数据项配置过多时,使用Groupbox无法显示多余的控件 这里使用Panel
            panel1.BorderStyle = BorderStyle.FixedSingle;
            panel1.AutoScroll = true;
            panel2.BorderStyle = BorderStyle.FixedSingle;
            panel2.AutoScroll = true;
        }

        private void FormSaveXmlConfigUsePanel_Load(object sender, EventArgs e)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                txtFilePath.Text = config.FilePath;
                //读取配置AppSetting节点,
                KeyValueConfigurationCollection keyValueCollection = config.AppSettings.Settings;
                AddAppSettingConfig(keyValueCollection);
                //读取连接字符串ConnectionStrings节点
                ConnectionStringSettingsCollection connectionCollection = config.ConnectionStrings.ConnectionStrings;
                AddConnectionStringConfig(connectionCollection);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载应用程序配置文件出错:{ex.Message}", "出错");
            }
        }

        /// <summary>
        /// 获取配置节点AppSettings的所有内容,将其添加到元组列表中
        /// </summary>
        /// <returns></returns>
        private List<Tuple<string, string>> GetAppSettingList()
        {
            List<Tuple<string, string>> tupleAppSettings = new List<Tuple<string, string>>();
            for (int i = 0; i < panel1.Controls.Count; i++)
            {
                if (panel1.Controls[i] is Label lbl)
                {
                    Control[] controls = panel1.Controls.Find($"txtValue{lbl.Tag}", true);
                    if (controls == null || controls.Length == 0)
                    {
                        throw new Exception($"没有找到【{lbl.Text}】对应的文本框控件【txtValue{lbl.Tag}】");
                    }
                    tupleAppSettings.Add(Tuple.Create(lbl.Text, controls[0].Text));
                }
            }
            return tupleAppSettings;
        }

        /// <summary>
        /// 获取配置节点onnectionStrings的所有内容,将其添加到元组列表中
        /// </summary>
        /// <returns></returns>
        private List<Tuple<string, string, string>> GetConnectionStringList()
        {
            List<Tuple<string, string, string>> tupleConnectionStrings = new List<Tuple<string, string, string>>();
            for (int i = 0; i < panel2.Controls.Count; i++)
            {
                if (panel2.Controls[i] is Label lbl && lbl.Name.StartsWith("lblName"))
                {
                    Control[] controlProviderNames = panel2.Controls.Find($"txtProviderName{lbl.Tag}", true);
                    if (controlProviderNames == null || controlProviderNames.Length == 0)
                    {
                        throw new Exception($"没有找到【{lbl.Text}】对应的文本框控件【txtProviderName{lbl.Tag}】");
                    }
                    Control[] controlConnectionStrings = panel2.Controls.Find($"txtConnectionString{lbl.Tag}", true);
                    if (controlConnectionStrings == null || controlConnectionStrings.Length == 0)
                    {
                        throw new Exception($"没有找到【{lbl.Text}】对应的文本框控件【txtConnectionString{lbl.Tag}】");
                    }
                    tupleConnectionStrings.Add(Tuple.Create(lbl.Text, controlProviderNames[0].Text, controlConnectionStrings[0].Text));
                }
            }
            return tupleConnectionStrings;
        }

        private void btnSaveConfig_Click(object sender, EventArgs e)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                List<Tuple<string, string>> tupleAppSettings = GetAppSettingList();
                for (int i = 0; i < tupleAppSettings.Count; i++)
                {
                    //修改配置节点AppSettings的内容
                    config.AppSettings.Settings[tupleAppSettings[i].Item1].Value = tupleAppSettings[i].Item2;
                }
                List<Tuple<string, string, string>> tupleConnectionStrings = GetConnectionStringList();
                for (int i = 0; i < tupleConnectionStrings.Count; i++)
                {
                    //修改配置节点ConnectionStrings的内容
                    config.ConnectionStrings.ConnectionStrings[tupleConnectionStrings[i].Item1].ProviderName = tupleConnectionStrings[i].Item2;
                    config.ConnectionStrings.ConnectionStrings[tupleConnectionStrings[i].Item1].ConnectionString = tupleConnectionStrings[i].Item3;
                }
                //保存配置文件
                config.Save();
                MessageBox.Show($"保存应用程序配置文件成功,开始重新加载应用程序配置.", "提示");

                //刷新配置
                FormSaveXmlConfigUsePanel_Load(null, e);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存应用程序配置文件出错:{ex.Message}", "出错");
            }
        }

        /// <summary>
        /// 读取所有的AppSetting节点,将其绑定到panel1中
        /// 只考虑在配置文件中【IsPresent为true】的节点
        /// </summary>
        /// <param name="keyValueCollection"></param>
        private void AddAppSettingConfig(KeyValueConfigurationCollection keyValueCollection)
        {
            panel1.Controls.Clear();
            int index = 0;
            foreach (KeyValueConfigurationElement keyValueElement in keyValueCollection)
            {
                ElementInformation elemInfo = keyValueElement.ElementInformation;
                if (!elemInfo.IsPresent)
                {
                    //考虑到部分配置不是在App.exe.config配置文件中,此时不做处理
                    continue;
                }
                Label label = new Label();
                label.AutoSize = true;
                label.Location = new System.Drawing.Point(20, 20 + index * 30);
                label.Name = $"lblKey{index + 1}";
                label.Text = keyValueElement.Key;
                label.Tag = index + 1;

                TextBox textBox = new TextBox();
                textBox.Location = new System.Drawing.Point(120, 20 + index * 30);
                textBox.Name = $"txtValue{index + 1}";
                textBox.Size = new System.Drawing.Size(300, 21);
                textBox.Text = keyValueElement.Value;

                panel1.Controls.AddRange(new Control[] { label, textBox });
                index++;
            }
        }

        /// <summary>
        /// 读取所有的ConnectionString节点,将其绑定到panel2中
        /// 只考虑在配置文件中【IsPresent为true】的节点
        /// </summary>
        /// <param name="connectionCollection"></param>
        private void AddConnectionStringConfig(ConnectionStringSettingsCollection connectionCollection)
        {
            panel2.Controls.Clear();
            int index = 0;
            foreach (ConnectionStringSettings connectElement in connectionCollection)
            {
                ElementInformation elemInfo = connectElement.ElementInformation;
                if (!elemInfo.IsPresent)
                {
                    //考虑到连接字符串有系统默认配置,不在配置文件中【IsPresent=false】,因此过滤掉,如下面两个
                    //LocalSqlServer、LocalMySqlServer
                    continue;
                }
                Label label = new Label();
                label.AutoSize = true;
                label.Location = new System.Drawing.Point(20, 20 + index * 30);
                label.Name = $"lblName{index + 1}";
                label.Text = connectElement.Name;
                label.Tag = index + 1;

                TextBox textBox = new TextBox();
                textBox.Location = new System.Drawing.Point(120, 20 + index * 30);
                textBox.Name = $"txtConnectionString{index + 1}";
                textBox.Size = new System.Drawing.Size(360, 21);
                textBox.Text = connectElement.ConnectionString;

                Label lblFixed = new Label();
                lblFixed.AutoSize = true;
                lblFixed.Location = new System.Drawing.Point(500, 20 + index * 30);
                lblFixed.Name = $"lblFixed{index + 1}";
                lblFixed.Text = "提供程序名称";

                TextBox txtProviderName = new TextBox();
                txtProviderName.Location = new System.Drawing.Point(580, 20 + index * 30);
                txtProviderName.Name = $"txtProviderName{index + 1}";
                txtProviderName.Size = new System.Drawing.Size(140, 21);
                txtProviderName.Text = connectElement.ProviderName;

                panel2.Controls.AddRange(new Control[] { label, textBox, lblFixed, txtProviderName });
                index++;
            }
        }
    }
}

程序运行如图:

【此时,我们发现已经会有滚动条出现】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

斯内科

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值