【问题标题】:How to access controls of dynamically added user controls in a panel in C#?如何访问 C# 面板中动态添加的用户控件的控件?
【发布时间】:2018-12-13 09:31:22
【问题描述】:

我有一个面板,它有多个动态添加的用户控件(都一样),我需要查看是否选中了一个复选框以及每个控件中的 label.text 是什么。不确定如何获得这些值?

这是将用户控件添加到面板的位置

private void Employee_Add_Load(object sender, EventArgs e)
    {
        List<string> VehicleTypes = DAL.LicenseDAL.GetAllVehicleTypes();

        foreach (string Vehicle in VehicleTypes)
        {
            User_Controls.Vehicle_Bar VTB = new Vehicle_Bar(Vehicle);
            pnlVehicleChecks.Controls.Add(VTB);
        }
    }

这是用户控件(实际上只是一个标签和复选框)

public partial class Vehicle_Bar : UserControl
{
    public string Vehicle = "";

    public Vehicle_Bar(string vehicle)
    {
        Vehicle = vehicle;
        InitializeComponent();
    }

    private void Vehicle_Bar_Load(object sender, EventArgs e)
    {
        lblType.Text = Vehicle;
    }
}

所有这些复选框都适用于员工的车辆执照,具体取决于选中的复选框取决于允许他们驾驶的车辆

【问题讨论】:

  • 您可以在表单中为您的usercontrol 提供onclick 事件。在form 中的foreach 循环中为usercontrol 声明onclick 事件

标签: c# winforms controls


【解决方案1】:

您可以在 UserControl 中处理复选框数据的检索,并将其存储在可公开访问的数据对象中

public class VehicleInfo
{
    public bool allowdrive {get; set; }
    public string vehicle {get; set; }
}

public partial class Vehicle_Bar : UserControl
{   
    public VehicleInfo vehicleInfo;

    public Vehicle_Bar(string vehicle)
    {
        vehicleInfo = new VehicleInfo(){
            vehicle = vehicle,
            allowdrive = false
        };

        InitializeComponent();
    }

    private void Vehicle_Bar_Load(object sender, EventArgs e)
    {
        lblType.Text = vehicleInfo.vehicle;
    }

    //Handle checkbox click event to set the value of "allowdrive"
}

字符串和复选框的组合数据存储在对象 vehicleInfo 中,可以使用 UserControl Vehicle_Bar 的实例访问该对象

示例:

Console.WriteLine(VTB.vehicleInfo.allowdrive);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 2011-08-01
    • 1970-01-01
    • 2010-10-11
    • 2012-12-10
    相关资源
    最近更新 更多