为什么Datalist只用我的代码显示最后一个值?

时间:2014-07-03 14:28:47

标签: c# asp.net

public void rt_changed(object sender, AjaxControlToolkit.RatingEventArgs e)
{
  // Declare l, also give it a default value, in the case that datalist is empty.
   Label l = null;
   foreach (DataListItem li in datalist.Items)
   { 
      l = li.FindControl("nl") as Label;
   }
   Label3.Text = l.Text; // l values is not getting
 }

在这里,我只获得从Datalist到Label3的最后一个值。基于我的点击我没有得到标签中的值。 我应该在此代码中更改/执行哪些操作?

1 个答案:

答案 0 :(得分:1)

您看到最后一条记录的原因是您没有在循环中保留标签的值。最好使用StringBuilder

public void rt_changed(object sender, AjaxControlToolkit.RatingEventArgs e)
{
    StringBuilder sb = new StringBuilder();
    // Declare l, also give it a default value, in the case that datalist is empty.
    Label l = null;
    foreach (DataListItem li in datalist.Items)
    {
        l = li.FindControl("nl") as Label;
        sb.AppendLine(l.Text);
    }
    Label3.Text = sb.ToString(); // l values is not getting
}