asp.net gridview binding to deeper property of specific type
-
09-02-2021 - |
题
my webside has a gridview i bind it to a dataset recived from powershell
in this dataset are a lot of different data types.
everything is working fine but for one field i would like to bind a deeper property to the boundfield!
i bind it like this:
c#
GridViewAgentGroups.DataSource = dt;
GridViewAgentGroups.DataBind();
Markup
<asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="True" />
<asp:BoundField HeaderText="Service" ReadOnly="True"
DataField="Identity" />
<asp:BoundField DataField="Description" HeaderText="Description"
ReadOnly="True" />
the boundfield of service binds to data of type: "Microsoft.Rtc.Rgs.Management.RgsIdentity"
it contains an instanceID
and serviceID
propertyand the serviceID
contains a property fullName
!
when i bind it directly like "DataField="Identity"
it shows a very long string with the fullName included!
is there a way to only bind the fullName? like "DataField="Identity.ServiceID.FullName"
? in xml? (this does not work :-)
解决方案
Yes it is possible with TemplateFields
but it depends upon the dataSource
design too. Have a look at this sample:
Markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%#Eval("Name") %>
<%#Eval("GroupName.Name") %>
<%#Eval("GroupName.RegionName.Name") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
public class Region
{
public string Name { get; set; }
}
public class Group
{
public string Name { get; set; }
private Region _region=new Region();
public Region RegionName { get { return _region; } set { _region = value; } }
}
public class Product
{
public string Name { get; set; }
private Group _groupName = new Group();
public Group GroupName { get { return _groupName; } set { _groupName = value; } }
}
public class Products : List<Product>
{
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Region reg1 = new Region() { Name = "North" };
Region reg2 = new Region() { Name = "East" };
Group group1 = new Group() { Name="Group1", RegionName=reg1 };
Group group2 = new Group() { Name = "Group2", RegionName=reg1 };
Group group3 = new Group() { Name = "Group3", RegionName = reg2 };
Products prod = new Products()
{
new Product(){ Name="Product1", GroupName=group1},
new Product(){ Name="Product1", GroupName=group2},
new Product(){ Name="Product2", GroupName=group3},
new Product(){ Name="Product3", GroupName=group1},
new Product(){ Name="Product2", GroupName=group2},
};
GridView1.DataSource = prod;
GridView1.DataBind();
}
}