【问题标题】:ASP.NET Datagrid HTML Output (Display)ASP.NET Datagrid HTML 输出(显示)
【发布时间】:2010-09-29 03:52:26
【问题描述】:

目前我正在将数据集与数据网格绑定。

ds = query.ExecuteReadQuery("select PollQuestionText as 'Survey Question',    
PollAnswer1Text as 'Selection 1', PollAnswer2Text as 'Selection 2', PollAnswer3Text  
as 'Selection 3', PollEnabled 'Status'  from tbl_pollquestions")

For Each row As Data.DataRow In ds.Tables(0).Rows
        If row.ItemArray(4).ToString = "0" Then
            row.ItemArray."<a href=""""> <img src=""img/box_icon_edit_pencil1.gif"" border=""0""> </a>"

        ElseIf row.ItemArray(4).ToString = "1" Then
            row.Item(4) = "<a href=""""> <img src=""img/box_icon_edit_pencil2.gif"" border=""0""> </a>"
        End If

    Next

GridView1.DataSource = ds

GridView1.DataBind()

既然我插入的是html代码,为什么没有转换成html?

输出结果全是文本。 (假设正在显示一个没有重定向 url 的图标)

我不知道为什么。

谢谢

【问题讨论】:

    标签: asp.net html vb.net data-binding dataset


    【解决方案1】:

    如果您使用的是网格视图,您可能希望按预期使用。

    你应该有一个内容模板。

    如果需要根据值进行格式化,请在 rowdatabound 事件中进行。

    我认为您遇到了“意外”行为,因为 gridview 可以绑定到广泛的集合数组(数组、哈希表、数据集等),并且它管理它如何专门绑定数据。

    gridview 的目的是在页面的 html 部分进行格式化...您可以在那里进行许多精美的格式化。

    如果你打算使用gridviews,最好熟悉onrowdatabound和onrowcommand事件...

    快速修复:

    我想可能需要一点时间来学习如何以正确的方式进行操作。在此期间,如果您想以最少的更改快速解决您的问题:

    • 使用 asp:literal 控件来控制您想要图像的位置
    • 更改数据库中的查询以将返回值替换为 html 而不是 0/1 值
    • 将文字绑定到返回值并跳过当前的格式化部分

    【讨论】:

      【解决方案2】:

      这是一种无需使用内容模板即可快速解决问题的方法。

      首先,将RowDataBound 事件添加到您的 GridView。

      <asp:GridView ID="GridView1" runat="server" onrowdatabound="GridView1_RowDataBound">
      </asp:GridView>
      

      其次,使用您的逻辑添加事件处理程序的代码。 RowDataBound 事件将为每一行触发,我们不必使用foreach。我使用的是 C#,但您可以轻松地将其转换为 VB。

      protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {    
          if (e.Row.RowType == DataControlRowType.DataRow) {        
              if (e.Row.Cells[4].Text == "0") {            
                  e.Row.Cells[4].Text = "<a href=''> <img src='img/box_icon_edit_pencil1.gif' border='0'> </a>"
              } else {
                  e.Row.Cells[4].Text = "<a href=''> <img src='img/box_icon_edit_pencil2.gif' border='0'> </a>"
              }
          }
      }
      

      作为旁注,您可能想要更改

      <a href=''> <img src='img/box_icon_edit_pencil1.gif' border='0'> </a>
      <a href=''> <img src='img/box_icon_edit_pencil2.gif' border='0'> </a>
      

      <a href="" class="Pencil1"></a>
      <a href="" class="Pencil2"></a>
      

      并使用 CSS 设置背景图像。

      【讨论】:

        【解决方案3】:

        要让 GridView 输出 HTML,您只需将所需绑定字段的 HtmlEncode 参数设置为 false。

        <asp:BoundField DataField="Question" HeaderText="Question" HtmlEncode="false" />
        

        【讨论】:

          猜你喜欢
          • 2021-02-26
          • 2010-09-14
          • 2017-05-30
          • 1970-01-01
          • 1970-01-01
          • 2010-10-06
          • 2013-05-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多