1

我正在 ASP.net 中创建一个 WebUserControl,并希望以后能够访问该控件的元素。当我访问它们时,虽然我试图一起访问它们。例如,将 CheckBox 和表格添加到控件,然后找到 CheckBox,检查它是否已被勾选,如果已被勾选,则从 TextBoxes 中获取值。

我目前从自定义控件加载页面上的所有内容,但是当迭代页面上的控件时,似乎没有我的 WebUserControl 类型的控件。所有控件都在页面上,但它们作为单独的 ASP.net 控件存在。

我想错了吗?有一个更好的方法吗?

我不确定这是否解释得很好,请随时提出澄清问题。

4

1 回答 1

2

您需要通过创建公共属性或函数来公开用户控件功能,以使其执行您需要的操作或按照您的意愿行事。因此,例如,在您的情况下,您可以在用户控件中拥有一个属性,例如(您也可以执行一个函数):

public List<string> SomeValues
{
    get
    {
        // return null if checkbox is not checked, you could just as easily return an empty list.
        List<string> lst = null;
        if (yourCheckBox.Checked)
        {
            lst = new List<string>();

            // You could have something that iterates and find your controls, remember you  
            // are running this within your user control so you can access all it's controls.
            lst.Add(yourTextBox1.Text);
            lst.Add(yourTextBox2.Text);
            lst.Add(yourTextBox3.Text);
            // etc...
        }
        return lst;
    }
}

然后在您的页面中,您可以访问您的用户控件并调用此属性来获取值:

// assuming you defined your usercontrol with the 'yourUserControl' ID
List<string> lst = yourUserControl.SomeValues;

关键是在您的用户控件中公开您想要的内容,因此无论使用什么都不需要知道它的细节或实现。您应该能够像使用任何其他控件一样使用它。

于 2010-03-03T01:04:13.793 回答