I want to continue to add data to datatable that already contains data.
In this method, it was get data like: dt = { 1, 2 }.
public class GetRowOne()
{
// some code
if(contains == null)
{
DataRow dr = dt.NewRow();
string[] array1 = lstHeader[1].ToArray();
for (int i = 0; i < 8; i++)
dr[i] = array1[i];
}
// some code
}
dt.Rows.Add(dr.ItemArray);
Now, in another method, I also create and run same like this code.
public class GetRowTwoAndThree()
{
// some code
DataRow dr = dt.NewRow();
string[] array1 = lstHeader[1].ToArray();
for (int i = 0; i < 8; i++)
dr[i] = array1[i];
// some code
}
dt.Rows.Add(dr.ItemArray);
It return new values in dt is: dt = { 4, 5 }
I think error at like: DataRow dr = dt.NewRow(); or line: dt.Rows.Add(dr.ItemArray);
You will look: when dt.Rows.Add(dr.ItemArray). All before data will null, it only add new values to dt.
I want dt save old data and new data, it should be:
dt = { 1, 2, 3, 4 }
Store Data in ViewState["OldData"] and after adding new row again store dt in ViewState["OldData"].
If in same page you are calling method then store that in viewstate, you can also store in session or create get set method for that datatable
DataTable dt{get; set;}
EDIT-:
DataTable dt = new DataTable();
public Form1()
{
InitializeComponent();
dt.Columns.Add("Column1");
dttest = dt;
}
public void GetRowOne()
{
DataRow dr = dt.NewRow();
dr["Column1"] = "Test";
dt.Rows.Add(dr);
dttest = dt;
}
DataTable dttest { get; set; }
private void button1_Click(object sender, EventArgs e)
{
GetRowOne();
}
Related
Use a for loop to generate numbers, 1-100, and add each number to the dataGridView
After I tried with my code, I only showed one line, which is the last 100.
public void aaa(int i) {
DataTable dt = new DataTable();
dt.Columns.Add("host");
DataRow dr = dt.NewRow();
for (int a = 1; a <= i; a++)
{
dr[a] = i;
}
dt.Rows.Add(dr);
this.dataGridView1.DataSource = dt;
}
private void button1_Click(object sender, EventArgs e) {
for (int i = 1; i <= 254; i++)
{
aaa(i);
}
}
your btn_click function. Every loop will initialize or create a new object inside the aaa(i) function
Every time aaa(i) is called in the for loop DataTable dt = new DataTable() will be called
public void aaa(int i)
{
DataTable dt = new DataTable(); ///this will initialize every time, a new data table will be created every loop
dt.Columns.Add("host");
DataRow dr = dt.NewRow();
for (int a = 1; a <= i; a++)
{
dr[a] = i;
}
dt.Rows.Add(dr);
this.dataGridView1.DataSource = dt;
}
}
Might i suggest you pass the 254 int in your aaa(i) function and do the loop inside like
private void button1_Click(object sender, EventArgs e)
{
aaa(254);
}
public void aaa(int i) //value of i = 254
{
DataTable dt = new DataTable();
DataRow dr = dt.NewRow();
for (var s = 0; s <= i; s++ ) {
for (int a = 1; a <= i; a++)
{
dr[a] = i;
}
dt.Rows.Add(dr);
this.dataGridView1.DataSource = dt;
}
}
}
or if the reason for the loop in the button is just for the number limit in the loop inside void aaa then you can simplify it as
public void aaa(int i) //value of i = 254
{
DataTable dt = new DataTable();
DataRow dr = dt.NewRow();
for (int a = 1; a <= i; a++)
{
dr[a] = i;
}
dt.Rows.Add(dr);
this.dataGridView1.DataSource = dt;
}
}
I thought of the available solutions myself.
DataTable dt = new DataTable();
dt.Columns.Add("number");
int i = 10;
int a = 0;
while (a<=i)
{
DataRow dr = dt.NewRow();
a++;
dr[0] = a;
dt.Rows.Add(dr);
}
this.dataGridView1.DataSource = dt;
I always do this like that
ListCollectionView collectionView;
collectionView = new ListCollectionView(*your list of items*);
datagridView1.ItemSource = collectionView;
Implementing like this give you in future open way for sorting, filtering etc. Here is link to ms documentation. where you will find more information about listCollectionView.
I am trying to load back values from a CSV to my class. Then display the values to my datatable. However, I get the error even after my values have been loaded into the class and placed inside the intended columns (See Figure 1). The error occurred at dt.Rows.Add(dr);. Below is my code:
public Newdatagrid()
{
InitializeComponent();
//Do datatable
ds = new DataSet();
dt = new DataTable();
dt.Columns.Add("Bus Model", typeof(string));//0
dt.Columns.Add("Bus Type", typeof(string));//1
dt.Columns.Add("Mileage", typeof(string));//2
if (Savestate.vehnochange_list.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
dr["Bus Model"] = Savestate.busmodel_list[Savestate.busmodel_list.Count];//0
dr["Bus Type"] = Savestate.bustype_list[Savestate.bustype_list.Count];//1
dr["Mileage"] = Savestate.busmileage_list[Savestate.busmileage_list.Count];//2
}
dt.Rows.Add(dr);
this.dataGridView2.DataSource = dt;
}
}
I think you want something like this:
public Newdatagrid()
{
InitializeComponent();
//Do datatable
ds = new DataSet();
dt = new DataTable();
dt.Columns.Add("Bus Model", typeof(string));//0
dt.Columns.Add("Bus Type", typeof(string));//1
dt.Columns.Add("Mileage", typeof(string));//2
if (Savestate.vehnochange_list.Count > 0)
{
for (int i=0; i < Savestate.vehnochange_list.Count; ++i)
{
DataRow dr = dt.NewRow();
dr["Bus Model"] = Savestate.busmodel_list[i];//0
dr["Bus Type"] = Savestate.bustype_list[i];//1
dr["Mileage"] = Savestate.busmileage_list[i];//2
dt.Rows.Add(dr);
}
this.dataGridView2.DataSource = dt;
}
}
I have one array.
I save this array to DataTable.
My code like:
string[] myResult;
DataTable dt = new DataTable();
dt.Columns.Add("myCategory");
for (int i = 0; i < myResult.Length; i++)
{
DataRow row = dt.NewRow();
row[0] = myResult[i];
dt.Rows.Add(row);
}
My data table like:
myCategory:
-+-+-+-+-+-+-+-+-+-
Student
Micheal
7.5
9.5
6.5
But I want this save like:
Category Name Score 1 Score 2 Score 3
Student Micheal 7.5 9.5 6.5
How to add columns like this.
You are always assigning the value to the first column with row[0]. Maybe you want to create a table with a single DataRow:
string[] myResult; // initialize ....
DataTable dt = new DataTable();
foreach(string s in myResult)
dt.Columns.Add(); // or a named column, but you haven't provided any informations
DataRow row = dt.Rows.Add(); // already added
for (int i = 0; i < myResult.Length; i++)
row.SetField(i, myResult[i]);
DataColumnCollection.Add() adds columns with a default name ("Column1", "Column2", ...).
Create a class to clear code
class MyResult
{
public String Category { get; set; }
public String Name { get; set; }
public float Score1 { get; set; }
public float Score2 { get; set; }
public float Score3 { get; set; }
}
Write the below code in your function.
List<MyResult> result = new List<MyResult>();
MyResult r1 = new MyResult
{
Category = "Student",
Name = "Micheal",
Score1 = 7.5f,
Score2 = 9.5f,
Score3 = 6.5f
};
result.Add(r1);
DataTable dt = new DataTable();
dt.Columns.Add("Category");
dt.Columns.Add("Name");
dt.Columns.Add("Score1");
dt.Columns.Add("Score2");
dt.Columns.Add("Score3");
foreach (MyResult item in result)
{
DataRow row = dt.NewRow();
row["Category"] = item.Category;
row["Name"] = item.Name;
row["Score1"] = item.Score1;
row["Score2"] = item.Score2;
row["Score3"] = item.Score3;
dt.Rows.Add(row);
}
You need more columns and also you should add your new row to your dt after the loop. So this should be what you want:
string[] myResult = {"Student" , "Micheal" , "7.5" , "9.5" , "6.5"};
DataTable dt = new DataTable();
dt.Columns.Add("myCategory");
dt.Columns.Add("Name");
dt.Columns.Add("Score 1");
dt.Columns.Add("Score 2");
dt.Columns.Add("Score 3");
DataRow row = dt.NewRow();
for (int i = 0; i < myResult.Length; i++)
{
row[i] = myResult[i];
}
dt.Rows.Add(row);
The result in a DataGridView:
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;
}
I am using this code to get data from a dataReader into a DataTable which can then be serialised.
However, it looks like any column with a null value isnt being written to the xml.
I cant see the issue.
This is my entire class, and im calling this method
Process(IDataReader data, string filePath)
Im certain that this works, because i have used it to serialise dataTables before
Process(DataTable table, string filePath)
So i think it must be in the "GetDataTableFromSqlDataReader" method??
public class DataSerialisation
{
public static DataRow GetFirstDataRow(string xmlFilePath)
{
return GetDataTable(xmlFilePath).Rows[0];
}
public static DataTable GetDataTable(string xmlFilePath)
{
DataSet ds = new DataSet();
ds.ReadXml(xmlFilePath);
return ds.Tables[0];
}
private static DataTable GetDataTableFromSqlDataReader(IDataReader dr)
{
DataTable dtSchema = dr.GetSchemaTable();
DataTable dt = new DataTable();
ArrayList listCols = new ArrayList();
if (dtSchema != null)
{
foreach (DataRow drow in dtSchema.Rows)
{
string columnName = Convert.ToString(drow["columnName"]); //drow["columnName"].ToString();
DataColumn column = new DataColumn(columnName, (Type) (drow["DataType"]));
//column.ColumnName = columnName;
//column.Unique = (bool) (drow["IsUnique"]);
column.AllowDBNull = (bool) (drow["AllowDBNull"]);
//column.AutoIncrement = (bool) (drow["IsAutoIncrement"]);
//column.AutoIncrement = (bool) (drow["IsAutoIncrement"]);
listCols.Add(column);
dt.Columns.Add(column);
}
while (dr.Read())
{
DataRow dataRow = dt.NewRow();
for (int i = 0; i < listCols.Count; i++)
dataRow[((DataColumn) listCols[i])] = dr[i];
dt.Rows.Add(dataRow);
}
}
return dt;
}
public static void Process(IDataReader data, string filePath)
{
Process(GetDataTableFromSqlDataReader(data), filePath);
}
public static void Process(DataTable table, string filePath)
{
DataSet ds = new DataSet();
ds.Tables.Add(table.Clone());
foreach (DataRow row in table.Rows)
{
DataRow newRow = ds.Tables[0].NewRow();
for (int col = 0; col < ds.Tables[0].Columns.Count; col++)
newRow[col] = row[col];
ds.Tables[0].Rows.Add(newRow);
}
ds.WriteXml(new StreamWriter(filePath));
}
}