2011-04-07 9 views
5

Estoy vinculando un DataGridView desde un List<T>. Me he puesto en el diseñador Enable adding.¿Cómo se permite la inserción en DataGridView?

Si la lista es nula, estoy creando una lista vacía para que se muestren los encabezados, pero no está creando una línea vacía para que pueda agregar elementos. ¿Por qué? ¿Cómo puedo permitir que el usuario agregue valores a esta lista?

Parte del código

public IEnumerable<Value> ValueList 
{ 
    get; 
    set; 
} 

private void Form1_Load(object sender, EventArgs ev) 
{ 
    if (ValueList == null) 
    { 
     ValueList = new List<Value>(); 
    } 

    dataGrid.DataSource = ValueList; 
} 
+0

¿Por qué no vinculante sobre un 'BindingList'? http://msdn.microsoft.com/en-us/library/ms132679.aspx – Jon

+0

@Jon No sabía acerca de 'BindingList', generalmente no código en winforms. Cambiarlo a un 'BindingList' funcionó, gracias. – BrunoLM

Respuesta

9

En primer lugar, debe haber DataGridView.AllowUserToAddRowstrue (y lo es ya que está configurando en el diseñador).

Esa propiedad dice

Si el DataGridView está enlazado a datos, se permite que el usuario añada casillas si tanto esta propiedad y la propiedad IBindingList.AllowNew los datos de origen se establecen en true.

IBindingList.AllowNew (que no es ajustable) también menciona:

Si IList.IsFixedSize o IList.IsReadOnly es cierto, este propiedad devuelve falso.

Dado que va a enlazar a un IEnumerable, creo que es IsReadOnlyfalse. Intente exponer la lista como List<T> y vinculante a BindingList<T>.

public List<Value> ValueList 
{ 
    get; 
    set; 
} 

private void Form1_Load(object sender, EventArgs ev) 
{ 
    if (ValueList == null) 
    { 
     ValueList = new List<Value>(); 
    } 

    dataGrid.DataSource = new BindingList<Value>(ValueList); 
} 
+0

Excelente, gracias. Esto hace mi vida mucho más fácil: D – BrunoLM

0

Agregando a la respuesta de Jon: BindingList<T> tiene un evento, AddingRow, que se puede escuchar, a specifiy el elemento que se ha añadido:

AddHandler _bindingList.AddingNew, Sub(s, args) 
              args.NewObject = New TicketItem("dawg") 
             End Sub 
1

Esa propiedad será falsa si tiene DataGridView. AllowUserToAddRows = verdadero; pero no tiene constructor predeterminado para su clase de enlace. Añadir por defecto y debería funcionar

public class atsTableInclude 
{ 
    // keep this to allow user to add row 
    public atsTableInclude() { } 

    public atsTableInclude(string p, bool u) 
    { 
     Prefix = p; 
     Use = u; 
    } 

    public string Prefix { get; set; } 
    public bool Use { get; set; } 
} 

    public Sorting.SortableBindingList<T> FillAtsList<T>(string jsonfile) where T : class 
    { 
     if (!File.Exists(jsonfile)) 
     { 
      MessageBox.Show(jsonfile, "File not found"); 
      return null; 
     } 

     try 
     { 
      // load json from file 
      using (StreamReader r = new StreamReader(jsonfile)) 
      { 
       string json = r.ReadToEnd(); 
       var res = JsonConvert.DeserializeObject<List<T>>(json); 
       return new Sorting.SortableBindingList<T>(res);     
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message, "Cannot load json", MessageBoxButtons.OK, MessageBoxIcon.Error); 
     } 
     return null; 
    } 
    private void frmATS_Load(object sender, EventArgs e) 
    {   
     string jsonfile2 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "atsTableInclude.json"); 
     dataGridView2.DataSource = FillAtsList<atsTableInclude>(jsonfile2); 
    } 
Cuestiones relacionadas