如何在DataGrid

时间:2015-06-16 19:59:33

标签: c# asp.net sql-server datagrid

我有一个客户要求为特定产品更改HeaderText,而不是" TL Price / 1000 sq ft"它说“每包TL价格”。

在上一页上,客户可以选择多个类别,然后在此页面上显示这些类别的产品列表。只有某些productId需要更改其类别表。

我遇到的问题是更改headerText DataGrid必须反弹,这是在绑定转发器时完成的。我尝试过改变' OnItemDataBound'但仍然没有结果。



 <asp:Repeater ID="repProducts" runat="server" OnItemDataBound="repProducts_ItemDataBound">
        <ItemTemplate>
            <section class="grey">
                <div class="container">
                    <div class="row">
                        <div class="col-sm-4">
                            <h2 class="h1">
                                <img class="img-responsive" src='<%# DataBinder.Eval(Container.DataItem, "TitleImage") %>' visible="<%# DataBinder.Eval(Container.DataItem, "TitleImage").ToString().Length > 0 %>" alt="<%# DataBinder.Eval(Container.DataItem, "Name") %>" />
                                <small visible="<%# DataBinder.Eval(Container.DataItem, "EffectiveDate").ToString().Length > 0 %>">
                                    <%# DataBinder.Eval(Container.DataItem, "EffectiveDate") %>
                                </small>
                            </h2>
                        </div>
                        <div class="col-sm-3 col-sm-offset-2">
                            <p visible="<%# DataBinder.Eval(Container.DataItem, "InformationLink").ToString().Length > 0 %>">
                                <a target="_blank" href="<%# DataBinder.Eval(Container.DataItem, "InformationLink") %>" class="btn btn-block btn-grey"><asp:Literal ID="litProductInformation" runat="server" Text="Product Information" meta:resourcekey="litProductInformationResource2"></asp:Literal> <i class="fa fa-caret-right"></i></a>
                            </p>
                        </div>
                        <div class="col-sm-3">
                            <p>
                                <button type="button" onclick="downloadPDF([<%# DataBinder.Eval(Container, "DataItem.ProductID") %>]);" class="btn btn-block btn-roxul"><asp:Literal ID="litDownloadSingle" runat="server" Text="Download PDF" meta:resourcekey="litDownloadSingleResource1"></asp:Literal> <i class="fa fa-caret-right"></i></button>
                            </p>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xs-12">
                            <div class="table-responsive">
                                <asp:DataGrid ID="dgProduct" AutoGenerateColumns="False" runat="server" DataSource='<%# DataBinder.Eval(Container.DataItem, "ProductDetails") %>' CssClass="table table-striped table-bordered products" meta:resourcekey="dgProductResource2" OnItemDataBound="dgProduct_ItemDataBound">
                                    <HeaderStyle CssClass="thead" />
                                    <Columns>
                                        <asp:BoundColumn DataField="ItemNumber" HeaderText="Item #" meta:resourcekey="colItemNumber"></asp:BoundColumn>
                                        <asp:BoundColumn DataField="UPC" HeaderText="UPC Code" meta:resourcekey="colUpcCode"></asp:BoundColumn>
                                        <asp:BoundColumn DataField="Stock" HeaderText="Stock" meta:resourcekey="colStock"></asp:BoundColumn>
                                        <asp:BoundColumn DataField="Dimensions" HeaderText="Dimensions<br/>Th x W x L" meta:resourcekey="colDimensions"></asp:BoundColumn>
                                        <asp:BoundColumn DataField="RValue" HeaderText="R-Value" DataFormatString="{0:n1}" meta:resourcekey="colRValue"></asp:BoundColumn>
                                        <asp:BoundColumn DataField="Format" HeaderText="Format" meta:resourcekey="colFormat"></asp:BoundColumn>
                                        <asp:BoundColumn DataField="NumberPerPack" HeaderText="No./Pack" meta:resourcekey="colNumberPerPack"></asp:BoundColumn>
                                        <asp:BoundColumn DataField="SquareFeetPerPack" HeaderText="SQ FT/<br/>Pack" meta:resourcekey="colSquareFeetPerPack"></asp:BoundColumn>
                                        <asp:BoundColumn DataField="PacksPerTrailerLength" HeaderText="Packs/TL" DataFormatString="{0:n0}" meta:resourcekey="colPacksPerTrailerLength"></asp:BoundColumn>
                                        <asp:BoundColumn DataField="SquareFeetPerTrailerLength" HeaderText="SQ FT/TL" meta:resourcekey="colSquareFeetPerTrailerLength"></asp:BoundColumn>
                                        <asp:BoundColumn DataField="MinimumQuantity" HeaderText="Minimum Order Quantity" meta:resourcekey="colMinQuantity"></asp:BoundColumn>
                                        <asp:TemplateColumn HeaderText="TL Price/<br/>1000 sq ft" meta:resourcekey="colTlPrice">
                                            <ItemTemplate>
                                                <span class="price<%# DataBinder.Eval(Container.DataItem, "ProductID") %>"><%# DataBinder.Eval(Container.DataItem, "Price") %></span>
                                            </ItemTemplate>
                                        </asp:TemplateColumn>
                                        <asp:TemplateColumn HeaderText="List Less Discount %" meta:resourcekey="colListLessDiscount">
                                            <ItemTemplate>
                                                <span class="lessDiscount<%# DataBinder.Eval(Container.DataItem, "ProductID") %>">0</span>%
                                            </ItemTemplate>
                                        </asp:TemplateColumn>
                                        <asp:TemplateColumn HeaderText="Net Price" meta:resourcekey="colNetPrice">
                                            <ItemTemplate>
                                                <span class="netPrice<%# DataBinder.Eval(Container.DataItem, "ProductID") %>"><%# DataBinder.Eval(Container.DataItem, "Price") %></span>
                                            </ItemTemplate>
                                        </asp:TemplateColumn>
                                    </Columns>
                                </asp:DataGrid>
                            </div>
                            <div class="visible-sm-block visible-xs-block">
                                <p><small><asp:Literal ID="litAdditionalInfo" runat="server" Text="Additional information can be found by scrolling the table horizontally." meta:resourcekey="litAdditionalInfoResource1"></asp:Literal></small></p>
                            </div>
                            <br>
                            <div class="row">
                                <div class="col-sm-8 col-sm-offset-4 col-md-6 col-md-offset-6">
                                    <div class="row">
                                        <div class="col-sm-4">
                                            <div class="discount-label">
                                                <asp:Literal ID="litDiscounted" runat="server" Text="List Less Discount %" meta:resourcekey="litDiscountedResource1"></asp:Literal>
                                            </div>
                                        </div>
                                        <div class="col-sm-8">
                                            <div class="input-group">
                                                <input type="number" class='form-control discount<%# DataBinder.Eval(Container.DataItem, "ProductID") %>' max="100" min="0">
                                                <span class="input-group-btn">
                                                    <button class="btn btn-grey" type="button" onclick='applyDiscount(<%# DataBinder.Eval(Container.DataItem, "ProductID") %>)' style="padding: 10px 13.5px"><asp:Literal ID="litApplyDiscount" runat="server" Text="Apply Discount" meta:resourcekey="litApplyDiscountResource1"></asp:Literal> <i class="fa fa-caret-right"></i></button>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </ItemTemplate>
        <AlternatingItemTemplate>
            <section class="white">
                <div class="container">
                    <div class="row">
                        <div class="col-sm-4">
                            <h2 class="h1">
                                <img class="img-responsive" src='<%# DataBinder.Eval(Container.DataItem, "TitleImage") %>' visible="<%# DataBinder.Eval(Container.DataItem, "TitleImage").ToString().Length > 0 %>" alt="<%# DataBinder.Eval(Container.DataItem, "Name") %>" />
                                <small visible="<%# DataBinder.Eval(Container.DataItem, "EffectiveDate").ToString().Length > 0 %>">
                                    <%# DataBinder.Eval(Container.DataItem, "EffectiveDate") %>
                                </small>
                            </h2>
                        </div>
                        <div class="col-sm-3 col-sm-offset-2">
                            <p visible="<%# DataBinder.Eval(Container.DataItem, "InformationLink").ToString().Length > 0 %>">
                                <a target="_blank" href="<%# DataBinder.Eval(Container.DataItem, "InformationLink") %>" class="btn btn-block btn-grey"><asp:Literal ID="litProductInformation" runat="server" Text="Product Information" meta:resourcekey="litProductInformationResource1"></asp:Literal> <i class="fa fa-caret-right"></i></a>
                            </p>
                        </div>
                        <div class="col-sm-3">
                            <p>
                                <button type="button" onclick="downloadPDF([<%# DataBinder.Eval(Container, "DataItem.ProductID") %>]);" class="btn btn-block btn-roxul"><asp:Literal ID="litDownloadPDF" runat="server" Text="Download PDF" meta:resourcekey="litDownloadPDFResource1"></asp:Literal> <i class="fa fa-caret-right"></i></button>
                            </p>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xs-12">
                            <div class="table-responsive">
                                <asp:DataGrid ID="dgProduct" AutoGenerateColumns="False" runat="server" DataSource='<%# DataBinder.Eval(Container.DataItem, "ProductDetails") %>' CssClass="table table-striped table-bordered products" meta:resourcekey="dgProductResource1">
                                    <HeaderStyle CssClass="thead" />
                                    <Columns>
                                        <asp:BoundColumn DataField="ItemNumber" HeaderText="Item #" meta:resourcekey="colItemNumber"></asp:BoundColumn>
                                        <asp:BoundColumn DataField="UPC" HeaderText="UPC Code" meta:resourcekey="colUpcCode"></asp:BoundColumn>
                                        <asp:BoundColumn DataField="Stock" HeaderText="Stock" meta:resourcekey="colStock"></asp:BoundColumn>
                                        <asp:BoundColumn DataField="Dimensions" HeaderText="Dimensions<br/>Th x W x L" meta:resourcekey="colDimensions"></asp:BoundColumn>
                                        <asp:BoundColumn DataField="RValue" HeaderText="R-Value" DataFormatString="{0:n1}" meta:resourcekey="colRValue"></asp:BoundColumn>
                                        <asp:BoundColumn DataField="Format" HeaderText="Format" meta:resourcekey="colFormat"></asp:BoundColumn>
                                        <asp:BoundColumn DataField="NumberPerPack" HeaderText="No./Pack" meta:resourcekey="colNumberPerPack"></asp:BoundColumn>
                                        <asp:BoundColumn DataField="SquareFeetPerPack" HeaderText="SQ FT/<br/>Pack" meta:resourcekey="colSquareFeetPerPack"></asp:BoundColumn>
                                        <asp:BoundColumn DataField="PacksPerTrailerLength" HeaderText="Packs/TL" DataFormatString="{0:n0}" meta:resourcekey="colPacksPerTrailerLength"></asp:BoundColumn>
                                        <asp:BoundColumn DataField="SquareFeetPerTrailerLength" HeaderText="SQ FT/TL" meta:resourcekey="colSquareFeetPerTrailerLength"></asp:BoundColumn>
                                        <asp:BoundColumn DataField="MinimumQuantity" HeaderText="Minimum Order Quantity" meta:resourcekey="colMinQuantity"></asp:BoundColumn>
                                        <asp:TemplateColumn HeaderText="TL Price/<br/>1000 sq ft" meta:resourcekey="colTlPrice">
                                            <ItemTemplate>
                                                <span class="price<%# DataBinder.Eval(Container.DataItem, "ProductID") %>"><%# DataBinder.Eval(Container.DataItem, "Price") %></span>
                                            </ItemTemplate>
                                        </asp:TemplateColumn>
                                        <asp:TemplateColumn HeaderText="List Less Discount %" meta:resourcekey="colListLessDiscount">
                                            <ItemTemplate>
                                                <span class="lessDiscount<%# DataBinder.Eval(Container.DataItem, "ProductID") %>">0</span>%
                                            </ItemTemplate>
                                        </asp:TemplateColumn>
                                        <asp:TemplateColumn HeaderText="Net Price" meta:resourcekey="colNetPrice">
                                            <ItemTemplate>
                                                <span class="netPrice<%# DataBinder.Eval(Container.DataItem, "ProductID") %>"><%# DataBinder.Eval(Container.DataItem, "Price") %></span>
                                            </ItemTemplate>
                                        </asp:TemplateColumn>
                                    </Columns>
                                </asp:DataGrid>
                            </div>
                            <div class="visible-sm-block visible-xs-block">
                                <p><small><asp:Literal ID="litAdditionalInfo2" runat="server" Text="Additional information can be found by scrolling the table horizontally." meta:resourcekey="litAdditionalInfo2Resource1"></asp:Literal></small></p>
                            </div>
                            <br>
                            <div class="row">
                                <div class="col-sm-8 col-sm-offset-4 col-md-6 col-md-offset-6">
                                    <div class="row">
                                        <div class="col-sm-4">
                                            <div class="discount-label">
                                                <asp:Literal ID="litDiscounted2" runat="server" Text="List Less Discount %" meta:resourcekey="litDiscounted2Resource1"></asp:Literal>
                                            </div>
                                        </div>
                                        <div class="col-sm-8">
                                            <div class="input-group">
                                                <input type="number" class='form-control discount<%# DataBinder.Eval(Container.DataItem, "ProductID") %>' max="100" min="0">
                                                <span class="input-group-btn">
                                                    <button class="btn btn-grey" type="button" onclick='applyDiscount(<%# DataBinder.Eval(Container.DataItem, "ProductID") %>)' style="padding: 10px 13.5px"><asp:Literal ID="litApplyDiscount2" runat="server" Text="Apply Discount" meta:resourcekey="litApplyDiscount2Resource1"></asp:Literal> <i class="fa fa-caret-right"></i></button>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </AlternatingItemTemplate>
    </asp:Repeater>
&#13;
&#13;
&#13;

&#13;
&#13;
protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            try
            {
                int productGroupID = int.Parse(Request.QueryString["group"].ToString());
                ProductGroup productGroup = Global.DbContext.ProductGroups.Where(x => x.ProductGroupID == productGroupID).FirstOrDefault();
                string[] tokens = Request.QueryString["products"].Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                int[] productIDs = Array.ConvertAll<string, int>(tokens, int.Parse);

                switch (this.CurrentLanguage)
                {
                    case "fr":
                        litCount.Text = string.Format("({0}) produits provenant de {1}", productIDs.Count(), productGroup.Name);
                        break;
                    case "es":
                        litCount.Text = string.Format("Para mostrar ({0}) productos provenientes del {1}", productIDs.Count(), productGroup.Name);
                        break;
                    default:
                        litCount.Text = string.Format("Showing ({0}) products from {1}", productIDs.Count(), productGroup.Name);
                        break;
                }

                repProducts.DataSource = Global.DbContext.Products.Where(x => productIDs.Contains(x.ProductID)).ToList();
                repProducts.DataBind();

                foreach (RepeaterItem item in repProducts.Items)
                {
                    DataGrid dgProduct = (DataGrid)item.FindControl("dgProduct");
                    if (dgProduct != null)
                    {
                        for (int col = 0; col < dgProduct.Columns.Count; col++)
                        {
                            if (dgProduct.Columns[col].GetType() == typeof(BoundColumn))
                            {
                                bool has_values = false;

                                foreach (DataGridItem dgitem in dgProduct.Items)
                                {
                                    if (!string.IsNullOrWhiteSpace(dgitem.Cells[col].Text) && dgitem.Cells[col].Text != "&nbsp;")
                                        has_values = true;
                                }

                                if (!has_values)
                                {
                                    dgProduct.Columns[col].Visible = false;
                                }
                            }
                        }
                    }
                }
                
            }
            catch (Exception ex)
            {
                litError.Text = Utility.FormatErrorMessage(ex);
            }
        }
    }

    protected string AllProductIDs
    {
        get
        {
            return Request.QueryString["products"];
        }
    }
&#13;
&#13;
&#13;

我已经考虑过使用jQuery来访问内容,因为产品ID是通过网址传递的,但由于模板列没有ID,这意味着它会非常困难。< / p>

如果有人可以提供帮助,我们将不胜感激。还有第一个问题,如果我发错了就好了。我搜索得非常彻底。

干杯,

安德鲁

2 个答案:

答案 0 :(得分:0)

我看到你用转发器来展示产品。太糟糕了,你将DataGrid用于ProductDetails。那个也可能是一个转发器,它可以让你更有控制力。无论如何,你是亲密的。我认为你已经完成了以下工作(从头开始做这个,至少10年后我至少使用了DataGrid / GridView)

protected void dgProduct_ItemDataBound(object sender, RepeaterItemEventArgs args) {
    if (args.Row.RowType == DataControlRowType.Header) {
        //Adjust the headerText here
        args.Row.Cells[3].Text = "New header text";
        //Or more elegantly try to avoid doing this by index
    }
}

转发器的另一个提示,如果它基本上只是不同的背景颜色,你可以避免对ItemTemplate和AlternatingItemTemplate进行双重编码。仅使用ItemTemplate并使用以下内容设置交替的css类,因此您可以在css中设置不同的backgroundcolor。

<section class='<%# (Container.Item.ItemType == ListItemType.Item) ? "grey" : "white" %>'>

答案 1 :(得分:0)

在对此工作了一段时间后,我终于能够完成必要的更改。 OnItemDataBound 为我工作,允许我在数据处于绑定过程中进行更改。

必须检查每个案例,以便标签能够根据语言并根据具体的产品ID正确显示信息。

我希望这可以帮助后来的人。

protected void repProducts_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        try
        {
            DataGrid dg = (DataGrid)e.Item.FindControl("dgProduct");
            if (dg != null)
            {
                for (int i = 0; i < dg.Columns.Count; i++)
                {
                    if (dg.Columns[i].HeaderText == String.Empty)
                    {
                        if (System.Globalization.CultureInfo.CurrentCulture.Name == "en-US")
                        {
                            switch (productIDs[numProductID])
                            {
                                case 264:
                                    dg.Columns[i].HeaderText = "TL Price Per Pack";
                                    dg.DataBind();
                                    numProductID++;
                                    break;
                                case 266:
                                    dg.Columns[i].HeaderText = "TL Price Per Pack";
                                    dg.DataBind();
                                    numProductID++;
                                    break;
                                case 296:
                                    dg.Columns[i].HeaderText = "TL Price Per Pack";
                                    dg.DataBind();
                                    numProductID++;
                                    break;
                                default:
                                    dg.Columns[i].HeaderText = "TL Price/<br/>1000 sq ft";
                                    dg.DataBind();
                                    numProductID++;
                                    break;
                            }
                        }
                        if (System.Globalization.CultureInfo.CurrentCulture.Name == "fr-FR")
                        {
                            switch (productIDs[numProductID])
                            {
                                case 265:
                                    dg.Columns[i].HeaderText = "TL Prix Par Paquet";
                                    dg.DataBind();
                                    numProductID++;
                                    break;
                                case 267:
                                    dg.Columns[i].HeaderText = "TL Prix Par Paquet";
                                    dg.DataBind();
                                    numProductID++;
                                    break;
                                case 297:
                                    dg.Columns[i].HeaderText = "TL Prix Par Paquet";
                                    dg.DataBind();
                                    numProductID++;
                                    break;
                                default:
                                    dg.Columns[i].HeaderText = "Prix TL/1000<br/>pieds carrés";
                                    dg.DataBind();
                                    numProductID++;
                                    break;
                            }
                        }
                        if (System.Globalization.CultureInfo.CurrentCulture.Name == "es-ES")
                        {
                            switch (productIDs[numProductID])
                            {
                                case 375:
                                    dg.Columns[i].HeaderText = "TL Precio Por Paquete";
                                    dg.DataBind();
                                    numProductID++;
                                    break;
                                case 377:
                                    dg.Columns[i].HeaderText = "TL Precio Por Paquete";
                                    dg.DataBind();
                                    numProductID++;
                                    break;
                                case 405:
                                    dg.Columns[i].HeaderText = "TL Precio Por Paquete";
                                    dg.DataBind();
                                    numProductID++;
                                    break;
                                default:
                                    dg.Columns[i].HeaderText = "Precio de TL por 1000 pies cuadrados";
                                    dg.DataBind();
                                    numProductID++;
                                    break;
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            litError.Text = Utility.FormatErrorMessage(ex);
        }
    }