我可以将动态创建的 c# 表转换为 html 字符串吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1524105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I convert a dynamically created c# table to a html string?
提问by Bilgin K?l??
Can I convert a dynamically created c# table to an html string ?
我可以将动态创建的 c# 表转换为 html 字符串吗?
I mean like this;
我的意思是这样;
Table t = new Table();
TableRow tr = new TableRow();
TableCell td = new TableCell();
td.Text = "Some text... Istanbul";
tr.Cells.Add(td);
t.Rows.Add(tr);
t.ToString();
Response.Write(t.ToString());
I wanna see in the page;
我想在页面中看到;
<table> <tr> <td> Some text...
Istanbul </td> <tr> </table>
采纳答案by CD..
using (StringWriter sw = new StringWriter())
{
Table t = new Table();
TableRow tr = new TableRow();
TableCell td = new TableCell {Text = "Some text... Istanbul"};
tr.Cells.Add(td);
t.Rows.Add(tr);
t.RenderControl(new HtmlTextWriter(sw));
string html = sw.ToString();
}
result:
结果:
<table border="0"><tr><td>Some text... Istanbul</td></tr></table>
<table border="0"><tr><td>Some text... Istanbul</td></tr></table>
回答by Pete OHanlon
Yes. It must become a string at some point for it to be rendered out to the browser - one way to do it is to take this and extract the table out of it.
是的。它必须在某个时候变成一个字符串才能呈现给浏览器 - 一种方法是取出它并从中提取表格。
回答by James
You should update your question to be a little more informative. However, I will assume you are using a DataGrid:
您应该更新您的问题以提供更多信息。但是,我假设您使用的是 DataGrid:
StringBuilder stringBuilder = new StringBuilder();
StringWriter stringWriter = new StringWriter(stringBuilder);
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
DataGrid1.RenderControl(htmlWriter);
string dataGridHTML = Server.HtmlEncode(stringBuilder.ToString());
回答by Ralph Lavelle
Just have a Panel on the page, and add the table to the Panel.
只需在页面上有一个面板,然后将表格添加到面板中。
So, in your aspx file:
因此,在您的 aspx 文件中:
<asp:Panel id="MyPanel" runat="server" />
and in your code behind:
并在您的代码后面:
MyPanel.Controls.Add(t)
// where 't' is your Table object
MyPanel.Controls.Add(t)
// 其中 't' 是您的 Table 对象
That places the table in your panel, which renders the Table as Html to the page, in a nice <div>
这会将表格放置在您的面板中,该面板将表格作为 Html 呈现给页面,以一种很好的方式呈现 <div>