我需要根据过滤器值(列)将数据从一个表显示到10个网格视图。
让我们说颜色。因此粉红色网格视图应仅显示具有粉红色列的项目。
目前我有一个Gridview绑定(在ASP中)到一个数据源。我正在更新代码隐藏中的数据源。
这样的事情:
String selectcommand = Select * from table where subject = "Pink"
sqlDatasource1.SelectCommand= (selectcommand);
mygv.Bind();
显然,重复相同的代码10次,每个主题一个是非常糟糕的主意。有没有更好的方式来做我想要的事情。
主要问题是我可以在更改颜色后使用与多个网格视图相同的数据吗?
解决方案一
我将所有gridviews绑定到一个数据源,而不用担心按颜色过滤。
然后在每个gridview的gridview rowdatabound事件中添加类似这样的内容
if e.Row.RowType = DataControlRowType.DataRow Then
if e.Row.DataItem("colour") = "pink" then e.Row.visible = False
还有其他建议吗?
答案 0 :(得分:0)
你是对的,复制代码不是一个理想的选择。但是,如评论中所述,您可以使用循环遍历分组数据集的转发器(因此您只需查询数据库一次),然后在内部绑定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事件处理程序绑定gridview所需的代码。
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事件获取每个单独的数据项(这是一个键和一个颜色列表),并将其绑定到它能够在Repeater模板中找到的GridView。 ILookup接口默认枚举它维护的项目列表。这允许它直接传递给GridView.DataSource
,我们不必担心尝试将其转换为List或任何内容。