We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

How to bind data from a datatable object to a grid

I am currently work in on a project that has a search module that returns its results in the form of a DataTable object. The DataTable columns are dynamic depending on the search results, so I can't convert this into any structured object with properties to map the data to. Is there a way to transform this type of datatable into something that the Syncfusion MVC Grid can use?

thanks in advance,
Gary Cryer


1 Reply

RR Ranjithkumar R G Syncfusion Team April 4, 2012 03:52 AM UTC


Hi Gary,

Thanks for using Syncfusion products.


We suggest you to convert DataTable into any IEumerable datasource. We can bind any number of datatables to the grid by defining the object instead of defining the type to bind the grid. Please refer to the below code snippet to convert DataTable into list and databinding to the grid.

[Student.cs]



public class Student
{
public string Id {get;set;}
public string Name{get;set;}
public string Class{get;set;}
}

public class StudentDataContext
{
public List StudentList
{
get
{
List student = new List();
IEnumerable Student1=GetData().AsEnumerable();
foreach (var s in Student1)
{
string[] stud = this.ToStringArray(s.ItemArray);
student.Add(new Student() { Id = stud[0], Name = stud[1], Class = stud[2] });
}
return student;
}
}
private DataTable GetData()
{
DataTable dt = new DataTable();
dt.Columns.Add("Id");
dt.Columns.Add("Name");
dt.Columns.Add("Class ");
DataRow dr = null;
for (int i = 0; i <= 29; i++)
{
dr = dt.NewRow();
dr[0] = "DS001" + i.ToString();
dr[1] = "Student Name " + i.ToString();
dr[2] = "Class " + i.ToString();
dt.Rows.Add(dr);
}
return dt;
}

private string[] ToStringArray(object[] values)
{
string[] stringArray = new string[values.Length];
for (int i = 0; i < values.Length; i++)
{
stringArray[i] = values[i].ToString();
}
return stringArray;
}
}



[ASPX]



<%--defining object instead of type--%>

<%= Html.Syncfusion().Grid<object>("flatgrid",(GridPropertiesModel<object>)ViewData["GridModel"])%>




[HomeController]



public ActionResult Index(string datatype, object data)
{
GridPropertiesModel<object> model = new GridPropertiesModel<object>()
{
Caption = " Grid",
AllowSorting = true,
AllowPaging = true,

};
if (datatype == "Student")
model.DataSource = new StudentDataContext().StudentList.ToList();
else
model.DataSource = new ProductDataContext().ProductList.ToList();
ViewData["GridModel"] = model;

return View();
}





Please refer to the below link to download the modified sample application.

http://www.syncfusion.com/downloads/Support/DirectTrac/General/sample339266687.zip


Please let me know if you have any concern.

Regards,
Ranjithkumar.





Loader.
Live Chat Icon For mobile
Up arrow icon