How to populate asp:GridView from code?

冷暖自知 提交于 2019-12-06 07:55:28

问题


I have a List<string[]> items list filled with arrays of strings in my code. On the ASPX page, I have added a new grid view control:

<asp:GridView ID="ProductList" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ProductID" EnableViewState="False">
  <Columns>
    <asp:BoundField DataField="ProductName" HeaderText="Product" SortExpression="ProductName" />
    <asp:BoundField DataField="CategoryName" HeaderText="Category" ReadOnly="True" SortExpression="CategoryName" />
    <asp:BoundField DataField="SupplierName" HeaderText="Supplier" ReadOnly="True" SortExpression="SupplierName" />
    <asp:BoundField DataField="UnitPrice" DataFormatString="{0:C}" HeaderText="Price" HtmlEncode="False" SortExpression="UnitPrice" />
    <asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued" SortExpression="Discontinued" />
  </Columns>
</asp:GridView>

I know that I should specify the DataSourceID attribute for the grid view in a fashion similar to this:

<asp:GridView ... `DataSourceID="ObjectDataSource1" ... > 
</asp:GridView>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" OldValuesParameterFormatString="original_{0}" SelectMethod="GetProducts" TypeName="ProductsBLL">
</asp:ObjectDataSource>

But, I don't know what do OldValuesParameterFormatString, SelectMethod and TypeName attributes represent. Also, I don't have the database to bind to, I just have the list of string arrays named items. Can you help me populate the grid view? It is not necessary to do it through the binding at all. Thanks!


回答1:


You don't even need an ObjectDataSource. At Page_Load in the codebehind, you can parse through the string array list and create a DataTable on the fly.

Make sure to wrap this around a Not Page.IsPostback so that it doesn't rebind on postback.

List<string[]> stringList = null;

DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add("ProductName", System.Type.GetType("System.String"));
dt.Columns.Add("CategoryName", System.Type.GetType("System.String"));
dt.Columns.Add("SupplierName", System.Type.GetType("System.String"));
dt.Columns.Add("UnitPrice", System.Type.GetType("System.Double"));
dt.Columns.Add("Discontinued", System.Type.GetType("System.String"));

foreach (string[] s in stringList) {
    foreach (string str in s) {
        dr = dt.NewRow();
        dr["ProductName"] = s[0];
        dr["CategoryName"] = s[1];
        dr["SupplierName"] = s[2];
        dr["UnitPrice"] = s[3];
        dr["Discontinued"] = s[4];
        dt.Rows.Add(dr);
    }
}

dt.AcceptChanges();
ProductList.DataSource = dt;
ProductList.DataBind();



回答2:


Edit: You'll have to change some of this code to match your needs. I'm making assumptions on the data types stored in your string[] based on the GridView code you provided.

You'll want to look into creating a class to use for your items, instead of a string[]. Maybe something like:

public class MyObject
{
    public string ProductName { get; set; }
    public string CategoryName { get; set; }
    public string SupplierName { get; set; }
    public decimal UnitPrice { get; set; }
    public bool Discontinued { get; set; }
}

You'd then need something to translate the string[] into MyObject:

private MyObject ConvertToMyObject(string[] values)
{
    var myObject = new MyObject();
    myObject.ProductName = values[0];
    myObject.CategoryName = values[1];
    myObject.SupplierName = values[2];

    decimal unitPrice;
    if (decimal.TryParse(values[3], out unitPrice))
    {
        myObject.UnitPrice = unitPrice;
    }

    bool discontinued;
    if (boo.TryParse(values[4], out discontinued))
    {
        myObject.Discontinued = values[4];
    }
}

Then you could use that method in your code and then bind:

protected void Page_Load(parameters here)
{
    if (IsPostback)
    {
        var myObjects = new List<MyObject>();
        foreach (string[] values in items)
        {
            myObjects.Add(ConvertToMyObject(values));
        }

        ProductList.DataSource = myObjects;
        ProductList.DataBind();
    }
}

Like I said in the comment, make sure you have access to items in the Page_Load event handler. Also, I typed this from memory, forgot the parameters in Page_Load. You most likely already have a Page_Load handler in your code behind though.




回答3:


You can try this

List<string[]> items = List<string[]>();
//add items to List

GridView1.DataSource = items;
GridView1.DataBind();

Your GridView

<asp:GridView runat="server" ID="GridView1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
   <asp:Label ID="stringLabel" Text="<%# Container.DataItem %>" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>


来源:https://stackoverflow.com/questions/12958457/how-to-populate-aspgridview-from-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!