2009-10-22 13 views
15

Tengo un ComboBox y quiero vincularle una lista genérica. ¿Alguien puede ver por qué el código siguiente no funcionará? La fuente de enlace tiene datos, pero no llenará la fuente de datos ComboBox.Enlazando una lista genérica <string> a un ComboBox

FillCbxProject(DownloadData Down) 
{ 
    BindingSource bindingSource = new BindingSource(); 
    bindingSource.DataSource = Down.ProjectList; 
    cbxProjectd.DataSource = bindingSource; 
} 

En una nota al margen: ¿Es malo pasar una instancia de una clase?

Gracias!

+0

¿Qué ves? ¿Asignó la propiedad DisplayMember? –

Respuesta

26

es necesario llamar al método unen:

cbxProjectd.DataBind(); 

Si esto es para WinForms entonces usted necesita para asegurarse de que lo que tenemos es de ser llamados, las siguientes obras:

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

Aunque puede establecer el DataSource de ComboBox directamente con la lista.

+2

¿Dónde está .DataBind at? No aparece en intellisense como una opción. – Nathan

+0

Es para formularios web, para formularios win su respuesta debería funcionar. Hay algo mal en otra parte de tu programa. Si aisla su código, debería funcionar. –

+0

Acabo de cavar más y encontré una excepción enterrada que de la razón brotó. Gracias a todos. – Nathan

3

esta es la forma más sencilla (funciona correctamente):

List<string> my_list = new List<string>(); 
my_list.Add("item 1"); 
my_list.Add("item 2"); 
my_list.Add("item 3"); 
my_list.Add("item 4"); 
my_list.Add("item 5"); 
comboBox1.DataSource = my_list; 
0
BindingSource bs = new BindingSource(); 
bs.DataSource = getprojectname(); 
comboBox1 = new ComboBox(); 
comboBox1.DataSource = bs; 
0

Aquí es una manera bastante simple que no utiliza BindingSource:

primero, agregue la lista genérica de cuerda , tal vez a una clase "consts/utils":

public static List<string> Months = new List<string> 
{ 
    "Jan", 
    "Feb", 
    "Mar", 
    "Apr", 
    "May", 
    "Jun", 
    "Jul", 
    "Aug", 
    "Sep", 
    "Oct", 
    "Nov", 
    "Dec" 
}; 

Y es como se agrega esas cadenas a un cuadro combinado aquí:

comboBoxMonth.Items.AddRange(UsageRptConstsAndUtils.Months.ToArray<object>()); 
0

Mediante el código de Yuriy Faktorovich anterior como base, aquí es cómo conseguir una lista de fechas en formato LongDateString para un número determinado de semanas, y asignarlos a un cuadro combinado. Esto utiliza "Lunes", pero se puede simplemente reemplazar "Lunes" con cualquier otro DOW para satisfacer sus propósitos:

private void PopulateSchedulableWeeks() 
{ 
    int WEEKS_COUNT = 13; 
    List<String> schedulableWeeks = PlatypusUtils.GetWeekBeginnings(WEEKS_COUNT).ToList(); 
    BindingSource bs = new BindingSource(); 
    bs.DataSource = schedulableWeeks; 
    comboBoxWeekToSchedule.DataSource = bs; 
} 

public static List<String> GetWeekBeginnings(int countOfWeeks) 
{ 
    // from http://stackoverflow.com/questions/6346119/datetime-get-next-tuesday 
    DateTime today = DateTime.Today; 
    // The (... + 7) % 7 ensures we end up with a value in the range [0, 6] 
    int daysUntilMonday = ((int)DayOfWeek.Monday - (int)today.DayOfWeek + 7) % 7; 
    DateTime nextMonday = today.AddDays(daysUntilMonday); 

    List<String> mondays = new List<string>(); 
    mondays.Add(nextMonday.ToLongDateString()); 

    for (int i = 0; i < countOfWeeks; i++) 
    { 
     nextMonday = nextMonday.AddDays(7); 
     mondays.Add(nextMonday.ToLongDateString()); 
    } 
    return mondays; 
} 

... y, si se desea agregar la fecha real para el cuadro combinado, también, puede usar un diccionario como lo siguiente:

int WEEKS_TO_OFFER_COUNT = 13; 
    BindingSource bs = new BindingSource(); 
    Dictionary<String, DateTime> schedulableWeeks = AYttFMConstsAndUtils.GetWeekBeginningsDict(WEEKS_TO_OFFER_COUNT);    bs.DataSource = schedulableWeeks; 
    comboBoxWeekToSchedule.DataSource = bs; 
    comboBoxWeekToSchedule.DisplayMember = "Key"; 
    comboBoxWeekToSchedule.ValueMember = "Value"; 

public static Dictionary<String, DateTime> GetWeekBeginningsDict(int countOfWeeks) 
{ 
    DateTime today = DateTime.Today; 
    // The (... + 7) % 7 ensures we end up with a value in the range [0, 6] 
    int daysUntilMonday = ((int)DayOfWeek.Monday - (int)today.DayOfWeek + 7) % 7; 
    DateTime nextMonday = today.AddDays(daysUntilMonday); 

    Dictionary<String, DateTime> mondays = new Dictionary<String, DateTime>(); 
    mondays.Add(nextMonday.ToLongDateString(), nextMonday); 

    for (int i = 0; i < countOfWeeks; i++) 
    { 
     nextMonday = nextMonday.AddDays(7); 
     mondays.Add(nextMonday.ToLongDateString(), nextMonday); 
    } 
    return mondays; 
} 
Cuestiones relacionadas