How to get a DataRow from object - c#

I am trying to reuse some code from a project that works with DataRow instead of object. In my new project I have the model created and I work all with objects but Im trying to bring that piece of code since its very large. So the question is how can I get a DataRow from an object.
class Person
{
public Int64 Id { get; set; }
public string Name { get; set; }
}
Person p1 = new Person();
p1.Id = 1;
p1.Name = "John";
// How to get a DataRow from this p1 object
drPerson["Id"] == 1
drPerson["Name"] == John
I am looking for a way to get done it automatically if that is possible
Thanks!

So finally thanks to the comments I got this code that works but it might be better
public static DataRow ToDataRow(object from) {
DataTable dt = new DataTable();
foreach(PropertyInfo property in from.GetType().GetProperties()) {
DataColumn column = new DataColumn();
column.ColumnName = property.Name;
column.DataType = property.PropertyType;
dt.Columns.Add(column);
}
DataRow dr = dt.NewRow();
foreach(PropertyInfo property in from.GetType().GetProperties()) {
dr[property.Name] = property.GetValue(from);
}
return dr;
}
With these code I can a DataRow with the name of the columns as the object atributes and also the values of it.
-- Edit
Usually DataRow objects don't just hang out by themselves. They will belong to a DataTable. This method is creating a throwaway DataTable just to make a row. - siride
That is right so I've changed it to this
public static DataRow ToDataRow(object from, DataTable dt) {
DataRow dr = dt.NewRow();
foreach(PropertyInfo property in from.GetType().GetProperties()) {
dr[property.Name] = property.GetValue(from);
}
return dr;
}
public static DataTable GetDataTable(object from) {
DataTable dt = new DataTable();
foreach(PropertyInfo property in from.GetType().GetProperties()) {
DataColumn column = new DataColumn();
column.ColumnName = property.Name;
column.DataType = property.PropertyType;
dt.Columns.Add(column);
}
return dt;
}
With this change I can retrieve the DataTable before getting the DataRow and use both

Related

convert an object (list of strings) into data table

I am working in C# and .net core. I have an object which consist of multiple lists of strings and i want to convert this object into datatable.
I have tried this code, but it failed:
public static DataTable ObjectToData(object o)
{
DataTable dt = new DataTable("OutputData");
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
o.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
f.GetValue(o, null);
dt.Columns.Add(f.Name, typeof(string));
dt.Rows[0][f.Name] = f.GetValue(o, null);
}
catch { }
});
return dt;
}
Generic convertion:
public DataTable ListToDataTable<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;
}
your problem is that you add the DataRow at the start of it. what you have to do is instanciate it, and then assign the values and finally add it to the datatable.
Also change the add information into the row for the next dr[f.Name] = f.GetValue(o, null);
here is the code:
public static DataTable ObjectToData(object o)
{
DataTable dt = new DataTable("OutputData");
DataRow dr = dt.NewRow();
o.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
f.GetValue(o, null);
dt.Columns.Add(f.Name, typeof(string));
dr[f.Name] = f.GetValue(o, null);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
});
dt.Rows.Add(dr);
return dt;
}
you can find an example here https://dotnetfiddle.net/EeegHg

How can I set read only property for Particular 'dr' in DATAROW

I try to shown a particular row as a read only format for ListBox. But when getting value from database I can't able to set the read only property for the particular row.
C#:
DataTable dt = new DataTable();
dt.Columns.Add("SectionId", typeof(string));
dt.Columns.Add("RegionalLanguage1", typeof(string));
foreach(DataTable table in dsPopularPrograms.Tables)
{
foreach(DataRow dr in table.Rows)
{
var IsDisable = dr["IsPrabalamanavai"].ToString();
DataRow newRow = dt.NewRow();
newRow["SectionId"] = dr["SectionId"].ToString();
newRow["RegionalLanguage1"] = dr["RegionalLanguage1"].ToString();
if (IsDisable == "D")
{
//Need to set the row as readonly
}
dt.Rows.Add(newRow);
}
}
In the particular condition I want to set the read only property. I don't know how it is.
Please give some suggestion.

How to add new row to an already existing DataTable on Runtime in C# MVC on Runtime

I have a datatable 'tblTest'. When I try to add next row, the first row will get deleted. I need to add data as the second row. Find my code below.
DataTable dt = new DataTable("tblTest"); // Declare as Global.
public JsonResult SaveTestData(string itemCode,int quantity)
{
dt.Columns.Add("ItemCode", typeof(string));
dt.Columns.Add("Quantity", typeof(int));
DataRow dr;
dr = dt.NewRow();
dr["ItemCode"] = itemCode;
dr["Quantity"] = quantity;
dt.Rows.Add(dr);
return Json(1);
}
The 'SaveTestData' function repeats and need to add rows as the next row.
Store DataTable in Session, like this:
public JsonResult SaveTestData(string itemCode, int quantity)
{
DataTable dt = new DataTable("tblTest"); // Declare as Global.
// A table saved in session
if (Session["tblTest"] != null)
{
dt = (DataTable)Session["tblTest"];
}
else // create new table and store in session
{
dt.Columns.Add("ItemCode", typeof(string));
dt.Columns.Add("Quantity", typeof(int));
}
DataRow dr;
dr = dt.NewRow();
dr["ItemCode"] = itemCode;
dr["Quantity"] = quantity;
dt.Rows.Add(dr);
//store new row in session
Session["tblTest"] = dt;
return Json(1);
}

How to get data from neo4j database and bind it into a grid view using C#?

I wrote this cypher query in C#:
var myClint = new GraphClient(new Uri("http://localhost:7474/db/data"), "neo4j", "1412");
myClint.Connect();
var getName= myClint.Cypher.Match("(n:Person)
.Return(n => n.As<Person>())
.Results;
I have setters and getters in Person class to get the name, ssn, and age for everyone in the Person node. I want to display those information on a grid view. I did that with sql server but I do not know how to do it with neo4j.
Thanks in advance
https://stackoverflow.com/users/6771545/abd
In essence, you need to create your own DataTable, you can do it manually with code like this:
public static DataTable ConvertToTable(IEnumerable<Person> people)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Age");
foreach (var person in people)
{
var row = dt.NewRow();
row[0] = person.Name;
row[1] = person.Age;
dt.Rows.Add(row);
}
return dt;
}
But that means you have to write one of those for each type, so you can do this instead:
public static DataTable ConvertToTableAutomatic<T>(IEnumerable<T> items)
{
DataTable dt = new DataTable();
var properties = typeof(T).GetProperties();
foreach (var property in properties)
dt.Columns.Add(property.Name);
foreach (var item in items)
dt.Rows.Add(FillRow<T>(dt.NewRow(), item, properties));
return dt;
}
private static DataRow FillRow<T>(DataRow row, T item, PropertyInfo[] properties)
{
foreach (var property in properties)
row[property.Name] = property.GetValue(item);
return row;
}
But bear in mind - you won't be able to update the Neo4j DB with this, just display the information.

How to work with dataTable?

My given problem is follow:
I have an object with x columns and every column has y values. I must now bring this into Excel.
I found a snippet in which a datatable can be exported easily. So I will bring my object to a datatable. How can I do this?
Language is C#
I'm not completely certain I know what you're trying to do. I assume you want to create a DataTable and load your existing object into it. Assuming your class looks something like this:
public class MyClass {
public int ID {get;set;}
public string Column1 {get;set;}
public DateTime Column2 {get;set;}
// ...
}
and assuming you have a list of them you want to copy into a DataTable, here's how:
DataTable dt = new DataTable("MyTable");
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Column1", typeof(string));
dt.Columns.Add("Column2", typeof(DateTime));
foreach (var o in _myObjectList) {
DataRow dr = dt.NewRow();
dr["ID"] = o.ID;
dr["Column1"] = o.Column1;
dr["Column2"] = o.Column2;
dt.Rows.Add(dr);
}
You can use reflection to get the fields of the object and add the columns to the DataTable:
private bool IsNullableType(Type theType)
{
return (theType.IsGenericType && theType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)));
}
// Create the columns based on the data in the album info - get by reflection
var ai = new <your object without data>;
Type t = ai.GetType();
this.dataTable.TableName = t.Name;
foreach (PropertyInfo p in t.GetProperties())
{
var columnSpec = new DataColumn();
// If nullable get the underlying type
Type propertyType = p.PropertyType;
if (IsNullableType(propertyType))
{
var nc = new NullableConverter(propertyType);
propertyType = nc.UnderlyingType;
}
columnSpec.DataType = propertyType;
columnSpec.ColumnName = p.Name;
this.dataTable.Columns.Add(columnSpec);
}
this.dataGridView.DataSource = dataTable;
Then to add a row to the table:
var info = new <your object with data>;
// Add by reflection
Type t = info.GetType();
var row = new object[t.GetProperties().Length];
int index = 0;
foreach (PropertyInfo p in t.GetProperties())
{
row[index++] = p.GetValue(info, null);
}
this.dataTable.Rows.Add(row);

Categories