C# List to DataTable

  • 495
  • 0

C# List to DataTable

var arr_dara = [];
var len = g_center.getStore().data.length;
if (len > 0) {
	for (var i = 0; i < len; i++) {
		var x = g_center.getStore().getAt(i).data;
		arr_dara.push(x);
	}
}

//console.log(arr_dara);					
//return;

//#region fn
Ext.Ajax.request({
	url: jg_url,
	params: {
		ac: 'update',
		Mydata: JSON.stringify(arr_dara)
	},
	success: function (response, opts) {
		console.log("success");
	},
	failure: function (response, opts) {
		console.log("failure");		
	}
});
//#endregion 
public class UpdateValue {
	public string id { get; set; }
	public string name { get; set; } 
}

 


if (ac == "update") {

	string Mydata = (Request.Form["Mydata"] == "" ? "" : Request.Form["Mydata"]);
	List<UpdateValue> obj = JsonConvert.DeserializeObject<List<UpdateValue>>(Mydata);
	DataTable dt3 = ConvertToDataTable<UpdateValue>(obj);

}

 

public DataTable ConvertToDataTable<T>(IList<T> data)
{
	PropertyDescriptorCollection properties =
	   TypeDescriptor.GetProperties(typeof(T));
	DataTable table = new DataTable();
	foreach (PropertyDescriptor prop in properties)
		table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
	foreach (T item in data)
	{
		DataRow row = table.NewRow();
		foreach (PropertyDescriptor prop in properties)
			row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
		table.Rows.Add(row);
	}
	return table;

}