复选框列表显示ID而不是文本

时间:2014-08-28 07:02:48

标签: c# linq data-binding checkboxlist

我正在动态创建一个通过linq填充的复选框列表。复选框列表确实已创建,但不是显示应该是name + surname的值(文本),而是显示用户的ID。

这就是我所做的:

    private void CreateUsersList()
    {
        chkUsers.Items.Clear();

        var query = (from u in context.SkillAssestUsers
                     select new
                        {
                            u.ID,
                            u.Name,
                            u.Surname
                        }).OrderBy(x => x.Name).ToList();

        chkUsers.AutoPostBack = false;
        chkUsers.CellPadding = 5;
        chkUsers.CellSpacing = 5;
        chkUsers.RepeatColumns = 4;
        chkUsers.RepeatDirection = RepeatDirection.Horizontal;
        chkUsers.RepeatLayout = RepeatLayout.Table;
        chkUsers.TextAlign = TextAlign.Right;
        chkUsers.CssClass = "CheckBoxList";

        if (query != null)
        {
            foreach (var result in query)
            {
                string fullName = result.Name + " " + result.Surname;
                CheckBox cb = new CheckBox();
                cb.ID = result.ID.ToString();
                cb.Text = result.Name + " " + result.Surname;
                cb.AutoPostBack = false;
                cb.CssClass = "CheckBox";

                chkUsers.Items.Add(new ListItem(result.ID.ToString(), result.Name + " " + result.Surname));
                chkUsers.Controls.Add(new LiteralControl("<br>"));
            }
        }
    }

这是我运行项目时数据的来源:

enter image description here

因此,我想要显示名称和姓氏,而不是ID,但我看不出我做错了什么......

有人可以指出我正确的方向吗?任何帮助将不胜感激......

1 个答案:

答案 0 :(得分:1)

这是因为ListItem的构造函数是:

public ListItem(
    string text,
    string value
)

所以改变这一行:

chkUsers.Items.Add(new ListItem(result.ID.ToString(), 
                   result.Name + " " + result.Surname));

到此:

chkUsers.Items.Add(new ListItem(result.Name + " " + result.Surname,
                       result.ID.ToString()));

参考:

  1. ListItem Constructor (String, String)
  2. ListItem Class