Reputation: 545
I am using Datatable to get some values from a database table.
DataTable dt = this.GetData();
StringBuilder html = new StringBuilder();
html.Append("<table border = '1'>");
foreach (DataRow row in dt.Rows)
{
html.Append("<tr>");
foreach (DataColumn column in dt.Columns)
{
html.Append("<td>");
html.Append(row[column.ColumnName]);
html.Append("</td>");
}
html.Append("</tr>");
}
html.Append("</table>");
The above code gives me this output:
The column with 0 0 is generated from the ID column of my table. I didn't pass the ID through my Stored Procedure because I dont need to display them. Is there a way to remove the first column itself and prevent it from displaying?
Upvotes: 2
Views: 5317
Reputation: 17
I was searching for the same thing, and I found this answer.
Credit for: Zortkun.
foreach (DataColumn column in dt.Columns)
{
if (dt.Columns.IndexOf(column) != 0)
{
html.Append("<td>");
html.Append(row[column.ColumnName]);
html.Append("</td>");
}
}
It worked for me.
Upvotes: 0
Reputation: 29714
Just use Linq Skip:
foreach (DataColumn column in dt.Columns.AsEnumerable().Skip(1))
Prob best to check that there are enough columns too:
if (dt.Columns.Length > 1)
{
foreach (DataColumn column in dt.Columns.AsEnumerable().Skip(1))
...etc
Upvotes: 3
Reputation: 2341
you can also use FOR instead of FOREACH and start from 1 instead of 0
for(int i=1;i<dt.Columns.Count;i++){//do whatever}
Upvotes: 2
Reputation: 73
dt.Columns.RemoveAt(0);
Just remove the column at the specified position.
Upvotes: 0