【问题标题】:How to change a <div>'s style=width that is inside an ItemTemplate如何更改 ItemTemplate 内的 <div> 样式=宽度
【发布时间】:2017-12-13 14:11:59
【问题描述】:

我有一个 Gridview,其中一个列需要显示一组任务的进度。我在其中一个 gridview 单元格中使用引导进度条。

如何更改 div 的 style="width: __%",当它位于 asp:TemplateField 中的 ItemTemplate 中时?

<asp:GridView ID="gvExample" runat="server" CssClass="table table-bordered table-striped table-hover" />
    <Columns>
        <asp:BoundField />
        <asp:BoundField />
        <asp:BoundField />                    
        <asp:TemplateField ItemStyle-Width="200">
            <ItemTemplate>
                <div class="progress">
                    <div style="width: 50%" class="progress-bar progress-bar-striped" role="progressbar" height: 20px;" aria-valuemin="0" aria-valuemax="100"></div>
                    <div id="ApprovedTherm" runat="server" class="progress-bar progress-bar-striped progress-bar-success" role="progressbar" height: 20px;" aria-valuemin="0" aria-valuemax="100"></div>
                    <div id="TotalTherm" runat="server" class="progress-bar progress-bar-striped progress-bar-warning" role="progressbar" height: 20px;" aria-valuemin="0" aria-valuemax="100"></div>
                </div>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>            
</asp:GridView>

TLDR:如何从后面的代码中设置 div style="width: __%"

【问题讨论】:

    标签: c# html asp.net gridview progress-bar


    【解决方案1】:

    您可以通过在后面的代码中设置属性来做到这一点。但是你需要先在 div 中添加一个IDrunat=server

    <ItemTemplate>
        <div id="ProgressBar" runat="server" style="width: 50%" class="progress-bar progress-bar-striped"></div>
    </ItemTemplate>
    

    然后在后面的代码中使用 FindControl 来定位 DIV 并设置属性。

    foreach (GridViewRow row in GridView1.Rows)
    {
        HtmlGenericControl hgc = row.FindControl("ProgressBar") as HtmlGenericControl;
        hgc.Attributes.Add("style", "width: 100%");
    }
    

    或按索引

    HtmlGenericControl hgc = GridView1.Rows[i].FindControl("ProgressBar") as HtmlGenericControl
    

    【讨论】:

    • 我之前尝试过,只是再次尝试以确保。但是,我不断收到“服务器标签格式不正确”。错误信息
    • 这是因为:role="progressbar" height: 20px;"。您缺少"。但无论如何,这个高度应该是一个样式属性。
    【解决方案2】:
    1. 将 id 赋予 DIV 并在服务器上运行它

      <div id="temp" runat="server" ... > ... </div>
      
    2. RowDataBound事件中获取:

      protected void gvExample_RowDataBound(object sender, GridViewRowEventArgs e)
      {
          if (e.Row.RowType == DataControlRowType.DataRow)
          {
              // access the div here
              HtmlGenericControl tempDiv = (HtmlGenericControl) e.Row.FindControl("temp");
              tempDiv.Attributes.Add("style", "width: 50%;");
          }
      }
      

      注意:不要忘记将OnRowDataBound="gvExample_RowDataBound" 属性添加到您的GridView。

    【讨论】:

    • 我不断收到服务器标签格式不正确。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    • 2016-05-10
    • 2021-05-22
    • 2014-12-11
    • 2019-10-28
    相关资源
    最近更新 更多