How to get custom class in DataTable column displayed as class.ToString() in GridView?
I've got a DataTable that I'm binding to a GridView like so:
DataTable WADSItems = new DataTable();
WADSItems.Columns.Add("Category", Type.GetType("System.String"));
WADSItems.Columns.Add("Quantity", Type.GetType("System.Int32"));
WADSItems.Columns.Add("Units", Type.GetType("Tables.PlantWADSUnitsList"));
gvPlantWADS.DataSource = WADSItems;
gvPlantWADS.DataBind();
The first two columns show up fine, but the 3rd o开发者_Python百科ne does not, even though the class PlantWADSUnitsList implements the ToString() override function. What's going on here and how can I get it to display?
Your question is missing some details, but here a working example based on the assumption that Tables.PlantWADSUnitsList has the following structure:
public class PlantWADSUnitsList
{
public string Name { get; set; }
public string Desc { get; set; }
public override string ToString()
{
return Name + ": " + Desc;
}
}
Using a gridview definition like this:
<asp:GridView ID="gvPlantWADS" runat="server" />
makes the rendered page only have two columns, one for category and one for quantity. I'm assuming this is your problem.
But if you disable AutoGenerateColumns and specify the columns yourself it works fine:
<asp:GridView ID="gvPlantWADS" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Category" DataField="Category" />
<asp:BoundField HeaderText="Quantity" DataField="Quantity" />
<asp:BoundField HeaderText="Units" DataField="Units" />
</Columns>
</asp:GridView>
精彩评论