C# 组合框无法显示数据源



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

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";
    }

尝试使用BindingSource执行此操作:

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

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

Combobox1.DataBind();

对我有用

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;
        }
    }
}

您必须绑定组合框以进行通知,例如;

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

最新更新