C#根据数据量自动排版标签的样例

在这里插入图片描述
这是一个C#根据数据量自动排版标签的样例

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using HslCommunication.Profinet;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private CancellationTokenSource _cancellationTokenSource;
        private Dictionary<string, string> fieldMappings;

        public Form1()
        {
            InitializeComponent();
            InitializeFieldMappings();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void InitializeFieldMappings()
        {
            fieldMappings = new Dictionary<string, string>
            {
                { "pltid", "平台ID" },
                { "basketcode", "篮子编码" },
                { "code", "编码" },
                { "productCode", "产品编码" },
                { "productName", "产品名称" },
                { "customerCode", "客户编码" },
                { "customerName", "客户名称" },
                { "workordernumber", "工单编号" },
                { "way", "方式" },
                { "matnr", "物料编码" },
                { "specs", "规格" },
                { "dimension", "尺寸" },
                { "equipmentnum", "设备编号" },
                { "djBusCode", "业务代码" },
                { "degEmCode", "异常代码" },
                { "fqty", "数量" },
                { "dinsert", "插入时间" },
                { "lkstatus", "锁定状态" },
                { "viewstatus", "查看状态" },
                { "mst", "主状态" },
                { "change_time", "变更时间" },
                { "lgid", "lg的编号" },
                { "lgmsg", "lg的信息" },
                { "lgtime", "lg的时间" }
            };
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            _cancellationTokenSource = new CancellationTokenSource();
            string connectionString = "Server=ip;Database=root;User Id=1;Password=1;";
            string query = "SELECT * FROM [1].[1] where viewstatus=1";

            bool isConnected = await Task.Run(() => TestDatabaseConnection(connectionString));
            if (isConnected)
            {
                textBox2.BackColor = Color.Green;
                label1.Text = "已连接";
                await Task.Run(() => MonitorDatabase(connectionString, query, _cancellationTokenSource.Token));
            }
            else
            {
                textBox2.BackColor = Color.Red;
                label1.Text = "连接失败";
            }
        }

        private bool TestDatabaseConnection(string connectionString)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        private void MonitorDatabase(string connectionString, string query, CancellationToken token)
        {
            DateTime lastCheck = DateTime.Now;

            while (!token.IsCancellationRequested)
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    SqlCommand command = new SqlCommand(query, connection);
                    command.Parameters.AddWithValue("@lastCheck", lastCheck);

                    try
                    {
                        connection.Open();
                        SqlDataReader reader = command.ExecuteReader();

                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                StringBuilder result = new StringBuilder();
                                for (int i = 0; i < reader.FieldCount; i++)
                                {
                                    string fieldName = reader.GetName(i);
                                    string fieldValue = reader[i].ToString();
                                    if (fieldMappings.ContainsKey(fieldName))
                                    {
                                        result.AppendLine($"{fieldMappings[fieldName]}: {fieldValue}");
                                    }
                                    else
                                    {
                                        result.AppendLine($"{fieldName}: {fieldValue}");
                                    }
                                }
                                UpdateUIWithResult(result.ToString(), reader);
                            }

                            lastCheck = DateTime.Now;
                        }
                        reader.Close();
                    }
                    catch (Exception ex)
                    {
                        UpdateUIWithResult("Error: " + ex.Message, null);
                    }
                }

                Thread.Sleep(1000); // 1 second interval
            }
        }

        private void UpdateUIWithResult(string text, SqlDataReader reader)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => CreateLabelsForData(reader)));
            }
            else
            {
                CreateLabelsForData(reader);
            }
        }

        private void CreateLabelsForData(SqlDataReader reader)
        {
            flowLayoutPanel1.Controls.Clear(); // 清空之前的控件
            int yOffset = 0; // 纵向偏移量

            for (int i = 0; i < reader.FieldCount; i++)
            {
                string fieldName = reader.GetName(i);
                string fieldValue = reader[i].ToString();

                // 创建标题标签
                Label titleLabel = new Label
                {
                    AutoSize = false,
                    Width = 200,
                    Height = 40,
                    Location = new Point(0, yOffset),
                    ForeColor = Color.Red,
                    BackColor = Color.Black,
                    Padding = new Padding(5),
                    Font = new Font("Arial", 18, FontStyle.Bold),
                    Text = fieldMappings.ContainsKey(fieldName) ? fieldMappings[fieldName] : fieldName
                };

                // 创建内容标签
                Label valueLabel = new Label
                {
                    AutoSize = false,
                    Width = 200,
                    Height = 40,
                    Location = new Point(210, yOffset),
                    ForeColor = Color.Green,
                    BackColor = Color.Black,
                    Padding = new Padding(5),
                    Font = new Font("Arial", 18, FontStyle.Regular),
                    Text = fieldValue
                };

                // 将标题和内容标签添加到Panel
                flowLayoutPanel1.Controls.Add(titleLabel);
                flowLayoutPanel1.Controls.Add(valueLabel);

                yOffset += 50; // 更新纵向偏移量
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            _cancellationTokenSource?.Cancel();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void button5_Click(object sender, EventArgs e)
        {
            _cancellationTokenSource?.Cancel();
            textBox2.BackColor = Color.WhiteSmoke; // 或者其他颜色表示断开连接
            label1.Text = "未连接";
        }
        private void flowLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {
            
        }
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

谁的BUG最难改

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

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

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

打赏作者

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

抵扣说明:

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

余额充值