在用户用户控件中查找控件

时间:2014-04-07 15:08:07

标签: c# asp.net

我想获取用户控件内的Text Box值。 我从代码隐藏文件中动态添加了用户控件。用户控件包含两个文本框和一个Drop Down。使用时更改文本框值。我想将该值更新到数据库中。

1 个答案:

答案 0 :(得分:0)

通过创建事件并在页面

中处理它,可以在用户控件中更改值时收到通知

这是一个示例

UC设计

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UCTest.ascx.cs" Inherits="UCDynamic.UCTest" %>
<div>
    <asp:TextBox ID="txtFirstName" runat="server" AutoPostBack="True" 
        ontextchanged="txtFirstName_TextChanged"></asp:TextBox>
</div>
<div>
    <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
</div>
<div>
    <asp:DropDownList ID="ddlCountry" runat="server">
    </asp:DropDownList>
</div>

UC代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UCDynamic
{
    public delegate void FirstNameValueChanged(string value);

    public partial class UCTest : System.Web.UI.UserControl
    {
        public event FirstNameValueChanged FirstNameChanged;

        protected void txtFirstName_TextChanged(object sender, EventArgs e)
        {
            FirstNameChanged.Invoke(txtFirstName.Text);
        }
    }
}

页面设计

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="UCDynamic.WebForm1" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Panel ID="Panel1" runat="server">
        </asp:Panel>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </div>
    </form>
</body>
</html>

网页代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UCDynamic
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        UCTest UCTest1;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Add UC
                UCTest1 = (UCTest)Page.LoadControl("~/UCTest.ascx");
                //Attach event
                UCTest1.FirstNameChanged += FirstName_TextChanged;

                this.Panel1.Controls.Add(UCTest1);
            }
        }

        protected void FirstName_TextChanged(string value)
        {
            TextBox1.Text = value;

            //Update value in database
        }
    }
}