1

I would like to make my razor code more dinamically. I have more than 100 columns with also more than 100 rows in the datatable (dr).

<table id="PS3" class="report">
<tr id="Parameter_name">
<td id="stick_no" bgcolor='#F0F0F0'>Stick No</td>
<td id="pos" bgcolor='#F0F0F0'>Pos</td>
<td id="id" bgcolor='#F0F0F0'>ID</td>
<td id="type" bgcolor='#F0F0F0'>Type</td>
<td id="packing_datetime" bgcolor='#F0F0F0'>Packing DateTime</td>
</tr>

@if (ViewData["AllEmpData"] != null)
{
    foreach (System.Data.DataRow dr in (ViewData["AllEmpData"] as System.Data.DataTable).Rows)
    {
        <tr>
            <td>
                @dr["stick_no"]
            </td>
            <td align="left">
                @dr["pos"]
            </td>
            <td>
                @dr["id"]
            </td>
            <td align="left">
                @dr["type"]
            </td>
            <td>
                @dr["packing_datetime"]
            </td>
        </tr>
    }
}
</table>

I would like to do something like this in the foreach cycle :

for(i=0; i< column_number; i++){
        <td>
            @dr[column_id[0].toString()]
        </td>
}

Where the column_number is the number of column in the id="Parameter_name" row. So in generally I don't want to write down all of the parameter in the foreach section.

0

1 Answer 1

2

You can use the Columns property of DataTable. like this:

<table id="PS3" class="report">
    <tr id="Parameter_name">
        <td id="stick_no" bgcolor='#F0F0F0'>Stick No</td>
        <td id="pos" bgcolor='#F0F0F0'>Pos</td>
        <td id="id" bgcolor='#F0F0F0'>ID</td>
        <td id="type" bgcolor='#F0F0F0'>Type</td>
        <td id="packing_datetime" bgcolor='#F0F0F0'>Packing DateTime</td>
    </tr>

    @if (ViewData["AllEmpData"] != null)
    {
        var dt = ViewData["AllEmpData"] as System.Data.DataTable;

        foreach (System.Data.DataRow dr in dt.Rows)
        {
            <tr>
                @foreach (System.Data.DataColumn col in dt.Columns)
                {
                    <td>@dr[col.ColumnName].ToString()</td>
                }
            </tr>
        }
    }
</table>

You can create the table headers this way as well. But you should consider converting the DataTable to a list in the controller and use it in the View.

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

1 Comment

Thanks for this. Did what I was looking for. This should be marked as the answer in my opinion. Cheers

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.