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

时间:2024-06-01 11:40:08
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) { } } }