2

我正在尝试为可以编辑并保存回数据库的数据库记录构建一个“编辑”页面。其中一个字段是多选列表框,加载时需要在硬编码列表中突出显示适当的列表项。

使用 C#,我如何根据数据库字段中的逗号分隔字符串填充多选列表框 - 并选择适当的项目?我研究了一些涉及循环的解决方案,但我无法让它们与我有限的 C# 技能组一起工作。

这就是我现在所拥有的,在我陷入困境之前。您会看到它没有考虑字符串中的多个值。是否有像“包含”这样的功能,我可以检查值是否匹配?我在这里仍然缺少一些(可能是基本的)C# 逻辑和编码。

int i;
for (i = 0; i <= CATEGORYListBox.Items.Count - 1; i++)
{
    if (reader["CATEGORY"].ToString() == CATEGORYListBox.Items(i).Value)
    {
        CATEGORYListBox.Items(i).Selected = True;                   
    }
}

...

<asp:ListBox ID="CATEGORYListBox" runat="server">
    <asp:ListItem Value="Circulation">Circulation</asp:ListItem>
    <asp:ListItem Value="Interactive Media">Interactive Media</asp:ListItem>
    <asp:ListItem Value="Classified">Classified</asp:ListItem>
    <asp:ListItem Value="Publishing">Publishing</asp:ListItem>
    <asp:ListItem Value="Editorial">Editorial</asp:ListItem>
    <asp:ListItem Value="Retail">Retail</asp:ListItem>
 </asp:ListBox>

谢谢大家。

4

5 回答 5

5

我会建议一些类似的东西。它似乎比嵌套循环更具可读性。

    List<string> categories = new List<string>(reader["CATEGORY"].ToString().Split(','));
    foreach (ListItem item in CATEGORYListBox.Items)
    {
        if (categories.Contains(item.Value))
            item.Selected = true;
    }
于 2009-02-10T15:04:41.647 回答
2

这是蛮力和丑陋的,但它应该工作。看起来您上面的代码是 VB 和 C# 之间的某种混合。下面的代码仅适用于 C#。此外,请考虑不要在代码隐藏中执行 ADO.Net 。

for (int i = 0; i < CATEGORYListBox.Items.Count; i++)
{
    foreach (string category in reader["CATEGORY"].ToString().Split(','))
    {
        if (category != CATEGORYListBox.Items[i].Value) continue;
        CATEGORYListBox.Items[i].Selected = true;
        break;
    }
}
于 2009-02-10T13:31:21.683 回答
0

该问题的另一个解决方案是:

    string[] arrSplitItems;
    arrSplitItems = TestsOrdrd.Split(',');
    if (arrSplitItems.Length > 0)
    {
        for (int iCount = 0; iCount < arrSplitItems.Length; iCount++)
        {
            lstTestcode.Items.FindByValue(arrSplitItems[iCount].ToString()).Selected = true;
        }
    }

TestsOrdrd 包含列表框的选定值。

谢谢, Rathika Krishnavelu

于 2009-10-06T05:36:17.607 回答
0

最简单的实现?

string sequenceFromDBorPostBack= "1,3,4,6,48";

foreach (ListItem item in lstLocations.Items)
{
     item.Selected = sequenceFromDBorPostBack.Split(',').Contains(item.Value);
}

我不确定这是否有效..

于 2010-09-22T10:43:01.883 回答
0
ListBox1.SelectionMode = ListSelectionMode.Multiple;
string[] pageRoles = myReader["UserProfile"].ToString().Split(',').ToArray();
pageRoles.ToList().ForEach(r => ListBox1.Items.FindByValue(r).Selected = true);
于 2013-06-12T23:23:08.173 回答