【问题标题】:Adding dynamically user control to a Asp Table将动态用户控件添加到 Asp 表
【发布时间】:2013-03-04 15:58:36
【问题描述】:

我正在尝试使用数据集中的一些数据将 输入复选框类型asp 文本框 动态添加到 Asp Tablecell。我已经阅读了一些关于此的帖子,但没有一个想要达到的组合。

这是我正在使用的代码(其中 ds 是数据集,tblMeasuredChar 是 Asp 表):

   If ds.Tables(0).Rows.Count > 0 Then

        For Each dr As DataRow In ds.Tables(0).Rows
            Dim tr As New TableRow()

            'defining input
            Dim tc As New TableCell()
            tc.Text = "<input type=" & Chr(34) & "checkbox" & Chr(34) & " name=" & Chr(34) & "chkMeasuredChars" & Chr(34) & " value=" & Chr(34) & dr("id") & Chr(34) & "/>" & dr("description")

            'defining unique textbox
            Dim txtbx As New TextBox()
            txtbx.ID = "tbMeasuredChars" & dr("id")
            'add it to the cell
            tc.Controls.Add(txtbx)

            'add the cell to the row
            tr.Controls.Add(tc)

            tblMeasuredChar.Rows.Add(tr)
        Next
    End If

问题是只显示了我添加到 TableRow 的最后一个“东西”。我必须使用这种类型的输入,不可能使用一些 asp 复选框。是否可以将用户控件添加到已经有其他文本的 TableCell 中?

我已经尝试添加 TableCell 像 tr.Cells.Add(tc) 和其他一些组合,但结果仍然相同。将控件添加到单元格会使复选框(以及早期定义的所有内容)消失。

谢谢大家。

【问题讨论】:

  • 如果您使用Repeater 进行此操作,您的生活会轻松很多。如果您想探索此选项,请告诉我,我很乐意为您举个例子。

标签: asp.net vb.net user-controls celltable


【解决方案1】:

您应该使用Literal control,而不是使用.Text 属性。像这样:

If ds.Tables(0).Rows.Count > 0 Then

    For Each dr As DataRow In ds.Tables(0).Rows
        Dim tr As New TableRow()

        'defining input
        Dim tc As New TableCell()
        tc.Controls.Add(New LiteralControl("<input type=" & Chr(34) & "checkbox" & Chr(34) & " name=" & Chr(34) & "chkMeasuredChars" & Chr(34) & " value=" & Chr(34) & dr("id") & Chr(34) & "/>" & dr("description")))

        'defining unique textbox
        Dim txtbx As New TextBox()
        txtbx.ID = "tbMeasuredChars" & dr("id")
        'add it to the cell
        tc.Controls.Add(txtbx)

        'add the cell to the row
        tr.Controls.Add(tc)

        tblMeasuredChar.Rows.Add(tr)
    Next
End If

听起来这会很好地满足您的需求,因为它不像普通的 ASP.NET serv 控件,它基本上只是静态 HTML 文本。从上面链接的文档中:

ASP.NET 编译所有不支持的 HTML 元素和可读文本 需要服务器端处理到此类的实例中。为了 例如,不包含 runat="server" 的 HTML 元素 开始标签中的属性/值对被编译成 LiteralControl 对象。

所以你的文本基本上已经被编译成文字控件了。我认为这将解决您遇到的显示问题,同时使用 .Text 属性和 .Controls 集合。

【讨论】:

  • 谢谢你,jadarnel,它就像一个魅力!非常感谢,不仅是为了回答,也是为了解释。
  • @weilah 我很高兴能帮上忙 =)
猜你喜欢
  • 2012-02-24
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-04
  • 2011-10-27
相关资源
最近更新 更多