[英]C# ComboBox can't display datasource
I try to add a list to a ComboBox as data source when click a button but it doesn't display. 我尝试在单击按钮时将列表添加到ComboBox作为数据源,但它不显示。 Here is what I tried 这是我尝试过的
List<string> data;
private void button1_Click(object sender, EventArgs e)
{
data = new List<string>() { "Beginer", "C# Programer", "Object Oriented" };
comboBox1.DataSource = data;
}
[![Screen Capture: when I click button, data source is updated but it doesn't display][1]][1] [![截屏:当我单击按钮时,数据源已更新,但未显示] [1]] [1]
But it works when I add a list 但是当我添加列表时它可以工作
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";
}
Try to do this using a BindingSource
: 尝试使用BindingSource
做到这一点:
BindingSource bs = new BindingSource();
bs.DataSource = new List<string> { "test1", "test2" };
comboBox1.DataSource = bs;
If this is a webform you have to use Databind
如果这是一个网络表单,则必须使用Databind
Combobox1.DataBind();
It works for me 这个对我有用
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;
}
}
}
You have to bind Combobox for winform such as; 您必须为Winform绑定Combobox,例如;
Combobox1.DisplayMember = "Value";
Combobox1.ValueMember = "Key";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.