如何将数据行从Form1传递到Form2并解决MessageBox字体过小问题
解决WinForm数据传递与MessageBox字体问题
一、实现Form1到Form2的数据传递
你当前的Form2已经定义了Attendance类,但还没利用它来接收和展示数据。我们可以通过修改Form2的构造函数来接收Form1传递的匹配数据,再将数据填充到对应的文本框中。
步骤1:确保Attendance实体类字段匹配
先确认你的Attendance类包含对应数据表的属性(如果还没定义,直接用下面的代码):
public class Attendance { public string EmpNo { get; set; } public string PrizeNo { get; set; } public string TableNo { get; set; } public int Year { get; set; } public string EmpName { get; set; } }
步骤2:修改Form2添加数据接收逻辑
给Form2新增一个带参数的构造函数,用来接收Attendance数据并填充文本框,同时保留原无参构造函数(设计器需要):
public partial class Form2 : Form { private Attendance pass; // 保留原无参构造函数 public Form2() { InitializeComponent(); DisableTextBoxes(); } // 新增带参数的构造函数,接收匹配数据 public Form2(Attendance attendanceData) : this() { pass = attendanceData; // 把数据填充到对应的文本框 txtName.Text = pass.EmpName; txtPrzNo.Text = pass.PrizeNo; txtTableNo.Text = pass.TableNo; txtYear.Text = pass.Year.ToString(); } // 提取禁用文本框的逻辑,让代码更整洁 private void DisableTextBoxes() { txtName.Enabled = false; txtPrzNo.Enabled = false; txtTableNo.Enabled = false; txtYear.Enabled = false; } private void btnOK_Click(object sender, EventArgs e) { this.Close(); } }
步骤3:在Form1中传递匹配数据
找到匹配的数据行后,把数据转换成Attendance对象,再传给Form2的构造函数,同时建议加break避免重复打开多个Form2:
// 匹配到数据时的逻辑 if (year3[i].ToString().Trim().Equals(txtEmployeeID.Text)) { txtStatusInsert.Visible = false; picsuccess.Visible = false; // 将DataRow转换为Attendance对象 Attendance matchedData = new Attendance { EmpNo = dt3.Rows[i]["EmpNo"].ToString(), PrizeNo = dt3.Rows[i]["PrizeNo"].ToString(), TableNo = dt3.Rows[i]["TableNo"].ToString(), Year = Convert.ToInt32(dt3.Rows[i]["Year"]), EmpName = dt3.Rows[i]["EmpName"].ToString() }; // 传递数据并打开Form2 Form2 form2 = new Form2(matchedData); form2.Show(); // 避免匹配到多个重复项时打开多个窗口 break; }
二、解决MessageBox字体过小的问题
默认MessageBox的字体由系统控制,无法直接修改。最灵活的方案是自定义弹窗Form,完全控制字体大小和样式:
步骤1:创建自定义弹窗Form
新建一个Form(比如命名为CustomMessageBox),设置以下属性:
FormBorderStyle设为FixedDialog(固定弹窗样式)StartPosition设为CenterScreen(居中显示)- 添加一个
Label(显示消息文本)和一个Button(关闭弹窗)
代码示例:
public partial class CustomMessageBox : Form { public CustomMessageBox(string message, string title) { InitializeComponent(); this.Text = title; // 设置消息字体大小,这里用Arial 12号,可按需调整 lblMessage.Font = new Font("Arial", 12, FontStyle.Regular); lblMessage.Text = message; } private void btnOK_Click(object sender, EventArgs e) { this.Close(); } }
步骤2:替换原MessageBox调用
把Form1中原来的MessageBox.Show替换为自定义弹窗:
// 原MessageBox代码替换成下面的自定义弹窗 string message = $"The following Employee Table number is {dt3.Rows[i]["TableNo"]} and Number is {dt3.Rows[i]["PrizeNo"]}"; CustomMessageBox msgBox = new CustomMessageBox(message, "Remind"); msgBox.ShowDialog();
这样就能完全控制弹窗的字体大小,完美解决老板的需求!
内容的提问来源于stack exchange,提问作者lim jia liang
相关产品推荐
相关产品推荐

