2017-10-15 66 views
2

DataGridView必须满足什么条件才能由用户编辑GUI?如按F2进行修改,选择要删除的行或添加新行?C#GUI可编辑DataGridView

当我将DataGridView.DataSource绑定到本地集合对象(如List<T>)时,我可以执行所有这三项操作。

当我将DataGridView.DataSource绑定到DataTableDataView时,我也可以用图形方式完成所有这三个操作。

但是,当我结合DataGridView.DataSourceDbSet<T>.ToList<T>()DbSet<T>.ToArray<T>()Entity Framework),I只能修改现有的行的非主键值,尽管我已经启用删除通过DataGridView的向导中添加功能,和专门设置AllowUserToAddRowsAllowUserToDeleteRowstrue。运行时,应用程序不会显示星号符号,表示可添加新行。删除行也是不可能的。

但是,数据显示正确。

所以,我很困惑。上述数据源的哪些特征可能会导致GUI中的不同行为?

由于

回答

2

DataGridView控制允许用户如果两个AllowUserToAddRow被设置为真和底层数据源实现IBindingList返回AllowNew作为真正添加行。类似的删除规则也是如此。

你可以看看AllowUserToAddRowsInternalAllowUserToDeleteRowsInternal内部方法的源代码。

  • List<T>

    基于数据源作为一个结论,这些都是允许的操作编辑

  • BindingList<T>:添加,编辑,删除(对于添加,T应该有参数的构造函数)
  • Array :编辑
  • DataTable:添加,编辑,删除
  • BindingSource:取决于und erlying数据源的BindingSource。如果它是IBindingList的实现,则从它那里请求,否则如果列表不是FixedSize那么允许所有操作,否则只允许编辑。例如,如果您将List<T>设置为绑定源的数据源,然后将绑定源设置为数据网格视图的数据源,则该列表将被允许用于所有操作。
  • IBindingList:从实施中询问。
+0

谢谢。对于列表这个根本不是IBindingList实现的数据源,是否意味着AllowUserToAddRows或AllowUserToDeleteRows属性足以确定是否允许添加或删除行?列表似乎支持添加除了您的结论中的编辑和删除。谢谢 –

+0

编辑'DataGridView'中'List '的唯一方法是使用'BindingSource'。根据绑定源规则,如果您将'List '设置为'BindingSource'的数据源,然后将'BindingSource'设置为'DataGridView'的数据源,那么您可以*添加*,*编辑*和*删除*清单'的项目。 –

+1

除了上述支持* Add *的条件之外,别忘了使用公共无参数的构造函数(通常在普通类中有这个)。 –

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); 
     } 
    } 
    } 
} 
  • 当你想更新数据库只需创建一个更新命令,并像上面所看到的那样执行它。