Hi
Can the below code can be done dynamically. Tables & no of fields van be different. Now i have to write in every file
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. Name Short Name Status Action ");
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("");
htmlTable.Append("");
htmlTable.Append(" ");
Count++;
}
htmlTable.Append("");
htmlTable.Append("
");
PlaceHolderTable.Controls.Add(new Literal { Text = htmlTable.ToString() });
Thanks
Naimish MakwanaPosted Sep 3, 2024, 4:30 AM
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:
Key Changes:This approach should help you avoid writing repetitive code for different tables and fields.
Thanks
Aman GuptaPosted Sep 3, 2024, 4:46 AM
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:
Explanation:
Usage Example:
This will help you Ramco.
Thanks
Gowtham CpPosted Sep 3, 2024, 4:34 AM
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:
Hope it helps!