Hi
Can the below code can be done dynamically. Tables & no of fields van be different. Now i have to write in every file
C#
StringBuilder htmlTable = new StringBuilder();
con.ConnectionString = ConfigurationManager.ConnectionStrings["cnn_Live"].ConnectionString; ;
SqlCommand cmd = new SqlCommand("select * from EmployeeCategory order by Category", con);
cmd.CommandType = CommandType.Text;
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
Int32 Count = 1;
htmlTable.Append("");
htmlTable.Append("Sr.NameShort NameStatusAction");
htmlTable.Append("");
foreach (DataRow row in dt.Rows)
{
String Status = "Blocked";
if (Convert.ToBoolean(row["status"]))
{
Status = "Active";
}
htmlTable.Append("");
htmlTable.Append("" + Count.ToString() + "");
htmlTable.Append("" + row["category"] + "");
htmlTable.Append("" + row["shortname"] + "");
if (Status == "Active")
htmlTable.Append("" + Status + "");
else
htmlTable.Append("" + Status + "");
htmlTable.Append("");
htmlTable.Append("");
string deleteAttributes = Status == "Blocked" ? "style='pointer-events: none; opacity: 0.5;' onclick='return false;'" : "data-toggle='modal' data-target='#modal_Delete' onclick='BindData(this);'";
htmlTable.Append($"");
htmlTable.Append("");
htmlTable.Append("" + row["docentry"] + "");
htmlTable.Append("" + row["status"] + "");
htmlTable.Append("");
Count++;
}
htmlTable.Append("");
htmlTable.Append("");
PlaceHolderTable.Controls.Add(new Literal { Text = htmlTable.ToString() });Thanks

Naimish MakwanaRank #324 · 7.7K reputationPosted Sep 3, 2024, 12:30 AM EDT
Yes, you can make this code more dynamic to handle different tables and fields. Here’s an example of how you can achieve this by using reflection and a more generic approach:
using System; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Text; using System.Web.UI.WebControls; public void GenerateHtmlTable(string tableName) { StringBuilder htmlTable = new StringBuilder(); string connectionString = ConfigurationManager.ConnectionStrings["cnn_Live"].ConnectionString; using (SqlConnection con = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand($"SELECT * FROM {tableName} ORDER BY 1", con); cmd.CommandType = CommandType.Text; if (con.State == ConnectionState.Closed) { con.Open(); } SqlDataAdapter sda = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); sda.Fill(dt); if (dt.Rows.Count > 0) { htmlTable.Append(""); htmlTable.Append(""); // Add table headers dynamically foreach (DataColumn column in dt.Columns) { htmlTable.Append($"{column.ColumnName}"); } htmlTable.Append("Action"); htmlTable.Append(""); int count = 1; foreach (DataRow row in dt.Rows) { htmlTable.Append(""); htmlTable.Append($"{count}"); foreach (DataColumn column in dt.Columns) { htmlTable.Append($"{row[column.ColumnName]}"); } string status = Convert.ToBoolean(row["status"]) ? "Active" : "Blocked"; string statusClass = status == "Active" ? "bg-primary" : "bg-danger"; htmlTable.Append($"{status}"); htmlTable.Append(""); htmlTable.Append(""); string deleteAttributes = status == "Blocked" ? "style='pointer-events: none; opacity: 0.5;' onclick='return false;'" : "data-toggle='modal' data-target='#modal_Delete' onclick='BindData(this);'"; htmlTable.Append($""); htmlTable.Append(""); htmlTable.Append(""); count++; } htmlTable.Append(""); htmlTable.Append(""); } } PlaceHolderTable.Controls.Add(new Literal { Text = htmlTable.ToString() }); }
Key Changes:This approach should help you avoid writing repetitive code for different tables and fields.
Thanks
Gowtham CpRank #1,552 · 1K reputationPosted Sep 3, 2024, 12:34 AM EDT
Hello Ramco Ramco ,
To create a dynamic HTML table in C#, follow these steps:
Fetch Data: Load your data from the database into a
DataTable.Build the Table: Use
StringBuilderto construct the HTML. Generate table headers and rows based on theDataTablecontent.Here’s a simplified example:
using System; using System.Data; using System.Data.SqlClient; using System.Text; using System.Web.UI.WebControls; public partial class YourPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { GenerateDynamicTable(); } private void GenerateDynamicTable() { StringBuilder htmlTable = new StringBuilder(); string connectionString = ConfigurationManager.ConnectionStrings["cnn_Live"].ConnectionString; using (SqlConnection con = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand("SELECT * FROM EmployeeCategory ORDER BY Category", con); SqlDataAdapter sda = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); sda.Fill(dt); if (dt.Rows.Count > 0) { htmlTable.Append(""); // Create headers htmlTable.Append(""); foreach (DataColumn column in dt.Columns) { htmlTable.Append($"{column.ColumnName}"); } htmlTable.Append("Action"); htmlTable.Append(""); // Create rows htmlTable.Append(""); int count = 1; foreach (DataRow row in dt.Rows) { string status = Convert.ToBoolean(row["status"]) ? "Active" : "Blocked"; string statusClass = status == "Active" ? "badge bg-primary" : "badge bg-danger"; string deleteAttributes = status == "Blocked" ? "style='pointer-events: none; opacity: 0.5;' onclick='return false;'" : "data-toggle='modal' data-target='#modal_Delete' onclick='BindData(this);'"; htmlTable.Append(""); htmlTable.Append($"{count}"); foreach (DataColumn column in dt.Columns) { if (column.ColumnName == "status") { htmlTable.Append($"{status}"); } else { htmlTable.Append($"{row[column]}"); } } htmlTable.Append(""); htmlTable.Append(""); htmlTable.Append($""); htmlTable.Append(""); htmlTable.Append(""); count++; } htmlTable.Append(""); htmlTable.Append(""); PlaceHolderTable.Controls.Add(new Literal { Text = htmlTable.ToString() }); } } } }Hope it helps!
Aman GuptaRank #193 · 12.4K reputationPosted Sep 3, 2024, 12:46 AM EDT
Hi Ramco,
Yes, you can make this code more dynamic to handle different tables and fields. Here’s an approach that can help you achieve that:
Here’s a modified version of your code:
public void GenerateDynamicTable(string tableName, string[] fields, string orderByField) { StringBuilder htmlTable = new StringBuilder(); con.ConnectionString = ConfigurationManager.ConnectionStrings["cnn_Live"].ConnectionString; string query = $"SELECT {string.Join(", ", fields)} FROM {tableName} ORDER BY {orderByField}"; SqlCommand cmd = new SqlCommand(query, con); cmd.CommandType = CommandType.Text; if (con.State == ConnectionState.Closed) { con.Open(); } SqlDataAdapter sda = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); sda.Fill(dt); if (dt.Rows.Count > 0) { int count = 1; htmlTable.Append(""); // Dynamically generate the table header htmlTable.Append("Sr."); foreach (DataColumn column in dt.Columns) { if (column.ColumnName != "docentry" && column.ColumnName != "status") { htmlTable.Append($"{column.ColumnName}"); } } htmlTable.Append("Action"); htmlTable.Append(""); htmlTable.Append(""); htmlTable.Append(""); htmlTable.Append(""); foreach (DataRow row in dt.Rows) { string status = Convert.ToBoolean(row["status"]) ? "Active" : "Blocked"; htmlTable.Append(""); htmlTable.Append($"{count}"); foreach (var field in fields) { htmlTable.Append($"{row[field]}"); } // Status column if (status == "Active") htmlTable.Append("" + status + ""); else htmlTable.Append("" + status + ""); // Action buttons htmlTable.Append(""); htmlTable.Append(""); string deleteAttributes = status == "Blocked" ? "style='pointer-events: none; opacity: 0.5;' onclick='return false;'" : "data-toggle='modal' data-target='#modal_Delete' onclick='BindData(this);'"; htmlTable.Append($""); htmlTable.Append(""); htmlTable.Append($"{row["docentry"]}"); htmlTable.Append($"{row["status"]}"); htmlTable.Append(""); count++; } htmlTable.Append(""); htmlTable.Append(""); PlaceHolderTable.Controls.Add(new Literal { Text = htmlTable.ToString() }); } }Explanation:
Usage Example:
string[] fields = { "category", "shortname", "status", "docentry" }; GenerateDynamicTable("EmployeeCategory", fields, "Category");This will help you Ramco.
Thanks