C#和Combobox没有加载列表的麻烦

时间:2012-09-12 20:28:28

标签: c# list combobox

我正在使用Combobox构建List,当从组合列表中选择Client时,它会加载特定的URL。问题是列表是空白的 下面是代码,但我没有看到我缺少的东西,但它可能是简单的疏忽,因为这是我第一次构建这样的Combobox。

public partial class Form1 : Form
{
    List<MyClient> clients;
    public Form1()
    {
        InitializeComponent();
        clients = new List<MyClient>();
        clients.Add(new MyClient { ClientName = "Client 1", UrlAddress = @"http://www.google.com" });
        BindBigClientsList();
    }

    private void BindBigClientsList()
    {
        BigClientsList.DataSource = clients;
        BigClientsList.DisplayMember = "ClientName";
        BigClientsList.ValueMember = "UrlAddress";
    }

    private void BigClientsList_SelectedIndexChanged(object sender, EventArgs e)
    {
        MyClient c = BigClientsList.SelectedItem as MyClient;
        if (c != null)
        {
            string url = c.ClientName;
            Process.Start(url);
        }
    }
}
class MyClient
{
    public string ClientName { get; set; }
    public string UrlAddress { get; set; }
}

2 个答案:

答案 0 :(得分:1)

您错过了最后一行: DataBind

private void BindBigClientsList()
{
    BigClientsList.DataSource = ClientSize;
    BigClientsList.DisplayMember = "ClientName";
    BigClientsList.ValueMember = "UrlAddress";
    BigClientsList.DataBind;
}

答案 1 :(得分:0)

您的构造函数应该如下所示

public Form1() 
    { 
        InitializeComponent(); 
        List<MyClient> clients = new List<MyClient>(); 
        clients.Add(new MyClient { ClientName = "Client 1", UrlAddress = @"http://www.google.com" });
        foreach(MyClient client in clients)
        {
            BigClients.Items.Add(client);
        } 
    }

这增加了两件事:

  • 将对象添加到ComboBox。没有它,该项目应该如何出现在ComboBox中?
  • 将代码放在InitializeComponent()语句之后。否则,当您尝试将MyClient对象添加到ComboBox时,它将抛出NullReferenceException。