c# - 在动态添加的 UserControl 上设置属性

标签 c# .net asp.net user-controls .net-2.0

我根据 this post 向页面动态添加自定义用户控件.

但是,我需要在用户控件上设置一个属性,因为我将它添加到页面。我怎么做?

代码片段会很好 :)

详细信息:

我有一个带有公共(public)字段的自定义用户控件(属性...例如 public int someId;)

当我向页面添加一个 UserControl 时,它的类型是 UserControl。我是否只是将其转换为 MyCustomUCType 并在转换控件上设置一个属性?

附注看来我终于回答了我自己的问题。

最佳答案

啊,我在你添加额外的说明之前回答了。简短的回答是,是的,只需将其转换为您的自定义类型即可。

我会把剩下的答案留在这里以供引用,尽管您似乎不需要它。


借用其他问题中的代码,并假设您的所有用户控件都可以从同一个基类继承,您可以这样做。

创建一个新类作为基础控件:

public class MyBaseControl : System.Web.UI.UserControl
{
    public string MyProperty 
    {
        get { return ViewState["MyProp"] as string; }
        set { ViewState["MyProp"] = value; }
    }
}

然后更新您的用户控件以从您的基类而不是 UserControl 继承:

public partial class SampleControl2 : MyBaseControl
{
    ....

然后,在你加载控件的地方,改变这个:

UserControl uc = (UserControl)LoadControl(controlPath);
PlaceHolder1.Controls.Add(uc);

到:

MyBaseControl uc = (MyBaseControl)LoadControl(controlPath);
uc.MyProperty = "foo";
PlaceHolder1.Controls.Add(uc);

关于c# - 在动态添加的 UserControl 上设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/508826/

相关文章:

c# - 如何重定向所有错误,包括 404

c# - 将 EF LINQ 方法语法转换为查询语法

c# - 系统.Data.SqlClient.SqlException : Implicit conversion from data type sql_variant to uniqueidentifier is not allowed.

c# - 显示名称为 'VJSharpCodeProvider' 的程序集加载失败

c# - C# 中的可空 DateTime

c# - 在 C# 中打开命令行并发送命令 PuTTY 或 KiTTY

c# - GetVersionEx() 已弃用 : should I use Environment. OSVersion?

c# - UpdatePanel 中的双重 PostBack

c# - DataGridView 不在 ToolStripDropDown 中显示数据

asp.net - 如何解决抓取问题