【问题标题】:Populating around 10 Gridviews using one data source ASP C#使用一个数据源 ASP C# 填充大约 10 个 Gridview
【发布时间】:2018-06-22 01:27:19
【问题描述】:

我需要根据过滤器值(列)将一个表中的数据显示到 10 个网格视图。

让我们说颜色。所以粉色网格视图应该只显示颜色列中有粉色的项目。

目前我有一个 Gridview 绑定(在 ASP 中)到一个数据源。我正在更新代码隐藏中的数据源。

类似这样的:

 String selectcommand = Select * from table where subject = "Pink" 
 sqlDatasource1.SelectCommand= (selectcommand);
 mygv.Bind();

显然,重复相同的代码 10 次是一个非常糟糕的主意,每个主题一个。有没有更好的方法来做我所追求的。

主要问题是我可以在更改颜色后将相同的数据源与许多网格视图一起使用吗?

解决方案一

我将所有网格视图绑定到一个数据源,而不用担心按颜色过滤。

然后在每个gridview的gridview rowdatabound事件中添加类似这样的内容

if e.Row.RowType = DataControlRowType.DataRow Then

   if e.Row.DataItem("colour") = "pink" then e.Row.visible = False

还有其他建议吗?

【问题讨论】:

  • mygv 是什么...好像肯定少了一些代码
  • mygv.是一个网格视图。这只是 sudo 代码,让您了解我想要做什么。
  • 它是如此 sudo 以至于我们不知道您要做什么......
  • 所有这些gridviews是在asp页面中定义的还是在代码中动态构建的?那些 sqlDatasources 也一样。
  • 我已经解释了我想要做什么。 10 Gridview 控件,显示来自同一个表的数据,但根据其中一列中的值对其进行过滤。

标签: c# asp.net gridview


【解决方案1】:

您说得对,复制代码不是一个理想的选择。但是,正如 cmets 中提到的,您可以使用循环遍历一组数据的中继器(因此您只需查询一次数据库),然后在内部绑定一个 GridView 模板。

Aspx 代码可能如下所示:

<asp:Repeater ID="repColors" OnItemDataBound="repColors_ItemDataBound" runat="server">
    <ItemTemplate>
        <asp:GridView ID="gvColor" runat="server" />
    </ItemTemplate>
</asp:Repeater>

Repeater 有一个 OnItemDataBound,它将用于在其 ItemTemplate 中查找和绑定 GridView。此 GridView 很简单,但可以根据您的用例所需的复杂程度。

aspx.cs 页面将包含您需要将所有主题加载到转发器中的代码,然后使用 OnItemDataBound 事件处理程序绑定网格视图。

protected void Page_Init(object sender, EventArgs e)
{
    var data = GetColors();
    var dataByColors = data.ToLookup(c => c.Subject, StringComparer.OrdinalIgnoreCase);

    repColors.DataSource = dataByColors;
    repColors.DataBind();
}

protected void repColors_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        var gv = e.Item.FindControl("gvColor") as GridView;

        gv.DataSource = e.Item.DataItem;
        gv.DataBind();
    }
}

public class Colors
{
    public string Text { get; set; }
    public string Subject { get; set; }
}

private IEnumerable<Colors> GetColors()
{
    yield return new Colors { Text = "Color1", Subject = "Blue" };
    yield return new Colors { Text = "Color2", Subject = "Pink" };
    yield return new Colors { Text = "Color3", Subject = "Blue" };
    yield return new Colors { Text = "Color4", Subject = "Red" };
    yield return new Colors { Text = "Color5", Subject = "Pink" };
}

Page_Load 用于从数据库中获取所有数据。然后我们使用 LINQ 按主题对其进行分组,生成的对象类似于:

{"Blue": {Color1, Color3}}
{"Pink": {Color2, Color5}}
{"Red": {Color4}}

然后将其绑定到中继器。中继器的 ItemDataBound 事件获取每个单独的数据项(这是一个键和颜色列表)并将其绑定到它能够在中继器模板中找到的 GridView。默认情况下,ILookup 接口将枚举它维护的项目列表。这允许它直接传递给GridView.DataSource,我们无需担心尝试将其转换为列表或任何东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多