Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate MVC Webgrid from DataTable

I am trying to populate a MVC Webgrid using a DataTable which is built up in the code behind and then made enumerable using the AsEnumerable() extension method.

However, when I call the GetHtml method, the output is not what I expect, it consists of two columns HasErrors and RowError and none of the columns I have defined.

Am I missing something?

        DataTable table = new DataTable();
        table.Columns.Add("I/Dia");

        foreach (var item in Variations.Where(item => !table.Columns.Contains(item.CrossSectionalDiameter)))
        {
            table.Columns.Add(item.CrossSectionalDiameter);
        }

        foreach (var item in Variations)
        {
            var r = table.Rows.Add();
            r["I/Dia"] = item.InternalDiameter;
            r[item.CrossSectionalDiameter] = item.Price;
        }

        return table.AsEnumerable();
like image 921
tompipe Avatar asked May 29 '11 15:05

tompipe


1 Answers

I have the similar question. Finally make some work around according to your comment.

        var result = new List<dynamic>();
        foreach (DataRow row in table.Rows)
        {
            var obj = (IDictionary<string, object>)new ExpandoObject();
            foreach (DataColumn col in table.Columns)
            {
                obj.Add(col.ColumnName, row[col.ColumnName]);
            }
            result.Add(obj);
        }
        var grid = new WebGrid(result)
like image 121
Eliot Avatar answered Oct 26 '22 10:10

Eliot