asp.net中重复的gridview列

时间:2014-01-24 23:59:56

标签: c# asp.net gridview datagridview

我使用GridView显示我希望在表中每列两次的数据。这意味着当1列已满时,其余数据将放入下一列。像这样的东西:

enter image description here

有可能吗?

1 个答案:

答案 0 :(得分:0)

1。一种解决方案是在绑定到GridView之前对数据进行整形。

添加一个类以保持双倍果实:

class MyDoubleObject
{
    public string Fruit1 { get; set; }
    public string Color1 { get; set; }
    public string Fruit2 { get; set; }
    public string Color2 { get; set; }
}

在绑定之前转换数据:

//Dummy test data
var lstFruits = new List<MyFruit>()
{
    new MyFruit {Fruit = "Banana", Color = "Yellow"},
    new MyFruit {Fruit = "Orange", Color = "Orange"},
    new MyFruit {Fruit = "Apple", Color = "Green"},
    new MyFruit {Fruit = "Apple", Color = "Red"},
    new MyFruit {Fruit = "Orange", Color = "Green"},
    new MyFruit {Fruit = "Pear", Color = "Green"},
    new MyFruit {Fruit = "Pear", Color = "Pale"}
};

var myNewList = new List<MyDoubleObject>();
int count = lstFruits.Count;

for (int i = 0; i < count; i++)
{
    var newObject = new MyDoubleObject();
    newObject.Fruit1 = lstFruits[i].Fruit;
    newObject.Color1  = lstFruits[i].Color;
    if (count > i + 1)
    {
        newObject.Fruit2 = lstFruits[i+1].Fruit;
        newObject.Color2 = lstFruits[i+1].Color;
    }

    myNewList.Add(newObject);
    i++;
}

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

输出:

enter image description here

2。或者您可以使用非常灵活的Repeater。

在标记中,您的转发器可能如下所示:

<asp:Repeater ID="rptFruit" runat="server" >
    <HeaderTemplate>
        <table>
            <tr>
                <th>Fruit</th>
                <th>Color</th>
                <th>Fruit</th>
                <th>Color</th>
            </tr>
            <tr>
    </HeaderTemplate>
    <ItemTemplate>
        <%# (Container.ItemIndex != 0 && Container.ItemIndex %2==0)? "</tr><tr>": "" %>
        <td><%#Eval("Fruit") %></td>
        <td><%#Eval("Color") %></td>
    </ItemTemplate>
    <FooterTemplate>
        </tr></table>
    </FooterTemplate>
</asp:Repeater>

在代码中你就像这样绑定:

//Dummy test data
var lstFruits = new List<MyFruit>()
{
    new MyFruit {Fruit = "Banana", Color = "Yellow"},
    new MyFruit {Fruit = "Orange", Color = "Orange"},
    new MyFruit {Fruit = "Apple", Color = "Green"},
    new MyFruit {Fruit = "Apple", Color = "Red"},
    new MyFruit {Fruit = "Orange", Color = "Green"},
    new MyFruit {Fruit = "Pear", Color = "Green"},
    new MyFruit {Fruit = "Pear", Color = "Pale"}
};

rptFruit.DataSource = lstFruits;
rptFruit.DataBind();