How to add column dynamically in datatable in c# - c#

i want to create datatable in which i want to add column names dynamically, my column names are coming from database, which is not fixed column name every time different its depend on user selection
i using sql server and c#.

Following code add column and row dynamically in the datatable:
DataTable dt = new DataTable();
var properties = typeof(model).GetProperties();
foreach (PropertyInfo p in properties)
{
dt.Columns.Add(p.Name, p.PropertyType);
}
foreach (var data in taskData)
{
var values = new object[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
values[i] = properties[i].GetValue(data, null);
}
dt.Rows.Add(values);
}

Here is an option
var dt = new DataTable();
dt.Columns.Add("Name",typeof(string));

you may also try this one.
var dt = new DataTable();
DataColumn column = new DataColumn();
{
column.Caption = "Name";
column.ColumnName = "ColumnName";
column.DataType = typeof(String);
dt.Columns.Add(column);
}

Related

How I can add these two variable which have Multiple values in DataTable?

Here and Two Variable Store Two tables Data Now I want to Add these tables in to DataTable through Foreach Loop ?
var meterData = MeterTable(startDateTime, endDateTime);
var levelData = LevelTable(startDateTime, endDateTime);
var dataTable = new DataTable();
dataTable.Columns.Add("Meter", typeof(string));
dataTable.Columns.Add("Volume", typeof(int));
dataTable.Columns.Add("OpeningBalance", typeof(int));
dataTable.Columns.Add("IN", typeof(int));
dataTable.Columns.Add("Transfer", typeof(int));
dataTable.Columns.Add("OUT", typeof(int));
dataTable.Columns.Add("ClosingBalance", typeof(int));
// how Onward i have not any idea ?
If you want all columns from each table you can do this:
var newTable = new DataTable();
//Copy the meter table into your new table
newTable = meterData.Copy();
//Use .Merge to merge in the level table
newTable.Merge(levelData);
If you want to add new rows, you create a datarow and add it to the datatable:
// Create new DataRow objects and add to DataTable.
for(int i = 0; i < someNumberOfRows; i++)
{
row = newTable.NewRow();
row["column1"] = i;
row["column2"] = "item " + i.ToString();
newTable.Rows.Add(row);
}
If you need to use foreach, I'm assuming you want to iterate the rows in your 2 tables:
foreach(DataRow r in meterData.Rows)
{
row = newTable.NewRow();
row["someColumn"] = r["someColumn"];
row["someOtherColumn"] = r["someOtherColumn"];
newTable.Rows.Add(row);
}
you can add new row through foreach loop like this
var dataTable = new DataTable();
dataTable.Columns.Add("Meter", typeof(string));
dataTable.Columns.Add("Volume", typeof(int));
foreach (var items in Source) //source is the where you want to loop
{
DataRow row = dataTable.NewRow();
row["Meter"] = "meter";
//you can access value of source items through item.NameofTargetField like items.meter
row["Volume"] = 11;
dataTable.Rows.Add(row);
}

Why does SqlDataAdapter's fill not allow me to add a row with the same its own rows' value as appearance?

Why does SqlDataAdapter's Fill method not allow me to add a row with the same its own rows' value as appearance? I could not success to provide a row's value that appears at the same row with filled one in DataTable.
Check this out:
using (SqlDataAdapter a = new SqlDataAdapter("SELECT SIPNO, SERINO, TARIH FROM SNOHAREKETLER WHERE Cast(TARIH as DATE) BETWEEN '2015/03/19' AND '2015/03/20' AND (TEZNO = 'T23' OR TEZNO = 'T31') AND CIKTI is null", c))
{
// 3
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
t.Columns.Add("MyColumn", typeof(string));
DataRow workRow;
int iGetCount = t.Rows.Count;
for (int i = 0; i <= iGetCount - 1; i++)
{
workRow = t.NewRow();
workRow["MyColumn"] = i;
t.Rows.Add(workRow);
}
// 4
// Render data onto the screen
dataGridView1.DataSource = t;
}
Here is the solution of my issue. I searched and consulted someone. My issue was trying to add a NewRow and this causes the issue.
DataTable t = new DataTable();
a.Fill(t);
DataColumn newCol = new DataColumn("NewColumn", typeof(string));
newCol.AllowDBNull = true;
t.Columns.Add(newCol);
foreach (DataRow row in t.Rows)
{
row["NewColumn"] = "With String";
}
dataGridView1.DataSource = t;

SqlBulkCopy.WriteToServer doesn't works

Sorry for asking, but I haven't solved my question by reading another situation like I have.
I have an array with longs and I should insert it into a database, that has only 2 fields: OGRN - bigint, data field, Id - int, identity field. I'm creating a DataTable like this
private static DataTable CreateDataTable()
{
var result = new DataTable();
var ogrn = new DataColumn("Ogrn") {DataType = typeof (long), ColumnName = "Ogrn"};
result.Columns.Add(ogrn);
var id = new DataColumn("Id") { DataType = typeof(int), ColumnName = "Id", AutoIncrement = true };
result.Columns.Add(id);
result.PrimaryKey = new[] { id };
return result;
}
after i'm doing this:
var dt = CreateDataTable();
foreach (long ogrn in ogrns)
{
var row = dt.NewRow();
row["Ogrn"] = ogrn;
dt.AcceptChanges();
}
using (var sqlBulkCopy = new SqlBulkCopy(ConnectionString))
{
sqlBulkCopy.DestinationTableName = "dbo.ULs";
sqlBulkCopy.ColumnMappings.Add("Ogrn", "Ogrn");
sqlBulkCopy.ColumnMappings.Add("Id", "Id");
sqlBulkCopy.WriteToServer(dt);
}
So why doesn't it work? Am I missing something important.
Add the new row to the Table!. That is not something that is automagically done when you call NewRow();
var dt = CreateDataTable();
foreach (long ogrn in ogrns)
{
var row = dt.NewRow();
row["Ogrn"] = ogrn.Ogrn;
dt.Rows.Add(row); // ADD the new row to the table!
}
dt.AcceptChanges();

Specifying the columns of the datatable in a general method C#

I already have the code that specify columns of the dataTable but what I want is to create a general method that has in her parameters: ColumnName and types.
How can I do that?
This is my code:
column = dt.Columns.Add();
column.ColumnName = "IPPName";
column.DataType = typeof(String);
column = dt.Columns.Add();
column.ColumnName = "tagName";
column.DataType = typeof(String);
column = dt.Columns.Add();
column.ColumnName = "time";
column.DataType = typeof(String);
column = dt.Columns.Add();
column.ColumnName = "value";
column.DataType = typeof(Double);
column = dt.Columns.Add();
column.ColumnName = "qtity";
column.DataType = typeof(Double);
I dont know if I understand question correctly. Do you want to implement something like this ?
public DataTable CreateDataTable(Dictionary<string,Type> columns)
{
DataTable dt = new DataTable();
foreach( var key in columns)
{
var column = dt.Columns.Add();
column.ColumnName = key.Key;
column.DataType = key.Value;
}
return dt;
}
public void CreateNewDataTable()
{
var columns = new Dictionary<string, Type>()
{
{"column", typeof (string)}
};
var dt = CreateDataTable(columns);
}
An additional way to solve it using extensionmethods. I believe it is a tad easier to follow than #adt answer and more useful since it can be called on an already existing DataTable.
If you need help regarding extensionmethods, have a look at this description or just ask :)
public static class DataTableExtentions {
public static void AddColumn(this DataTable table, string columnName, Type columnType)
{
var col = table.Columns.Add();
col.ColumnName = columnName;
col.DataType = columnType;
}
}
And it would be called like this:
column = dt.AddColumn("IPPName", typeof(String));
column = dt.AddColumn("tagName", typeof(String));
column = dt.AddColumn("time", typeof(String));
column = dt.AddColumn("value", typeof(Double));
column = dt.AddColumn("qtity", typeof(Double));

Convert datatable to datareader

For Performance improvement I want to convert datatable to datareader. I can not do that through query. So is there any other way to do so?
I know this is old, but the answers here seem to have missed the point of the OPs question.
DataTables have a method called CreateDataReader which will allow you to convert a DataTable to a DbDataReader object. In this case a DataTableReader.
DataTable table = new DataTable();
//Fill table with data
//table = YourGetDataMethod();
DataTableReader reader = table.CreateDataReader();
I should point out that this will not increase performance since you should be using one or the other.
Here are some more resources on the matter:
DataReader Vs DataTable
Is datareader quicker than dataset when populating a datatable?
For example
public DataTable ConvertDataReaderToDataTable(SqlDataReader dataReader)
{
DataTable datatable = new DataTable();
DataTable schemaTable = dataReader.GetSchemaTable();
try
{
foreach (DataRow myRow in schemaTable.Rows)
{
DataColumn myDataColumn = new DataColumn();
myDataColumn.DataType = myRow.GetType();
myDataColumn.ColumnName = myRow[0].ToString();
datatable.Columns.Add(myDataColumn);
}
while (dataReader.Read())
{
DataRow myDataRow = datatable.NewRow();
for (int i = 0; i < schemaTable.Rows.Count; i++)
{
myDataRow[i] = dataReader[i].ToString();
}
datatable.Rows.Add(myDataRow);
myDataRow = null;
}
schemaTable = null;
return datatable;
}
catch (Exception ex)
{
Error.Log(ex.ToString());
return datatable;
}
}
Use DataTable constructor,
DataTable table = new DataTable();
//Fill table with data
DataTableReader reader = new DataTableReader(table);
Good Look!
public DataTable GetTable(IDataReader _reader)
{
DataTable dataTable1 = _reader.GetSchemaTable();
DataTable dataTable2 = new DataTable();
string[] arrayList = new string[dataTable1.Rows.Count];
for (int i = 0; i < dataTable1.Rows.Count; i++)
{
DataColumn dataColumn = new DataColumn();
if (!dataTable2.Columns.Contains(dataTable1.Rows[i]["ColumnName "].ToString()))
{
dataColumn.ColumnName = dataTable1.Rows[i]["ColumnName "].ToString();
dataColumn.Unique = Convert.ToBoolean(dataTable1.Rows[i]["IsUnique "]);
dataColumn.AllowDBNull = Convert.ToBoolean(dataTable1.Rows[i]["AllowDBNull "]);
dataColumn.ReadOnly = Convert.ToBoolean(dataTable1.Rows[i]["IsReadOnly "]);
dataColumn.DataType = (Type)dataTable1.Rows[i]["DataType "];
arrayList[i] = dataColumn.ColumnName;
dataTable2.Columns.Add(dataColumn);
}
}
dataTable2.BeginLoadData();
while (_reader.Read())
{
DataRow dataRow = dataTable2.NewRow();
for (int j = 0; j < arrayList.Length; j++)
{
dataRow[arrayList[j]] = _reader[arrayList[j]];
}
dataTable2.Rows.Add(dataRow);
}
_reader.Close();
dataTable2.EndLoadData();
return dataTable2;
}

Categories

Resources