C# GUI 可编辑 DataGridView

4
什么条件必须满足才能让用户通过GUI编辑DataGridView?例如按下F2进行修改,选择一行进行删除或添加新行?
当我将DataGridView.DataSource绑定至本地集合对象,例如List时,我可以执行这三个动作。
当我将DataGridView.DataSource绑定至DataTable或DataView时,我同样可以使用图形界面来实现这三个动作。
但是,当我将DataGridView.DataSource绑定至DbSet.ToList()或DbSet.ToArray()(Entity Framework)时,尽管我已通过DataGridView向导启用了“删除”和“添加”功能,并明确设置了AllowUserToAddRows和AllowUserToDeleteRows为true,但我只能修改现有行的非主键值。运行应用程序时,它不会显示星号符号,表明能够添加新行。也无法删除行。
然而,数据显示正确。
所以,我感到困惑。上述数据源的哪些特征可能导致GUI中的不同行为?
谢谢。
2个回答

2
DataGridView控件允许用户添加行,如果AllowUserToAddRow设置为true,并且底层数据源实现了返回AllowNew为true的IBindingList。删除也有类似的规则。
您可以查看AllowUserToAddRowsInternalAllowUserToDeleteRowsInternal内部方法的源代码。
总之,这些是基于数据源允许的操作:
  • List<T>:编辑
  • BindingList<T>:添加、编辑、删除(对于添加,T应该有无参数构造函数)
  • Array:编辑
  • DataTable:添加、编辑、删除
  • BindingSource:取决于BindingSource的底层数据源。如果它是IBindingList的实现,则从中询问,否则如果列表不是FixedSize,则允许所有操作,否则仅允许编辑。因此,例如,如果您将List<T>设置为绑定源的数据源,然后将绑定源设置为数据网格视图的数据源,则列表将允许进行所有操作。
  • IBindingList:从实现中询问。

编辑 DataGridView 中的 List<T> 的唯一方法是使用 BindingSource。根据绑定源规则,如果将 List<T> 设置为 BindingSource 的数据源,然后将 BindingSource 设置为 DataGridView 的数据源,则可以添加、编辑和删除 List<T> 的项目。 - Reza Aghaei
1
除了上述支持Add的条件外,不要忘记拥有公共无参数构造函数(通常在普通类中都会有)。 - Reza Aghaei
非常感谢您的帮助。但我仍然感到困惑。我理解您关于List<T>的Add操作不受支持的推理,但既然它也没有实现IBindingList.AllowRemove,为什么删除操作是允许的呢? - user6338533
1
不客气。当您将DataGridView绑定到DataTable时,实际上是将其绑定到默认视图,该视图是实现接口的DataView。 - Reza Aghaei
1
Reza,非常感谢你。现在我对这个有了更好的理解。你真棒。 - user6338533
显示剩余8条评论

0
  1. 填充dataTable并将其用作datagridview的绑定源

1.1 在datagridview中进行更改...

public void DAL_UpdateStudentsTable(DataTable table) //DAL represents 3-tyer architecture (so data access layer)
{
  using (SqlConnection sqlConn = new SqlConnection(connString))
  {
    using (SqlCommand cmd = new SqlCommand())
    {
      cmd.CommandText = @"UPDATE Students SET " +
                "StudentID = @id, " +
                "FirstName = @first, " +
                "LastName = @last, " +
                "Birthday = @birthday, " +
                "PersonalNo = @personal " +
                "WHERE StudentID = @oldId";
      cmd.Parameters.Add("@id", SqlDbType.Int, 5, "StudentID");
      cmd.Parameters.Add("@first", SqlDbType.VarChar, 50, "FirstName");
      cmd.Parameters.Add("@last", SqlDbType.VarChar, 50, "LastName");
      cmd.Parameters.Add("@birthday", SqlDbType.DateTime, 1, "Birthday");
      cmd.Parameters.Add("@personal", SqlDbType.VarChar, 50, "PersonalNo");
      SqlParameter param = cmd.Parameters.Add("@oldId", SqlDbType.Int, 5, "StudentID");
      param.SourceVersion = DataRowVersion.Original;
      cmd.Connection = sqlConn;
      using (SqlDataAdapter da = new SqlDataAdapter())
      {
        da.UpdateCommand = cmd;
        da.Update(table);
      }
    }
  }
}

当您想要更新数据库时,只需创建一个更新命令并像上面所示那样执行即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接