如何将二维UInt16数组从父窗体传递到子窗体的控件中?
解决方案
1. 优化子窗体(ChildTest)代码
调整子窗体逻辑,确保标签按TabIndex顺序排列,并提供公共方法接收数据更新标签,避免直接暴露控件列表:
public partial class ChildTest : Form { // 私有列表存储按TabIndex排序的标签,保证数据对应顺序 private List<Label> _sortedLabels = new List<Label>(); public ChildTest() { InitializeComponent(); } private void ChildTest_Load(object sender, EventArgs e) { // 筛选TabIndex 0-27的标签,并按TabIndex升序排序 _sortedLabels = tableLayoutPanel1.Controls.OfType<Label>() .Where(lbl => lbl.TabIndex >= 0 && lbl.TabIndex < 28) .OrderBy(lbl => lbl.TabIndex) .ToList(); // 初始化默认文本 foreach (var lbl in _sortedLabels) { lbl.Text = "001x"; } } // 公共方法:接收一行数据并更新对应标签 public void RefreshLabels(UInt16[] rowData) { if (rowData == null || rowData.Length != 28) { throw new ArgumentException("传入数据长度必须为28"); } for (int i = 0; i < _sortedLabels.Count; i++) { // 按需求格式化数字,示例为4位补零格式 _sortedLabels[i].Text = rowData[i].ToString("D4"); } } }
2. 父窗体数据传递逻辑
根据需求选择两种传递方式:
方式1:创建子窗体时直接传递对应行数据
// 初始化数组并填充数据 UInt16[,] _array = new UInt16[4, 28]; // 此处省略数组数据填充逻辑 // 创建Child1并传递第0行数据 ChildTest child1 = new ChildTest(); UInt16[] row0 = Enumerable.Range(0, 28).Select(col => _array[0, col]).ToArray(); child1.RefreshLabels(row0); child1.Text = "Child1"; child1.Show(); // 创建Child2并传递第1行数据 ChildTest child2 = new ChildTest(); UInt16[] row1 = Enumerable.Range(0, 28).Select(col => _array[1, col]).ToArray(); child2.RefreshLabels(row1); child2.Text = "Child2"; child2.Show(); // 创建Child3并传递第2行数据 ChildTest child3 = new ChildTest(); UInt16[] row2 = Enumerable.Range(0, 28).Select(col => _array[2, col]).ToArray(); child3.RefreshLabels(row2); child3.Text = "Child3"; child3.Show(); // 创建Child4并传递第3行数据 ChildTest child4 = new ChildTest(); UInt16[] row3 = Enumerable.Range(0, 28).Select(col => _array[3, col]).ToArray(); child4.RefreshLabels(row3); child4.Text = "Child4"; child4.Show();
方式2:动态更新已打开的子窗体
如果数组数据后续会更新,需要刷新已打开的子窗体,可使用以下逻辑:
// 遍历所有打开的ChildTest窗体,匹配对应行更新 foreach (Form form in Application.OpenForms) { if (form is ChildTest childForm) { UInt16[] targetRow = null; switch (childForm.Text) { case "Child1": targetRow = Enumerable.Range(0, 28).Select(col => _array[0, col]).ToArray(); break; case "Child2": targetRow = Enumerable.Range(0, 28).Select(col => _array[1, col]).ToArray(); break; case "Child3": targetRow = Enumerable.Range(0, 28).Select(col => _array[2, col]).ToArray(); break; case "Child4": targetRow = Enumerable.Range(0, 28).Select(col => _array[3, col]).ToArray(); break; } targetRow?.Let(row => childForm.RefreshLabels(row)); } }
关键注意点
- 标签排序:必须通过
OrderBy(lbl => lbl.TabIndex)保证标签顺序与数组列索引对应,避免数据错位。 - 封装性:通过公共方法传递数据,不直接操作子窗体控件,符合面向对象设计原则。
- 格式自定义:可根据需求修改
ToString的格式参数,比如去掉补零直接用rowData[i].ToString()。
内容的提问来源于stack exchange,提问作者EverActive
相关产品推荐
相关产品推荐

