小编use*_*870的帖子

将"Control"转换为文本框并为其指定值

我正在尝试创建一个表单.表单控件名称始终是相同的.但是控制的类型会改变.例如,我有一个名为"first_name"的控件.页面初始化时,它从数据库中检索数据,说明控件的类型(TextBox,DropDownList或CheckBox); 然后在页面上动态创建表单.为了保持视图状态,我在OnInit方法中创建了控件.

protected override void OnInit(EventArgs e)
{
    Control first_name;
    string ControlType = GridView1.Rows[0].Cells[1].Text;
    switch (ControlType)
    {
        case("TextBox"):
            first_name = new Control() as TextBox; first_name.ID = "first_name"; this.Controls.Add(first_name);
            break;
        case("DropDownList"):
            first_name = new Control() as DropDownList; first_name.ID = "first_name"; this.Controls.Add(first_name);
            break;
        case("CheckBox"):
            first_name = new Control() as CheckBox; first_name.ID = "first_name"; this.Controls.Add("first_name");
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我将控件呈现给页面.

protected override void Render(HtmlTextWriter writer)
{
    writer.Write("first_name: ");
    first_name.RenderControl(writer);
}
Run Code Online (Sandbox Code Playgroud)

接下来,我尝试为控件赋值.这是我遇到问题的地方.我知道当它被全局声明时,它被声明为一个控件并保存这些值.

有没有办法在函数内全局声明它,或者在全局声明后更改控件的类型?

protected void Page_Load(object sender, EventArgs e)
{
    switch (first_name.GetType().ToString())
    {
        case ("TextBox"): …
Run Code Online (Sandbox Code Playgroud)

c# asp.net controls

0
推荐指数
1
解决办法
2万
查看次数

标签 统计

asp.net ×1

c# ×1

controls ×1