Reputation: 9416
List<string> columsToAdd = SelectedColumns.Split(',').ToList<string>();
string tableHeader = string.Empty;
tableHeader = "<table border = 1>" +
"<thead>" +
"<tr style='font-weight:bold;background-color: #f2f8f8;text-align:center;vertical-align:middle;color: #01846a;'>" +
"<th>" + Headers.Dynamic.Country + "</th>" +
"<th>" + Headers.Dynamic.State + "</th>" +
"<th>" + Headers.Dynamic.City + "</th>" +
"<th>" + Headers.Dynamic.Item1 + "</th>" +
"<th>" + Headers.Dynamic.Item2 + "</th>" +
"<th>" + Headers.Dynamic.Item3 + "</th>" +
"<th>" + Headers.Dynamic.Item4 + "</th>" +
"<th>" + Headers.Dynamic.Item5 + "</th>" +
"</tr>" +
"</thead></table>";
In the above code snippet, i'm creating an html table header. How can i dynamically first check if an item exists in List<string> columsToAdd
before adding a particular <th>
to string tableHeader
.
For example, i want to only add "<th>" + Headers.Dynamic.Item5 + "</th>" +
only if columsToAdd
contains the string "Item5"
Upvotes: 0
Views: 841
Reputation: 14624
You can check the existence of element by using IndexOf
method. If IndexOf
of some colunm is greater than 0 than add column.
if(columsToAdd.IndexOf(Headers.Dynamic.Country) > -1)
Your code should look like this
string tableHeader = string.Empty;
tableHeader = "<table border = 1>" +
"<thead>" +
"<tr style='font-weight:bold;background-color: #f2f8f8;text-align:center;vertical-align:middle;color: #01846a;'>";
if(columsToAdd.IndexOf(Headers.Dynamic.Country) > -1)
tableHeader +="<th>" + Headers.Dynamic.Country + "</th>";
tableHeader +="<th>" + Headers.Dynamic.State + "</th>" +
"<th>" + Headers.Dynamic.City + "</th>" +
"<th>" + Headers.Dynamic.Item1 + "</th>" +
"<th>" + Headers.Dynamic.Item2 + "</th>" +
"<th>" + Headers.Dynamic.Item3 + "</th>" +
"<th>" + Headers.Dynamic.Item4 + "</th>" +
"<th>" + Headers.Dynamic.Item5 + "</th>" +
"</tr>" +
"</thead></table>";
Similarly you can check other columns.
Upvotes: 2