簡體   English   中英

是否可以通過編程方式添加到面板的自定義控件中訪問和更改值?

[英]Is there a way to access and change a value in a custom control that was added, programmatically, to a panel?

在將自定義控件中的復選框“ checked”值以編程方式添加到表后,如何更改它?

我有一個具有文本框和復選框的自定義控件。 (我沒有足夠的聲譽來發布圖像,但這是鏡頭) 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);
                }
            }

        }

如果您無法分辨,每個復選框將32位數字中的一位值保留為4個數字(因此,嵌套循環0-31,共4次),關鍵是顯示或控制這些值。 您可以忽略有關標簽的代碼。 所有要做的就是從文件中讀取文本,並使用讀取的文本填充文本框。

在執行代碼時,如果某個位的狀態發生更改,則復選框也應更改狀態。 下面的循環將被修改以遍歷int的數組(4個int),並在讀取每個位的狀態后更新每個復選框。 當前,僅將循環設置為將所有位更改為“ true”。 這最終不是我想要的,但重點是,我什至無法引用面板中的自定義控件來完全更改復選框。 我認為以下方法會起作用,但是我沒有嘗試過。

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM