用户控制一个实例的两个实例对其他事件做出反应

时间:2011-05-09 08:15:24

标签: c# winforms user-controls

我有一个用户控件。用户控制一个实例的两个实例对其他事件做出反应。

一些建议?

1 个答案:

答案 0 :(得分:1)

这是用户控件,

名字:

<asp:TextBox ID="TextBoxFirstName" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RQV1" runat="server" ControlToValidate="TextBoxFirstName" ErrorMessage="*"></asp:RequiredFieldValidator>

姓氏:

<asp:TextBox ID="TextBoxLastName" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RQV2" runat="server" ControlToValidate="TextBoxLastName" ErrorMessage="*"></asp:RequiredFieldValidator>

以下是公开属性的页面的代码隐藏,

public string GetFirstName
{
    get { return TextBoxFirstName.Text; }
    set { TextBoxFirstName.Text = value; }
}

public string GetLastName
{
    get { return TextBoxLastName.Text; }
    set { TextBoxLastName.Text = value; }
}

在代码隐藏中,我创建了两个公共字符串变量,将值设置为TextBox控件的Text属性并返回TextBox控件的Text属性。

然后,在主页面中,

<form id="form1" runat="server">
<div>This is page to add multiple user controls.</div>
<p>
    Customer1 Details:<br />
    <uc1:WebUserControl1 ID="WebUserControl11" runat="server" />
</p>

<p>
    Customer2 Details:<br />
    <uc1:WebUserControl1 ID="WebUserControl12" runat="server" />           
</p>

<asp:Button ID="Button1" runat="server" Text="Continue" OnClick="GetCustDetails"/>
<asp:Button ID="Button2" runat="server" Text="Clear" CausesValidation="false" OnClick="ClearFields" /><br />

Customer1 FirstName: <asp:label ID="Label1" runat="server"></asp:label><br />
Customer1 LastName: <asp:label ID="Label2" runat="server"></asp:label><br />
Customer2 FirstName: <asp:label ID="Label3" runat="server"></asp:label><br />
Customer2 LastName: <asp:label ID="Label4" runat="server"></asp:label><br />
</form>

我正在向页面添加两个用户控件实例。然后有四个Label控件将在Button1单击时显示用户控件的属性。还有另一个Button2可以清除所有用户控件的TextBox控件。

protected void GetCustDetails(object sender, EventArgs e)
{
    Label1.Text = WebUserControl11.GetFirstName;
    Label2.Text = WebUserControl11.GetLastName;
    Label3.Text = WebUserControl12.GetFirstName;
    Label4.Text = WebUserControl12.GetLastName;
}

protected void ClearFields(object sender, EventArgs e)
{
    WebUserControl11.GetFirstName = string.Empty;
    WebUserControl11.GetLastName = string.Empty;
    WebUserControl12.GetFirstName = string.Empty;
    WebUserControl12.GetLastName = string.Empty;
}