简体   繁体   English

从父页面从Web用户控件中的元素获取值

[英]Get values from element in a Web User Control from the parent page

I have a Web User Control that contains a CheckBoxList. 我有一个包含CheckBoxList的Web用户控件。

MyListControl: MyListControl:

<asp:checkboxlist id="chkList" runat="server">
     <asp:listitem id="option1" runat="server" value="Madrid" />
     <asp:listitem id="option2" runat="server" value="Oslo" />
     <asp:listitem id="option3" runat="server" value="Lisbon" />
</asp:checkboxlist>

I want to check what Items are checked before a form is submitted on the parent page. 我想检查在父页面上提交表单之前要检查哪些项目。 I was hoping it would work like this: 我希望它能像这样工作:

myParentPage: myParentPage:

MyUserControlInstance.chkList.Items.Count

How does one reference a control in a user control from the parent page? 如何从父页面引用用户控件中的控件?

Encapsulate the property in your code behind of the control.. 将属性封装在控件后面的代码中。

public int GetLength
{
    get
    {
        return CheckListBox.Items.Cast<ListItem>().Where(
                                     i => i.Selected).ToList().Count;
    }
}

Now replace the line 现在更换线

MyUserControlInstance.chkList.Items.Count

with MyUserControlInstance.GetLength MyUserControlInstance.GetLength


Note - Please add necessary Namespaces like System.Collections.Generic and System.Linq 注意 -请添加必要的命名空间,例如System.Collections.GenericSystem.Linq

I would expose this information as a public property on the User Control, returning only the necessary information, such as: 我会将这些信息公开为用户控件上的公共属性,仅返回必要的信息,例如:

using System.Collections.Generic;
using System.Linq;

// ...

public IList<string> CheckedValues
{
    get { return chkList.Items.Cast<ListItem>().Where(i => i.Selected).Select(i => i.Value).ToList(); }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM