0
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"

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.