1

我有一个TableLayoutPanel并且我正在迭代一个集合以动态构建表的内容。我正在尝试ErrorProvider为每个ComboBox生成的内容添加一个。但是,我不知道如何在组合框验证事件处理程序中获取相应错误提供程序的句柄?

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    TableLayoutPanel _tableLayoutPanel1;

    private void Form1_Load(object sender, EventArgs e)
    {
        _tableLayoutPanel1 = new TableLayoutPanel();
        _tableLayoutPanel1.AutoSize = true;

        BuildTableContents();

        this.Controls.Add(_tableLayoutPanel1);
    }

    private void BuildTableContents()
    {
        for (int i = 0; i < 3; i++)
        {
            Label labelLeft = new Label();
            labelLeft.Text = "Test Left Column";
            _tableLayoutPanel1.Controls.Add(labelLeft, 0, i);

            ComboBox cbo = new ComboBox();
            cbo.Validated += new EventHandler(cbo_Validated);
            cbo.Name = "cbo_" + i;
            cbo.Items.AddRange(new object[] { "Yes", "No" });
            _tableLayoutPanel1.Controls.Add(cbo, 1, i);

            ErrorProvider err = new ErrorProvider();
            err.SetIconAlignment(cbo, ErrorIconAlignment.MiddleRight);
        }
    }

    void cbo_Validated(object sender, EventArgs e)
    {
        //How do I get a handle on associated 
        //Error Provider to current combo box?

    }

    private void btnSave_Click(object sender, EventArgs e)
    {
        ValidateChildren();
    }
}
4

1 回答 1

2

尝试将 ErrorProvider 放在表单范围级别:

TableLayoutPanel _tableLayoutPanel1;
ErrorProvider err = new ErrorProvider();

public Form1() {
    InitializeComponent();
}
于 2012-12-18T18:21:55.207 回答