c# - 有没有办法访问和更改以编程方式添加到面板的自定义控件中的值?
问题描述
在以编程方式将其添加到表格后,如何更改自定义控件中的复选框“已选中”值?
我有一个自定义控件,它有一个文本框和一个复选框。(我没有足够的声誉来发布图片,但这是一个镜头) https://imgur.com/a/yyXG7p8
它有一个复选框和一个文本框。
该类中有一个公共方法,允许将复选框设置为 true 或 false:
public void setCheckBox(bool set)
{
checkBox1.Checked = set;
}
在另一个类,主类中,我有一个循环,将这些自定义控件添加到面板中:
private void DrawInputBits()
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 32; j++)
{
currentTag = tagsFile[tagIndex];
tagIndex++;
CustomControl.BitsControl newBits = new CustomControl.BitsControl(i, j, currentTag, false);
InputBitsTable.Controls.Add(newBits);
}
}
}
如果您无法分辨,每个复选框都包含 4 个数字的 32 位数字中的一个位的值(因此嵌套循环 0-31,4 次),重点是显示或控制这些值。您可以忽略有关标签的代码。所做的只是从文件中读取文本并用读取的文本填充文本框。
当代码执行时,如果一个位的状态改变,复选框也应该改变状态。下面的循环将被修改为遍历一个整数数组(4 个整数),并在读取每个位的状态后更新每个复选框。目前,循环只是设置为将所有位更改为“真”。这最终不是我想要的,但重点是,我什至无法引用面板中的自定义控件来更改复选框。我认为以下方法会起作用,但我没有尝试过。
private void UpdateInputsScreen(int[] inputDINTS)
{
for(int i = 0; i < InputBitsTable.Controls.Count; i++)
{
for(int j = 0; j < 32; j++)
{
InputBitsTable.Controls[i].setCheckBox(true);//this line gives an error.
}
}
}
这是自定义控件的类。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace CustomControl
{
public partial class BitsControl: UserControl
{
int bit = 0;
int dint = 0;
string tag = "";
BitsControl(int dint, int bit, string tag, bool isEnabled)
{
InitializeComponent();
this.dint = dint;
this.bit = bit;
this.tag = makeTag(tag, dint, bit);
this.textBox1.Text = this.tag;
checkBox1.Enabled = isEnabled;
}
private string makeTag(string tag, int dint, int bit)
{
string newTag = tag + ":[" + dint + "]." + bit;
return newTag;
}
public void setCheckBox(bool set)
{
checkBox1.Checked = set;
}
}
}
主要课程有点长,无法提供,但我可以应要求提供。
解决方案
将列表或字典保存到您的控件中怎么样:
var dict = new Dictionary<string, CustomControl.BitsControl>();
创建组件时将其添加到字典中:
dict.Add(currentTag, newBits);
然后尝试类似:
foreach(var tag in tagsFile)
{
dict[tag].setCheckBox(true);
}
推荐阅读
- wix - 如何在 WIX 中的 MSI 安装程序标题中显示版本号?
- playlist - 液体肥皂备用播放列表
- javascript - 为什么 MDN 说“Function.prototype 不能被修改”?
- javascript - 如何让 Electron 在外部应用程序中自动打开下载的文件?
- php - 如何在本地主机的 wp-admin 中修复 ERR_CONNECTION_REFUSED 错误?
- python - Numpy 将在 Jupyter 中加载,但不会在 cmd/IDLE 中加载
- c# - 如何检查命令行参数的数量+异常处理
- kotlin - 从列表中删除不在另一个列表中的元素 - Kotlin
- java - 什么是更高性能的 equal 或 instanceof?
- python - 如何使用 db.command 获取 Python Mongo Aggregate 解释?