I would like to fill a DataTable object from MySql query, and display with DataGrid. The display part of my code works well (It shows a custom DataTable). Somehow the DataTable fill method won't work for me (i copied it from stackoverflow).
If i fill up DataTable from List with this function is works well
DataTable t = ConvertToDataTable(userlist);
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;
}
And below the other people's solution what won't work for me. i think table is null.
string searchQuery = "SELECT * FROM USERS";
MySqlCommand command = new MySqlCommand(searchQuery, connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
DataTable table = new DataTable();
adapter.Fill(table);
GridView1.DataSource = table;
this.GridView1.DataBind();
I also attached my MySQL database sample values.
It doesn't fill the DataGrid show no values. Any tips?
Related
I have correct source DataTable "sourceDataTable" and I call method to split it into several and store the result into DataSet "ds":
DataSet ds = MyClass.SplitDataTables(sourceDataTable);
Here is the method MyClass.SplitDataTables():
public static DataSet SplitDataTables(DataTable sourceDataTable)
{
using (DataSet dsOut = new DataSet())
{
DataTable dt1 = new DataTable;
DataTable dt2 = new DataTable;
DataTable dt3 = new DataTable;
dt1 = sourceDataTable.Clone();
dt2 = sourceDataTable.Clone();
dt3 = sourceDataTable.Clone();
foreach (DataRow row in sourceDataTable.Rows)
{
//column is for example "City" and some row has "Boston" in it, so I put this row into dt1
if (row["ColumnName"].ToString() == "something")
{
dt1.ImportRow(row);
}
else if (...)
{ } //for other DataTables dt2, dt3, etc...
else .......... ;
}
//here I put resulting DataTables into one DataSet which is returned
string[] cols= { "dt1", "dt2", "dt3" };
foreach (string col in cols)
{
dsOut.Tables.Add(col);
}
return dsOut;
}
}
So with this returned DataSet I display new Windows each with one DataTable
foreach (DataTable dtt in ds.Tables)
{
string msg = dtt.TableName;
Window2 win2 = new Window2(dtt, msg);
win2.Show();
}
All I get shown is Windows with placeholder for "empty DataGrid"
Windows code is correct, as it works whith "unsplit DataTable".
I assume code in splitting DataTables is all wrong as it does not output DataSet with filled DataTables. I will greatly appreciate any help on this issue. Thank you!
You don't need a for loop here
Replace below code
string[] cols= { "dt1", "dt2", "dt3" };
foreach (string col in cols)
{
dsOut.Tables.Add(col);
}
With this
dsOut.Tables.Add(dt1);
dsOut.Tables.Add(dt2);
dsOut.Tables.Add(dt3);
Thanks to #Krishna I got this solved. So if you ever encounter similar problem here are 2 things to note:
string[] cols = { "dt1", "dt2", "dt3", ... };
foreach (string col in cols)
{
dsOut.Tables.Add(col);
}
This cycle does not have access to objects of DataTables with same name and writes only empty DataTables into DataSet collection (regardless of same name!).
If you create new DataTable and you will be making it a clone of another DataTable, dont bother yet with setting its name.
DataTable dt1 = new DataTable();
Make new DataTable of same format as source DataTable:
dt1 = sourceDataTable.Clone();
dt2 = sourceDataTable.Clone();
//etc...
Now you have to set unique DataTable names to each DataTable cloned from source DataTable:
dt1.TableName = "Name1";
dt2.TableName = "Name2";
//and so on
Now all works as intended.
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.
I am trying to bind DataTable to DataGridView as below;
DataTable table = new DataTable();
foreach (ConsumerProduct c in ctx.ConsumerProducts)
{
DataRow row = table.NewRow();
row["Id"] = c.ID;
row["Model"] = c.Model;
row["Status"] = "Offline";
table.Rows.Add(row);
}
dataGridView1.DataSource = table;
I get exception at the first line itself row["Id"]
Column 'Id' does not belong to table .
P.S. I have already added these columns in the designer view of dataGridView.
You just created a blank DataTable and then you are trying to add data to particular columns like Id, Model and Status.
You have to add those columns as well.
DataTable table = new DataTable();
table.Columns.Add("Id");
table.Columns.Add("Model");
table.Columns.Add("Status", typeof(string)); //with type
There is no issue in biding.
Also you can project your required column to an Anonymous type and then bind that to your data grid like:
var result = ctx.ConsumerProducts
.Select(r=> new
{
Id = r.ID,
Model = r.Model,
Status = "Offline"
}).ToList();
dataGridView1.DataSource = result;
I have the same issue as here is LINQ join two DataTables
but my datatables are made on runtime like
DataTable dtTML = (DataTable)JsonConvert.DeserializeObject(Convert.ToString(data.Json.Args[0]["TML"]), (typeof(DataTable)));
the solution that someone gave is fine but I am getting error on datarows2 at
select dtResult.LoadDataRow(new object[]
{
dataRows2.Field<int>("stock") // here is error : does not exist in current context
}
while dataRows1.Field(s) are fine
I can't see what's wrong with this approach :
DataTable dt1 = new DataTable();
dt1.Columns.Add("PK", typeof(int));
dt1.Columns.Add("Data1", typeof(int));
DataTable dt2 = new DataTable();
dt2.Columns.Add("FK", typeof(int));
dt2.Columns.Add("Data2", typeof(int));
dt2.Rows.Add(1, 5000);
dt1.Rows.Add(1, 1000);
var Result = (from r1 in dt1.AsEnumerable()
join r2 in dt2.AsEnumerable()
on r1["PK"] equals r2["FK"]
select new
{
A = r1.Field<int>("Data1"),
B = r2.Field<int>("Data2"),
// choose more columns if any
}).ToList();
You can do whatever you want using it. If you need the result to be a Datatable , just use this method [ ListToDataTable ] to convert List to DataTable:
public static DataTable ListToDataTable<T>(List<T> items)
{
System.ComponentModel.PropertyDescriptorCollection properties =
System.ComponentModel.TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (System.ComponentModel.PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in items)
{
DataRow row = table.NewRow();
foreach (System.ComponentModel.PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
I want to convert dataview rowfilter value to datatable. I have a dataset with value. Now i was filter the value using dataview. Now i want to convert dataview filter values to datatable.please help me to copy it........
My partial code is here:
DataSet5TableAdapters.sp_getallempleaveTableAdapter TA = new DataSet5TableAdapters.sp_getallempleaveTableAdapter();
DataSet5.sp_getallempleaveDataTable DS = TA.GetData();
if (DS.Rows.Count > 0)
{
DataView datavw = new DataView();
datavw = DS.DefaultView;
datavw.RowFilter = "fldempid='" + txtempid.Text + "' and fldempname='" + txtempname.Text + "'";
if (datavw.Count > 0)
{
DT = datavw.Table; // i want to copy dataview row filter value to datatable
}
}
please help me...
You can use
if (datavw.Count > 0)
{
DT = datavw.ToTable(); // This will copy dataview's RowFilterd values to datatable
}
You can use DateView.ToTable() for converting the filtered dataview in to a datatable.
DataTable DTb = new DataTable();
DTb = SortView.ToTable();
The answer does not work for my situation because I have columns with expressions. DataView.ToTable() will only copy the values, not the expressions.
First I tried this:
//clone the source table
DataTable filtered = dt.Clone();
//fill the clone with the filtered rows
foreach (DataRowView drv in dt.DefaultView)
{
filtered.Rows.Add(drv.Row.ItemArray);
}
dt = filtered;
but that solution was very slow, even for just 1000 rows.
The solution that worked for me is:
//create a DataTable from the filtered DataView
DataTable filtered = dt.DefaultView.ToTable();
//loop through the columns of the source table and copy the expression to the new table
foreach (DataColumn dc in dt.Columns)
{
if (dc.Expression != "")
{
filtered.Columns[dc.ColumnName].Expression = dc.Expression;
}
}
dt = filtered;
The below code is for Row filter from Dataview and the result converted in DataTable
itemCondView.RowFilter = "DeliveryNumber = '1001'";
dataSet = new DataSet();
dataSet.Tables.Add(itemCondView.ToTable());