2011-04-07 58 views
5

我绑定DataGridViewList<T>。我已经设置了设计师Enable adding如何允许在DataGridView上插入?

如果列表为空,我将创建一个空列表,以便显示标题,但它不会为我创建一个空行来添加元素。为什么?我如何使用户能够将值添加到此列表中?

一些代码

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

你为什么不绑定在'BindingList'上? http://msdn.microsoft.com/en-us/library/ms132679.aspx – Jon 2011-04-07 01:54:10

+0

@Jon我不知道'BindingList',我通常不会在WinForms上编码。将它更改为'BindingList'工作,谢谢。 – BrunoLM 2011-04-07 02:00:32

回答

9

首先,DataGridView.AllowUserToAddRows必须true(这是因为你在设计设置它)。

该属性说

如果在DataGridView绑定到数据, 允许用户添加行,如果 此属性和数据源 的IBindingList.AllowNew 属性设置为true。

IBindingList.AllowNew(不设置)也提到:

如果IList.IsFixedSize或 IList.IsReadOnly是真实的,这 属性返回false。

由于您绑定到IEnumerable,我相信IsReadOnlyfalse。尝试将列表公开为List<T>并绑定到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

非常好,谢谢。这使我的生活更容易:D – BrunoLM 2011-04-07 02:10:47

0

添加到乔恩的答案:BindingList<T>有一个事件,AddingRow,你可以听,要specifiy要添加的项目:

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

该属性将是错误的,如果你有DataGridView中。 AllowUserToAddRows = true;但没有绑定类的默认构造函数。 添加默认值,它应该工作

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