当数据来自多个相关表时,在ASP.NET DataGrid中实现编辑

时间:2013-02-25 06:01:11

标签: asp.net datagrid sqldatasource

今天在我的一个客户项目上工作时,我想出了一个我无法找到解决方案的问题。所以我把它扔给你们。

我使用的是数据绑定GridView控件,SqlDataSource的代码同样如下:

<asp:SqlDataSource ID="SqlDataSource_familyMembers" runat="server" 
     ConnectionString="<%$ ConnectionStrings:VBAT_dbConnectionString %>" 
     SelectCommand="
       select 
          a.memberid,a.fristName,a.lastname,a.gender,a.dob,
          b.relation as [Relation with Family Head],
      c.districtname,d.statename,e.countryname,a.mobno,f.occupation,a.ismaried 
      from 
         family_members_info as a
      left outer join
         master_relations as b
      on
         a.RelationWithFamilyHead=b.relationid
      join
         master_district as c
      on 
         a.cadistrict=c.districtid
      join
         master_state as d
      on 
        a.castate=d.stateid
     join
        master_country as e
     on 
        a.cacountry=e.countryid
     join
       master_occupation as f
     on
       a.occupation=f.occupationid
     where 
         familyid=@familyid" 
   UpdateCommand="
         update 
             family_members_info 
         set                    
            firstName=@firstname, lastname=@lastName, dob=@dob,
            relationwithfamilyhead=@relationwithfamilyhead,cadistrict=@cadistrict, 
            castate=@castate, cacountry=@cacountry,mobno=@mobno,occupation=@occupation 
         where 
            memberID=@memberID">
  <SelectParameters>                    
    <asp:ControlParameter ControlID="HiddenField1" Name="familyid"   PropertyName="Value" />
  </SelectParameters>
  <UpdateParameters>
      <asp:Parameter Name="firstname"  />
      <asp:Parameter Name="lastName" />
      <asp:Parameter Name="dob" />
      <asp:Parameter Name="relationwithfamilyhead" />
      <asp:Parameter Name="cadistrict" />
      <asp:Parameter Name="castate" />
      <asp:Parameter Name="cacountry" />
      <asp:Parameter Name="mobno" />
      <asp:Parameter Name="occupation" />
      <asp:Parameter Name="memberID" />
   </UpdateParameters>
</asp:SqlDataSource>

从Select查询中可以看出,数据来自几个相关的表,一切正常,除非用户想要编辑数据。

对于所有列,默认情况下,GridView显示文本框,而它应显示外键列的DropdownList。

如果有人可以为我指导一个可能的解决方案,那将是很好的帮助。

1 个答案:

答案 0 :(得分:1)

要实现您的目标,请遵循以下高级步骤:

  1. 网格视图的模板 - 为网格视图中的每列创建TemplateField项,适用于ItemTemplateEditItemTemplate
  2. 对于ID字段,请将EditItemTemplate的控件类型指定为DropDownList
  3. 创建一个SqlDataSource或您选择的任何其他数据绑定方法,并将其绑定到DropDownList以从所需表中检索ID和值
  4. DataValueField的{​​{1}}设为 ID ,将DropDownList设为显示值
  5. 以上是上述各点的工作示例 - Filtering Dropdownlist populated from sqldatasource