如何从代码中填充asp:GridView?

Bor*_*ris 3 asp.net data-binding binding gridview populate

我的代码中有一个List<string[]> items填充了字符串数组的列表.在ASPX页面上,我添加了一个新的网格视图控件:

<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>
Run Code Online (Sandbox Code Playgroud)

我知道我应该以类似于这样的方式为网格视图指定DataSourceID属性:

<asp:GridView ... `DataSourceID="ObjectDataSource1" ... > 
</asp:GridView>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" OldValuesParameterFormatString="original_{0}" SelectMethod="GetProducts" TypeName="ProductsBLL">
</asp:ObjectDataSource>
Run Code Online (Sandbox Code Playgroud)

但是,我不知道该怎么做OldValuesParameterFormatString,SelectMethodTypeName属性表示.另外,我没有要绑定的数据库,我只有名为的字符串数组列表items.你能帮我填充网格视图吗?根本没有必要通过绑定来完成.谢谢!

dan*_*yim 6

你甚至不需要ObjectDataSource.在代码隐藏中的Page_Load中,您可以解析字符串数组列表并动态创建DataTable.

确保将其包裹在一起,Not Page.IsPostback以便它不会在回发时重新绑定.

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();
Run Code Online (Sandbox Code Playgroud)