My Datagrid is filled with the right number of rows, but there are no data show.
All the row are display empty cols.
What could be the reason for that ?
basedon
It is the first time I use a datagridview.
public void BindDataGridView(DataGridView dgv, Hashtable ht) {
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add("test");
//now build our table
dt.Columns.Add("col1", typeof(string));
dt.Columns.Add("col2", typeof(Int32));
IDictionaryEnumerator enumerator = ht.GetEnumerator();
DataRow row = null;
while (enumerator.MoveNext()) {
string index = (string)enumerator.Key; // boekingsREf
MyClass a = (MyClass)enumerator.Value;
row = dt.NewRow();
row["col1"] = index;
row["col2"] = a.number;
dt.Rows.Add(row);
}
//dgv.DataSource = ds.Tables[0];
dgv.DataSource = ds.Tables[0];
}
First example:
public Form1()
{
InitializeComponent();
Hashtable ht = new Hashtable();
ht[1] = "One";
ht[2] = "Two";
ht[3] = "Three";
BindDataGridView(dataGridView1, ht);
}
public void BindDataGridView(DataGridView dgv, Hashtable ht)
{
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add("test");
//now build our table
dt.Columns.Add("col1", typeof(int));
dt.Columns.Add("col2", typeof(string));
foreach (DictionaryEntry dictionaryEntry in ht)
{
int index = (int)dictionaryEntry.Key;
string value = (string)dictionaryEntry.Value;
DataRow row = dt.NewRow();
row["col1"] = index;
row["col2"] = value;
dt.Rows.Add(row);
}
dgv.DataSource = ds.Tables[0];
}
Second example:
Assuming your MyClass is
public class MyClass
{
public int number { get; set; }
static public implicit operator MyClass(int value)
{
return new MyClass() { number = value };
}
}
and the hashtable is (reverse keys/values)
Hashtable ht = new Hashtable();
ht["One"] = 1;
ht["Two"] = 2;
ht["Three"] = 3;
and you change this line from your post code
MyClass a = (int)enumerator.Value;
Related
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 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();
}
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:
I have a program by VC2008 that send dataTable I sended it using the constractor I solve it help at losing data entered in dataview C# - to datagridview in another Form it work fine but I want to send only the new row I tried to copy using ImportRrow it to another datatable but it gives Form2 Blank.
and I send the data as datatable by method as following:
public DataTable showout2()
{
DataTable dtab = new DataTable();
DataColumn dc1 = new DataColumn("رقم المتسلسل");
DataColumn dc2 = new DataColumn("رقم الحساب");
DataColumn dc3 = new DataColumn("أسم الحساب");
DataColumn dc4 = new DataColumn("المالك");
DataColumn dc5 = new DataColumn("قيمة");
DataColumn dc6 = new DataColumn("نوع العملة");
DataColumn dc7 = new DataColumn("الدائن");
DataColumn dc8= new DataColumn("المدين");
DataColumn dc9= new DataColumn("تاريخ");
DataColumn dc10 = new DataColumn("تفاصيل");
dtab.Columns.Add(dc1);
dtab.Columns.Add(dc2);
dtab.Columns.Add(dc3);
dtab.Columns.Add(dc4);
dtab.Columns.Add(dc5);
dtab.Columns.Add(dc6);
dtab.Columns.Add(dc7);
dtab.Columns.Add(dc8);
dtab.Columns.Add(dc9);
dtab.Columns.Add(dc10);
DateTime date = new DateTime();
date = DateTime.Now;
// Create an array for the values.
object[] newRow = new object[10];
Set the values of the array.
string s = numb.Text;
newRow[0] = numb.Text;
newRow[1] = Account_numb.Text;
newRow[2] = Account_nam.Text;
newRow[3] = owner.Text;
newRow[4] = curency.Text;
newRow[5] = comboBox1.Text;
newRow[6] = Depet.Text;
newRow[7] = cridet.Text;
newRow[8] = date.ToString();
newRow[9] = note.Text;
declare DataRow and adding it to DataTable
DataRow row;
dtab.BeginLoadData();
// Add the new row to the rows collection.
row = dtab.LoadDataRow(newRow, true);
return dtab;
}
I transfer the data from Form as following
cashagree fm = cashagree(shouwout2());
I copy the datarow in constractor take datatable as prameter as following:
public Cashagree(DataTable d2)
{
dt.ImportRow(d2.Rows[0]);
}
here I assign the datasource and mange the secound datagridview
private void Cashagree_Load_1(object sender, EventArgs e)
{
try
{
for (int i = 0; i != dt.Rows.Count; i++){
label1.Text= dt.Rows[i].ToString();
if (string.IsNullOrEmpty(dt.Rows[i].ToString()))
{
MessageBox.Show("This is empty");
}
}
dataGridView.DataSource = dt;
dataGridView.Columns[3].Visible = false;
dataGridView.Columns[4].Visible = false;
dataGridView.Columns[5].Visible = false;
dataGridView.Columns[6].Visible = false;
dataGridView.Columns[7].Visible = false;
}
catch (Exception w) { MessageBox.Show("Error" + w.StackTrace); }
}
thank you for helping
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));
}
}