【问题标题】:How to bind a List<string[]> to a gridview?如何将 List<string[]> 绑定到 gridview?
【发布时间】:2012-10-01 19:51:11
【问题描述】:

我在任何地方都找不到答案...我有一个 List 填充如下:

...
while (myReader.Read())
{
    string[] row = new string[myInt];

    for (int i = 0; i < myInt; i++)
    {
        row[i] = myReader[i].ToString();
    }

    myList.Add(row);    
}
...

如何将此列表绑定到具有 TemplateField 列的网格视图?

【问题讨论】:

  • mygridview.datasource = mylist;mygridview.databind();
  • @JonH 如何引用 TemplateField 中的列?它可以将索引用作字段名称吗?

标签: c# asp.net list data-binding gridview


【解决方案1】:

更简单的方法是创建一个匿名类并将其绑定到您的 GridView。示例:

var query = from c in row
            select new { SomeProperty = c };

GridView.DataSource=query;
GridView.DataBind();

【讨论】:

  • 这行得通。但如果我这样做,我将如何处理 gridview 分页?此数据源不支持服务器端数据分页。
  • 你没有。如果您需要为单个列表利用所有这些复杂功能,则需要重新考虑存储方法。您需要分页的单个字符串的多少行?
【解决方案2】:

您始终可以使用GridViewRowDataBound 事件

<asp:GridView ID="gridView1" runat="server" 
    OnRowDataBound="gridView1_DataBound">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Label ID="myLabel" runat="server"></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

绑定数据时:

var myStrings = new List<string[]>
                      {
                          new [] { "hello", "bye"},
                          new [] { "1", "2"}
                      };

gridView1.DataSource = myStrings;
gridView1.DataBind();

RowDataBound事件:

public void gvDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType != DataControlRowType.DataRow)
    {
        return;
    }

    var item = (string[]) e.Row.DataItem;
    Label myLabel = e.Row.FindControl("myLabel") as Label;
    myLabel.Text = item[0];
}

【讨论】:

    【解决方案3】:

    像往常一样简单地使用数据绑定。要引用该列,它默认按索引进行。像这样:

    <asp:GridView runat="server" AutoGenerateColumns="false" ID="rpt">
    <Columns>
        <ItemTemplate>
            <%# Eval("Key") %>
        </ItemTemplate>
    </Columns>
    </asp:Repeater>
    
    Dictionary<string, string> lst = new Dictionary<string, string>();
    lst.Add("test", String.Empty);
    lst.Add("test1", String.Empty);
    this.rpt.DataSource = lst;
    this.rpt.DataBind();
    

    【讨论】:

    • gridview 使用 TemplateField 列
    • 哦,我明白你的意思了。使用中继器。
    • 我想这也不起作用。 K,你可以做的另一件事是把它变成一本字典
    • 字典真的很轻,所以你不必去数据表的路由。
    猜你喜欢
    • 2011-02-10
    • 1970-01-01
    • 2010-10-05
    • 1970-01-01
    • 2021-06-28
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    相关资源
    最近更新 更多