【问题标题】:Add Div to GridView将 div 添加到 GridView
【发布时间】:2016-11-07 16:35:25
【问题描述】:

我正在尝试在我的 gridview 表中的一列的 td 内添加一个 div。我发现this question 与我正在尝试做的事情相似,但答案不够彻底,无法让它按我的意愿工作。基本上,我是从 DataTable dt 自动为我的 gridview 生成数据:

GridView1.DataSource = dt;
GridView1.DataBind();

gridview 的 html 在这里:

<div class="gridTable" style="width:100%">
  <asp:GridView runat="server"  ID="GridView1" OnRowDataBound="GridView1_RowDataBound">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <div id="insideDiv" runat="server"></div>
            </ItemTemplate>
        </asp:TemplateField>           
    </Columns>
  </asp:GridView>
</div>

我希望在标题为“评论”的列上有一个内部 div。我的 OnRowDataBound 函数做到了这一点:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
        {
            HtmlGenericControl div = (HtmlGenericControl)e.Row.FindControl("insideDiv");

        }
}

但我不确定如何从这里开始。我需要的是能够访问我的 css 中的 div,因为该列的格式与其他列不同。

【问题讨论】:

  • 我认为您不能在服务器上运行
    标记。您可以使用&lt;asp:Literal id="lit0" runat="server" /&gt; 从那里,您可以添加和设置
    标签、文本等。
  • @Sometowngeek 是的,它可以在服务器上运行。这就是HtmlGenericControl 的用途。

标签: c# html asp.net gridview


【解决方案1】:

您可以使用数据绑定表达式设置 div 的内容,并设置您将在 CSS 样式中引用的类属性。假设内容由数据源的Comments 字段给出,它可能如下所示:

<asp:TemplateField>
    <ItemTemplate>
        <div class="innerDiv" >
            <%# Eval("Comments") %>
        </div>
    </ItemTemplate>
</asp:TemplateField>

然后您可以为innerDiv 类添加样式定义:

<style type="text/css">
    .innerDiv
    {
        ...
    }
</style>


更新

在您的评论(如下)中,您提到您更愿意替换自动生成列的内容,而不是添加带有 TemplateField 的列。为此,您可以使用类似于我们在 Hide Column in GridView from Code Behind 中使用的技术。

Comments字段的列索引定义一个变量:

private int commentsColIndex;

从数据表中获取它的值:

commentsColIndex = dt.Columns["Comments"].Ordinal;
GridView1.DataSource = dt.DefaultView;
GridView1.DataBind();

将其内容替换为RowDataBound事件处理程序中的div元素,并设置div元素的class属性:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        TableCell commentsCell = e.Row.Cells[commentsColIndex];
        HtmlGenericControl div = new HtmlGenericControl("DIV");
        div.Attributes.Add("class", "innerDiv");
        div.InnerHtml = commentsCell.Text;
        commentsCell.Text = string.Empty;
        commentsCell.Controls.Add(div);
    }
    ...
}

注意如果在该行中移动或删除了其他一些单元格,您可能需要向commentsColIndex 添加偏移量。

【讨论】:

  • 我需要对 GridView1_RowDataBound 函数做些什么吗?
  • 如果你只想用Comments字段值填充div并设置类样式,上面的代码应该足够了。这就是为什么我没有显示idrunat="server" 属性。
  • 当我将它添加到我的代码中时,它会创建另一列,将 Comments 字段值放入表的开头。当我检查页面时,我看到每个单元格都在 innerDiv div 内。但是,它仍然将 Comments 列保留在表的末尾,并且该列不在 div 内。有没有办法将 div 添加到我现有的列中?当前的解决方案似乎是添加另一个包含 div 和数据的列,而不是仅将 div 添加到现有列。
  • 是的,添加一个 TemplateField 会在“自动生成”的列之前添加一列。有一种方法可以修改生成的列,这将使用与your previous post 中类似的技术。我将不得不更新我的答案,但不会立即更新(大约一个小时后,如果之前没有其他人回答)。
  • 我将新代码添加到我的答案中。顺便说一句,我假设您确实需要使用自动生成的列。如果没有,设置AutoGenerateColumn="false" 并在标记中明确定义列将使事情变得更容易。
猜你喜欢
相关资源
最近更新 更多
热门标签