代码中有什么错误?它不工作了!!
实际上,我想从数据库的一个字段中拆分条目。其中的项目用逗号分隔。
这就是我正在做的事情。
string str = dataSet.Tables[0].Rows[0]["Ingredients"].ToString();
string[] split = str.Split(',');
IList<string> lblListItemIngredients = new List<string>();
foreach (string item in split)
{
lblListItemIngredients.Add(item);
}在我的aspx页面中,
<ul>
<li>
<asp:label id="lblListItemIngredients" runat="server></asp:Label>
</li>
</ul>但是输出不会出现,但在调试模式下,我可以看到字符串正在拆分。怎么了?
发布于 2012-09-15 19:46:54
您必须以某种方式将列表中的数据放到控件中。这不会因为你给了一个变量与控件的id同名而神奇地发生。
实际上,您应该为变量使用不同的名称,否则它将隐藏已添加到页面对象的属性。
如果你想创建一个HTML列表,仅仅在一个列表项中放置一个标签是不够的,它不会为每个字符串创建一个列表项。您可以使用中继器:
<ul>
<asp:Repeater id="lblListItemIngredients" runat="server">
<ItemTemplate>
<li><%# Container.DataItem %></li>
</ItemTemplate>
</asp:Repeater>
</ul>您不必为数据源创建列表,数组就可以很好地工作:
string str = dataSet.Tables[0].Rows[0]["Ingredients"].ToString();
string[] split = str.Split(',');
lblListItemIngredients.DataSource = split;
lblListItemIngredients.DataBind();发布于 2012-09-15 19:49:43
当您应该使用asp:ListBox之类的东西时,却在页面标记中使用了asp:label控件。也要从代码中删除IList<String>声明。
将字符串数组添加到ListBox的更好方法只需如下所示:
首先,在标记中,将不正确的控件引用更改为ListBox:
<asp:ListBox id="IngredientList" runat="server"></asp:ListBox>其次,在源代码中,简化添加:
string str = dataSet.Tables[0].Rows[0]["Ingredients"].ToString();
string[] ingredients= str.Split(',');
IngredientList.Items.AddRange(ingredients);此方法消除了标记中不正确的label控件,并从代码隐藏中消除了手动迭代和原始版本中不需要的IList声明。希望这能有所帮助。
发布于 2012-09-15 20:11:44
Guffa已经很棒了,但只是为了完整,因为它符合你最初做它的精神:-)
如果您将标记更新为:
<ul>
<asp:Literal id="literalIngredients" runat="server" />
</ul>(老实说,如果在foreach循环中使用yourLabel.Text += item;,那么您的原始代码或多或少会正常工作,正如Guffa所说,使用相同的名称调用变量和控件并不是一个好主意)
并将您的代码更新为
string str = dataSet.Tables[0].Rows[0]["Ingredients"].ToString();
string[] split = str.Split(',');
// not needed IList<string> lblListItemIngredients = new List<string>();
foreach (string item in split)
{
literalIngredients.Text += string.Format("<li>{0}</li>",item);
}https://stackoverflow.com/questions/12437062
复制相似问题