Dynamically insert checkbox into a table in ASP.NET with variable number of fields. C# codebehind

时光毁灭记忆、已成空白 提交于 2019-12-12 05:26:52

问题


I'm building an exemption request form that populates from an SQL Server 2008 database.

DataRow[] exemption = ds.Tables[2].Select();
    foreach (DataRow dr in exemption)
    {
        string exemptionType = dr["ExemptionType"].ToString();
        string exemptionID = dr["ExemptionID"].ToString();
        string exemptionDesc = dr["ExemptionDescription"].ToString();
        string displayLabel = dr["DisplayLabel"].ToString();
        sb.Append("<table align='center' width='730px'>");
        sb.Append("<tr><td><asp:CheckBox ID=\"chk" + exemptionID + "\" runat=\"server\" /></td>");
        sb.Append("<td><strong>" + exemptionDesc + "</strong></td>");
        sb.Append("</table>");
        sb.Append("<table align='center' width='630px'>");
        sb.Append("<tr><td>" + displayLabel + "</td></tr>");
        sb.Append("</table>");
    }
    return sb.ToString();

As it stands right now, the table builds fine, all the data displays fine, but the checkbox does not show up. Was wondering if doing it this way is possible at all, and if so, what am I doing wrong?


回答1:


You're inserting ASP.NET into your HTML and that HTML is probably not getting processed by ASP.NET. If you want to do it the way you're doing it now... switch to using input tags like so...

DataRow[] exemption = ds.Tables[2].Select(); 
foreach (DataRow dr in exemption) 
{ 
  string exemptionType = dr["ExemptionType"].ToString(); 
  string exemptionID = dr["ExemptionID"].ToString(); 
  string exemptionDesc = dr["ExemptionDescription"].ToString(); 
  string displayLabel = dr["DisplayLabel"].ToString(); 
  sb.Append("<table align='center' width='730px'>"); 
  sb.Append("<tr><td><input type=\"checkbox\" id=\"chk" + exemptionID + "\" /></td>"); 
  sb.Append("<td><strong>" + exemptionDesc + "</strong></td>"); 
  sb.Append("</table>"); 
  sb.Append("<table align='center' width='630px'>"); 
  sb.Append("<tr><td>" + displayLabel + "</td></tr>"); 
  sb.Append("</table>"); 
} 
return sb.ToString(); 

The other route would be to actually create the ASP.NET Checkboxes. That would look somethig like this...

  var checkbox = new CheckBox();
  checkbox.ID = "chk" + exemptionId;
  wrapper.Controls.Add(checkbox);

Where wrapper is a Panel or something of the sort.



来源:https://stackoverflow.com/questions/8537947/dynamically-insert-checkbox-into-a-table-in-asp-net-with-variable-number-of-fiel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!