为什么我的ListBox显示“(Collection)”而不是我的字典中的内容? (C#WinForms)

时间:2014-11-02 21:51:00

标签: c# winforms dictionary listbox

我试图创建一个带有输入的应用程序(通过文本框),根据以URL为关键字和该网站的HTMLCode作为值创建一个字典条目,我试图显示JUST但是,列表框的关键是我遇到了一些麻烦。

我的词典正确填充了Url和html但是,我试图让键显示的列表框只显示“(Collection)”。我已经尝试了几种我已经看过的解决方案,它仍然只显示(收藏)

我已经尝试了好几天才找到一个没有成功的解决方案。谢谢你的阅读。

代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;

namespace HtmlChecker
{
    public partial class Form1 : Form
    {
        public Form1()
        {
        InitializeComponent();
        }

        static SortedDictionary<string, WebsiteInfo> dict =
                new SortedDictionary<string, WebsiteInfo>();

        BindingSource bSource = new BindingSource();

        private void Form1_Load(object sender, EventArgs e)
        {
            DataTable table = new DataTable();
            table.Columns.Add("Key");
            table.Columns.Add("Value");

            foreach (KeyValuePair<string, WebsiteInfo> pair in dict)
            {
                table.Rows.Add(pair.Key, pair.Value);
            }
            bSource.DataSource = dict;

            this.lstDisplay.DisplayMember = "Value";
            this.lstDisplay.ValueMember = "Key";
            this.lstDisplay.DataSource = bSource;
        }

        private void btnCheck_Click(object sender, EventArgs e)
        {
            addWebsite(txtUrl.Text);
        }    

        private static void addWebsite(string websiteUrl)
        {
            try
            {
                dict.Add(websiteUrl, new WebsiteInfo { WebsiteUrl = websiteUrl, HtmlCode = getHtml(websiteUrl) });
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        public static string getHtml(string websiteUrl)
        {
            using (WebClient client = new WebClient())
                return client.DownloadString(websiteUrl);
        }

    }

    public class WebsiteInfo
    {
        public string WebsiteUrl;
        public string HtmlCode;

        public override string ToString()
        {
            string formated = string.Format("{0}\n---------------------------------- \n{1}", WebsiteUrl, HtmlCode);
            return formated;
        }

    }
}

1 个答案:

答案 0 :(得分:0)

尝试更改下一个代码:

bSource.DataSource = dict;

this.lstDisplay.DisplayMember = "Value";
this.lstDisplay.ValueMember = "Key";
this.lstDisplay.DataSource = bSource;

要:

bSource.DataSource = table; //assign created table as DataSource

this.lstDisplay.DisplayMember = "Key"; //Column's name which you want to show in the list
this.lstDisplay.ValueMember = "Value";
this.lstDisplay.DataSource = bSource;