C# 在用户控件内查找控件

C# 在用户控件内查找控件,c#,asp.net,C#,Asp.net,我想获取用户控件中的文本框值。 我从代码隐藏文件中动态添加了用户控件。用户控件包含两个文本框和一个下拉列表。使用时更改文本框值。我想将该值更新到数据库中。通过创建事件并在第页中处理,您可以在用户控件中的值更改时收到通知 这是一个样本 UC设计 <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UCTest.ascx.cs" Inherits="UCDynamic.UCTest" %> <div>

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

通过创建事件并在第页中处理,您可以在用户控件中的值更改时收到通知

这是一个样本

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>
页面设计

<%@ 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>

如果动态添加控件,则应该知道其名称。所以你可以正常引用它。MyControl.TextBox1.text如果它是动态完成的,那么它可能没有变量。。。这里有
this.Controls.OfType.First
可能会起作用,但对我来说似乎有点不对劲,实际上,从它的声音来看,您的用户控件应该有一个文本更改事件来更新此数据库谢谢您的回复。如果用户更改文本框值的情况。我想获得文本框的更改值
<%@ 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
        }
    }
}