2

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: enter image description here 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?

Bibek Aryal
  • 545
  • 9
  • 28

4 Answers4

3

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
Liam
  • 27,717
  • 28
  • 128
  • 190
  • tried this and added System.Linq namespace too but it says 'DataColumnCollection' doesn not contain a definition for Skip. How do I solve this please – Bibek Aryal Aug 24 '16 at 10:55
  • 1
    use .asenumerable – Neil Aug 24 '16 at 11:04
  • Yeah, you need to case as an IEnumerable. Updated – Liam Aug 24 '16 at 11:04
  • I'm not sure if its count() or length BTW to test for number of columns. Been a while since I've used a DataTable object. It'll be one or the other. I think it's Length on none IEnumerable objects – Liam Aug 24 '16 at 11:06
  • Added AsEnumerable but its giving me error on "dt.Columns". I am beginning to suspect that I am getting all these errors because I got my data as List and used a function to convert them to datatable. I will try and display my data as list itself – Bibek Aryal Aug 24 '16 at 11:17
2

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}
Shannon Holsinger
  • 2,293
  • 1
  • 15
  • 21
0
dt.Columns.RemoveAt(0);

Just remove the column at the specified position.

Liam
  • 27,717
  • 28
  • 128
  • 190
Bogoljub
  • 73
  • 6
0

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.

wgrando
  • 17
  • 6