【发布时间】:2015-05-01 16:00:45
【问题描述】:
我的 Codebehind 中有 HTML 表格,它将在页面加载时绑定数据。
现在我有一个按钮可以将数据插入数据库。我的问题是当我在按钮单击时插入数据时,我的页面得到回发。我的 html 表格数据将只显示旧数据而不是我添加的新数据。因为 html 表首先在页面加载中绑定,然后我的控件将转到 button_click 事件。
我尝试将 ispostback 放在 page_load 上,但是当页面第一次加载时,html 表不显示任何数据。
我该如何解决这个问题。
protected void Page_Load(object sender, EventArgs e)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from Ticket";
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
// //Building an HTML string.
StringBuilder html = new StringBuilder();
//Table start.
html.Append("<table id='tbldata' style='table-layout:fixed;' border='0'>");
html.Append("<THEAD>");
html.Append("<TR>");
html.Append("<TH>Ticket</TH>");
html.Append("<TH>Priority</TH>");
html.Append("<TH>Status<div class='fildownarrow'></div></TH>");
html.Append("<TH>Practice Name<div class='fildownarrow'></div></TH>");
html.Append("<TH>Patient Name</TH>");
html.Append("<TH>Assigned</TH>");
html.Append("<TH>Subject</TH>");
html.Append("<TH style='width:100px;><a href='#'><div class='filtericon'></div></a></TH>");
html.Append("</TR>");
html.Append("</THEAD>");
if (dr.HasRows)
{
while (dr.Read())
{
html.Append("<tbody>");
html.Append("<tr>");
html.Append("<td>" + dr["Ticket_no"] + "</td>");
html.Append("<td>" + dr["Priority"] + "</td>");
html.Append("<td>" + dr["Status"] + "</td>");
html.Append("<td>" + dr["Practice_Name"] + "</td>");
html.Append("<td>" + dr["Patient_Name"] + "</td>");
html.Append("<td>" + dr["Assign_User_Name"] + "</td>");
html.Append("<td>" + dr["Msg_Subject"] + "</td>");
html.Append("</tr>");
html.Append("</tbody>");
}
}
//Table end.
html.Append("</table>");
//Append the HTML string to Placeholder.
PlaceHolder1.Controls.Add(new Literal { Text = html.ToString() });
dr.Close();
dr.Dispose();
}
【问题讨论】:
-
不要这样做,将数据检索到列表中并将其绑定到列表视图控件。将为您省去很多麻烦。
-
使用SqlDataAdapter检索数据,使用Repeater、DataList或GridView显示数据