【问题标题】:How to get the width of a GridView Column in rowbound event?如何在行绑定事件中获取 GridView 列的宽度?
【发布时间】:2016-11-21 21:44:36
【问题描述】:

我在 GridView 中有一个名为“Weightage”的列。我在 gridview 之外有一个名为“Total”的文本框,我想将此文本框对齐在 Weightage 列的正下方。

 </asp:GridView>
   <div>
           <span id="q1totalweightage" runat="server">Total<asp:TextBox ID="txtq1totalweightage" runat="server" ></asp:TextBox></span>
   </div>

代码背后:

protected void grvGoals_RowDataBound1(object sender, GridViewRowEventArgs e)
{
    switch (e.Row.RowType)
    {
      case DataControlRowType.DataRow:
      q1totalweightage.Attributes.Add("style", "margin-left: " +     e.Row.Cells[0].Width + "px;");
 break;
     }

注意:假设由于某种原因我不能将整个文本框放在页脚中。

【问题讨论】:

    标签: c# css asp.net gridview


    【解决方案1】:

    无法获得服务器端GridView 列的计算宽度。为此,您必须使用JavaScript

    为此,您必须像这样为您的列提供类名

    <asp:TemplateField HeaderText="Contact Name">
        <ItemTemplate>
            <asp:Label ID="ContactName" runat="server"  
                CssClass="my-column"
                Text='<%# Eval("ContactName") %>'>
            </asp:Label>                
        </ItemTemplate>
    </asp:TemplateField>
    

    也不需要使用runat="server" 作为跨度。

    <span id="q1totalweightage">Total
        <asp:TextBox ID="txtq1totalweightage" runat="server" >
        </asp:TextBox>
    </span>
    

    原版 JavaScript

    document.addEventListener("DOMContentLoaded", function (event) {
        var column = document.getElementsByClassName("my-column")[0].parentNode;
        var row = column.parentNode;
        var newMargin = row.clientWidth - column.clientWidth;
        document.getElementById("q1totalweightage").style.marginLeft = newMargin + "px";
    });
    

    或者 jQuery

    $(document).ready(function () {
        var column = $(".my-column:first").closest("td");
        var row = column.closest("tr");
        //var newMargin = row.width() - column.width();
        var newMargin = row.outerWidth() - column.outerWidth();
        $("#q1totalweightage").css("margin-left", newMargin + "px");
    });
    

    P.S:此代码假定列 Contact Name 是表的 最后 列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-10
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 2013-03-14
      • 2017-04-26
      • 1970-01-01
      相关资源
      最近更新 更多