C#ComboBox无法显示数据源

时间:2017-01-29 15:11:56

标签: c# combobox

我尝试在单击按钮时将一个列表添加到ComboBox作为数据源,但它没有显示。 这是我试过的

List<string> data;
    private void button1_Click(object sender, EventArgs e)
    {
        data = new List<string>() { "Beginer", "C# Programer", "Object Oriented" };
        comboBox1.DataSource = data;
    }

[![屏幕截图:当我点击按钮时,数据源已更新,但它没有显示] [1]] [1]

但是当我添加列表

时它会起作用
List<Food> data;
    private void button1_Click(object sender, EventArgs e)
    {   
        data = new List<Food>()
        {
            new Food() {Name = "Hotdog", Price = 10 },
            new Food() {Name = "Paparati", Price = 12 }
        };

        comboBox1.DataSource = data;
        comboBox1.DisplayMember = "Name";
    }

3 个答案:

答案 0 :(得分:0)

尝试使用BindingSource

执行此操作
BindingSource bs = new BindingSource();
bs.DataSource = new List<string> { "test1", "test2" };
comboBox1.DataSource = bs;

如果这是一个网络表单,则必须使用Databind

Combobox1.DataBind();

答案 1 :(得分:0)

它对我有用

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;

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


            List<string> data;
    private void button1_Click(object sender, EventArgs e)
        {
            data = new List<string>() { "Beginer", "C# Programer", "Object      ``Oriented" };
            comboBox1.DataSource = data;
        }
    }

}

答案 2 :(得分:0)

您必须将Combobox绑定到winform,例如;

Combobox1.DisplayMember = "Value";
Combobox1.ValueMember = "Key";