当DataSource是LIst<&a;>时,如何使DataGridView在WinForms中可编辑

时间:2017-08-03 15:25:37

标签: winforms entity-framework datagridview

我可以执行以下操作,但它将我的DataGridView创建为Readonly。

var entries = (from e in dbContext.Entries
 where e.FromWord == "test"
  select new {
    EntryID = e.EntryID,
    WordClass = e.WordClass,
    Plural = e.Plural,
    FromWord = e.FromWord,
    LettersOnly = e.LettersOnly,
    Notes = e.notes
  }
).ToList();
dataGridView1.DataSource = entries; 

如何使DataGridView可编辑?

如果我删除ToList(),我会收到一条错误消息,说我必须使用DataSet作为DataSource。有没有一种简单的方法来创建DataSet。我正在使用Entity-Framework和Database-First。

1 个答案:

答案 0 :(得分:0)

@Nobody,在上面的评论中,帮助我通过此链接回答了我的问题Editable DataGridView bound to a list

我创建了这个模型类:

  public class RowEntry
  {
    public int EntryID {get; set;}
    public string WordClass {get; set;}
    public bool Plural {get; set;}
    public string FromWord {get; set;}
    public string LettersOnly {get; set;}
    public string Notes { get; set; }
  }

然后只需将linq查询更改为 - 删除匿名类:

List<RowEntry> entries = (from e in dbContext.Entries
     where e.FromWord == "test"
      select new RowEntry {
        EntryID = e.EntryID,
        WordClass = e.WordClass,
        Plural = e.Plural,
        FromWord = e.FromWord,
        LettersOnly = e.LettersOnly,
        Notes = e.notes
      }
    ).ToList();
dataGridView1.DataSource = entries;

DataGridView现在可以编辑。我猜测匿名List类型的范围太有限,无法由DataGridView类编辑。