我正在尝试生成一个用户控件,它由标签,下拉菜单和文本框组成,动态,因此我可以设置标签的值。当我运行它时,我的下拉列表和文本框有问题,因为它们需要在带有runat服务器的表单标签中。当我添加表单标记时,编译器会抱怨只能有一个表单标记。请帮忙。这是我的代码:
用户控制:
<%@ Control Language="C#" AutoEventWireup="true"
CodeFile="IngredientQuantityControl.ascx.cs" Inherits="IngredientQuantityControl" %>
<asp:Label ID="IngredientDisplay" runat="server" Text="Label"></asp:Label>
<asp:DropDownList ID="DropDownList1" runat="server" >
<asp:ListItem Value=null >Please Choose a Unit</asp:ListItem>
<asp:ListItem Value="Unit">Unit(s)</asp:ListItem>
<asp:ListItem>Cup</asp:ListItem>
<asp:ListItem>Tbsp</asp:ListItem>
<asp:ListItem>Tsp</asp:ListItem>
<asp:ListItem>To Taste</asp:ListItem>
<asp:ListItem>Milligrams</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
代码隐藏:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class IngredientQuantityControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void SetLabelText(String s)
{
IngredientDisplay.Text = s;
}
}
动态添加到面板
protected void Button1_Click(object sender, EventArgs e)
{
Page.Controls.Add(LoadControl("IngredientQuantityControl.ascx"));
IngredientQuantityControl uc = (IngredientQuantityControl)Page.LoadControl("IngredientQuantityControl.ascx");
uc.SetLabelText("Halleluyah!");
Panel1.Controls.Add(uc);
//string text = listBox1.GetItemText(listBox1.SelectedItem);
}
}
答案 0 :(得分:0)
您要将IngredientQuantityControl.ascx
作为对象添加两次。
protected void Button1_Click(object sender, EventArgs e)
{
IngredientQuantityControl uc = (IngredientQuantityControl)Page.LoadControl("IngredientQuantityControl.ascx");
uc.SetLabelText("Halleluyah!");
Panel1.Controls.Add(uc);
//string text = listBox1.GetItemText(listBox1.SelectedItem);
}