【问题标题】:How to create a nested GridView to edit EF Code First relation?如何创建嵌套的 GridView 来编辑 EF Code First 关系?
【发布时间】:2011-09-14 13:04:21
【问题描述】:

我有一个经典的父子关系,我想通过使用 asp:GridView 控件来 CRUD。对父级进行 CRUD 很容易,但挑战是将 asp:GridView 嵌套在能够处理子关系的 asp:GridView 中。

为了使问题更简单,我构建了一个示例。考虑以下 EF 代码:

public class Context : DbContext
{         
    public DbSet<Animal> Animals { get; set; }
    public DbSet<Tag> Tags { get; set; }
}

public class Animal
{
    public int AnimalID { get; set; }
    public string Name { get; set; }
    public virtual IEnumerable<Tag> Tags { get; set; }
}

public class Tag
{
    public int TagID { get; set; }
    public string Name { get; set; }
}

我正在使用asp:Gridview 来查看/编辑Animal 对象:

<asp:GridView runat="server" DataSourceID="animalDataSource" DataKeyNames="AnimalID" AutoGenerateColumns="false">   
    <Columns>
        <asp:BoundField DataField="Description" HeaderText="Description" />
        <asp:CommandField ShowCancelButton="true" ShowEditButton="true" ShowDeleteButton="true" />
    </Columns>
</asp:GridView>

DataSource 与后面的代码绑定:

protected void DataSource_ContextCreating(object sender, EntityDataSourceContextCreatingEventArgs e) 
{    
        var context = new Context();
        e.Context = ((IObjectContextAdapter)context).ObjectContext; } 
}

我想包含一个嵌套的asp:Gridview 作为列之一,以添加/删除/编辑属于该AnimalTag 对象。 我怎样才能做到这一点?

【问题讨论】:

标签: c# asp.net entity-framework ef-code-first crud


【解决方案1】:

BoundField 将指定 DataSource 字段的值显示为文本。通过使用绑定字段,我们可以使用标题文本和数据字段直接绑定数据,而无需使用任何控件。 . TemplateField 允许混合使用 HTML 标记、Web 控件和数据绑定语法。我们可以在模板字段中定义自己的 asp.net 控件。所以基本上你将绑定字段转换为模板列模板列还带有一个编辑模板标签,它为您提供的不仅仅是该 gridview 行的标准编辑是需要的......例如,在编辑模式下,在该行中放置一个下拉列表供我选择 - 可能性无穷无尽

  • 更改模板字段去编辑

  • 模板向字段添加网格控件

  • 添加编辑/删除链接按钮

  • 继续编辑模板下嵌套网格的属性
  • 查找更新、行数据绑定事件等
  • 我认为这会有所帮助

    将 grd1 调暗为 GridViewRow

            Dim gv As GridView
            Dim l1, l2 As Label
            Dim strsql As String
            For Each grd1 In GridView1.Rows
                'find controls of parent gridrow
                l1 = grd1.FindControl("l00")
                l2 = grd1.FindControl("l1")
                gv = grd1.FindControl("gv1")
                strsql = "select file_name from product_file where pname='" & l1.Text & "' and categry='" & l2.Text & "'"
              Dim dt1 As New DataTable()
                Dim da1 As New SqlDataAdapter(strsql, con)
                da1.Fill(dt1)
                gv.DataSource = dt1
                gv.DataBind()
            Next
    

当你填充你的父网格时做这样的事情

【讨论】:

  • 是的,但问题是填充嵌套的网格视图。我需要将过滤的实体或其他东西绑定到 DataSource 并将其用作输入,但到目前为止我还没有让它工作......
  • 看起来是解决这个问题的好方法......对网格中的控件进行一些过滤。它可能只是工作......唯一的问题是我使用的是EF而不是SQL。我会试试你的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多