【问题标题】:ASP.NET lisbox - Selected first item, alwaysASP.NET 列表框 - 始终选择第一项
【发布时间】:2010-05-01 17:39:51
【问题描述】:

我有一个使用字典填充的列表框。当我使用以下代码遍历所选项目时,它始终只显示第一个项目被选中 - 即使第一个项目未被选中。

你遇到过这种情况吗?

你能帮忙吗?

当我使用字典进行绑定时会出现此问题。另一方面,通用列表可以正常工作。

 private void PopulateListBox2()
    {
        List<string> subjectList = new List<string>();
        subjectList.Add("Maths");
        subjectList.Add("Science");

        ListBox1.DataSource = subjectList;
        ListBox1.DataBind();
    }

如果值是唯一的,即使它也可以正常工作。但在我的情况下,值是相同的;唯一的关键变化。以下作品

 private void PopulateListBox5()
    {
        Dictionary<string, string> resultDictionary = new Dictionary<string, string>();

        resultDictionary.Add("Maths", "Lijo1");
        resultDictionary.Add("Science", "Lijo2");

        ListBox1.DataValueField = "Value";
        ListBox1.DataTextField = "Key";

        ListBox1.DataSource = resultDictionary;
        ListBox1.DataBind();
    }

^^^^^^^^^^^^^^^^^^^ 以下代码有问题。

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            PopulateListBox1();
            ListBox1.SelectionMode = ListSelectionMode.Multiple;
        }
    }

    private void PopulateListBox1()
    {
        Dictionary<string, string> resultDictionary = new Dictionary<string, string>();

        resultDictionary.Add("Maths", "Lijo");
        resultDictionary.Add("Science", "Lijo");

        ListBox1.DataValueField = "Value";
        ListBox1.DataTextField = "Key";

        ListBox1.DataSource = resultDictionary;
        ListBox1.DataBind();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        MakeList1Items();
    }

    private void MakeList1Items()
    {
        string test = null;

        foreach (ListItem item in ListBox1.Items)
        {
            if (item.Selected == true)
            {
                if(string.IsNullOrEmpty(test))
                {
                    test=item.Text;
                }
                else
                {
                    test = test +", " + item.Text;
                }

            }
        } 
        Response.Write(test);
    }

}

谢谢

李乔

【问题讨论】:

  • 这段代码出现在页面生命周期的什么地方?
  • 此事件属于在按钮单击事件处理程序中调用的函数。
  • 所以它在按钮的点击处理程序中?您可能希望使用更多周边代码来更新您的问题。这里真的没什么可做的。此外,请记住使用010 101 按钮或将代码缩进 4 个空格以使其格式正确。

标签: asp.net listbox selecteditem


【解决方案1】:

ListBox 的DataValueFieldDataTextField 出现错误。我不确定为什么,但它们一定是这样的:

ListBox1.DataValueField = "Key";
ListBox1.DataTextField = "Value";

因此,实际上,您最好不要使用 Dictionary 进行这种绑定。不妨试试List&lt;KeyValuePair&lt;string, string&gt;&gt;

【讨论】:

  • 没有。它不起作用。我已经用更多细节更新了原始问题。
  • 确实有效。我复制了你的代码,切换了“键”和“值”,两者都被输出了。他们需要这样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-09
  • 2012-03-18
相关资源
最近更新 更多