Why does converting a datasource to a datatable prevent formating - c#

I have come accross a strange problem that can be illustrated using the 2 seperate code blocks below.
If i use the first block, you can clearly see that column 5 has a currency format applied to it.
Using the second block where the only difference is that the string array is added to a datatable and then used as the datasource -> no formatting is applied!
Can anyone explain this behaivour and provide a workaround for me? I am using a large datatable that i will need to format.
Thanks!
Block 1:
string[] list = new string[10];
for (int i = 0; i < 10; i++)
{
list[i] = i.ToString();
}
this.dataGridViewX1.DataSource = list;
this.dataGridViewX1[0, 5].Style.Format = "C2";
Block 2:
string[] list = new string[10];
for (int i = 0; i < 10; i++)
{
list[i] = i.ToString();
}
DataTable dt = new DataTable();
dt.Columns.Add();
for (int i = 0; i < list.Length; i++)
{
DataRow dr = dt.NewRow();
dr[0] = list[i];
dt.Rows.Add(dr);
}
this.dataGridViewX1.DataSource = dt;
this.dataGridViewX1[0, 5].Style.Format = "C2";

Don't you need to set the DataColumn DataType?
DataColumn col1;
col1.DataType = Type.GetType("System.DateTime"); // or other type

the First One uses the datatables binding. use reflector to figure out what Happens there.

Related

How to add data to datatable

I want to add data to datatable within a loop in c# but I cannot.
I use this code but it runs 1 time not more. When i=2 it dose not work.
Please help.
DataTable dt = new DataTable();
dt.Columns.Add("ProductId");
dt.Columns.Add("ProductTotalPrice");
DataRow dr = dt.NewRow();
for (int i = 0; i < 10; i++)
{
dr["ProductId"] = i.ToString();
dr["ProductTotalPrice"] = (i*1000).ToString();
dt.Rows.Add(dr);
}
That's cause you are creating only one DataRow outside loop and so you are actually over writing the old values in that row with new one's. Your row creation should be inside loop and thus you will have new row per iteration like
DataTable dt = new DataTable();
dt.Columns.Add("ProductId");
dt.Columns.Add("ProductTotalPrice");
DataRow dr = null;
for (int i = 0; i < 10; i++)
{
dr = dt.NewRow(); // have new row on each iteration
dr["ProductId"] = i.ToString();
dr["ProductTotalPrice"] = (i*1000).ToString();
dt.Rows.Add(dr);
}
for (int i = 0; i < 10; i++)
{
dr = dt.NewRow();
dr["ProductId"] = i.ToString();
dr["ProductTotalPrice"] = (i*1000).ToString();
dt.Rows.Add(dr);
}
Should work.
Each time you need to add different dataRow. You're trying to add the same.
Yet another simple way:
for (int i = 0; i < 10; i++)
{
dt.Rows.Add(i, i * 1000);
}

C# winform create columns in datagridview with observableCollection

I used a simple dataTable to load my data before is this way:
DataTable dt = new DataTable("grid");
//split array to width X height dataTable
// create columns
for (int i = 0; i < width; i++)
{
dt.Columns.Add();
}
for (int i = 0; i < height; i++)
{
// create a DataRow using .NewRow()
DataRow row = dt.NewRow();
// iterate over all columns to fill the row
for (int j = 0; j < width; j++)
{
row[j] = grid.Cells[j + (width * i)].State.ToString();
}
// add the current row to the DataTable
dt.Rows.Add(row);
}
dataGridView1.DataSource = dt;
And that worked, but not good enough because i want to update 100x100 matrix of colors fast so i thought about an observable collection.
I have now this code:
ObservableCollection<String> data = new ObservableCollection<String>();
dataGridView1.DataSource = new BindingSource { DataSource = data };
for (int i = 0; i < grid.Cells.Length; i++)
{
data[i] = grid.Cells[i].State.ToString();
}
(grid is my model)
this seems to load all the data but i have no representation to the columns so i have only rows.
How do i specify the amount of columns?
And am i in the right direction?
I used my first lines of code, just added:
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
And now it works just fine.

How to add Year list using for loop in datatable?

I have follwing code but it get error-Input array is longer than the number of columns in this table.
DataTable dtYear = new DataTable();
int Year1 = Convert.ToInt32(DateTime.Now.ToString("yyyy"));
for (i = 1980; i <= Year1; i++)
{
dtYear.Rows.Add(i);
}
ddlYear.DataSource = dtYear;
ddlYear.DataBind();
Your DataTable doesn't contain any columns - so you cant add a row containing a value for a column.
Edit:
Change your code like this:
DataTable dtYear = new DataTable();
dtYear.Columns.Add("Year", typeof(int)); // add this line
int Year1 = Convert.ToInt32(DateTime.Now.ToString("yyyy"));
for (i = 1980; i <=> Year1; i++)
{
dtYear.Rows.Add(i);
}
ddlYear.DataSource = dtYear;
ddlYear.DataBind();
Add "Year" column to the DataTable first.
dtTable.Columns.Add("Year", typeof(int));
You can use the Year property of the DateTime.
int Year1 = DateTime.Now.Year;
And also you should use a valid compare operator in the for condition. <=> is not valid in c#.
for (i = 1980; i <= Year1; i++)
{
}
You have to add the column to the DataTable first:
DataTable dtYear = new DataTable();
dtYear.Columns.Add("year",typeof(int)); // add the column
int Year1 = Convert.ToInt32(DateTime.Now.ToString("yyyy"));
for (int i = 1980; i <= Year1; i++)
{
dtYear.Rows.Add(i);
}
ddlYear.DataSource = dtYear;
ddlYear.DataBind();
I don't think that your code will even compile, so how is it throwing an error.
use Data Columns before assigning values to row.
here is some modification in your code.
DataTable dtYear = new DataTable();
int Year1 = Convert.ToInt32(DateTime.Now.ToString("yyyy"));
//add columns to DataTable
dtYear.Columns.Add("Years",typeof(int), null);
for (int i = 1980; i <= Year1; i++)
{
dtYear.Rows.Add(i);
}
ddlYear.DataSource = dtYear;
ddlYear.DataTextField = "Years";
ddlYear.DataBind();
hope this will help.

Transposing columns in GridView

I have a data table that contains the data like below.
I want to display it in my Grid View like Following. It is actually the transpose of above table and one additional Row added for Viewing Product Details that will be a link button.
Can you please help me how can I achieve the following requirement in ASP.net using C#.
Many Thanks,
Awais Afzal.
Assuming that you table is a DataTable, you could use such an extension to reorder it:
public static DataTable Pivot(this DataTable tbl)
{
var tblPivot = new DataTable();
tblPivot.Columns.Add(tbl.Columns[0].ColumnName);
for (int i = 1; i < tbl.Rows.Count; i++)
{
tblPivot.Columns.Add(Convert.ToString(i));
}
for (int col = 0; col < tbl.Columns.Count; col++)
{
var r = tblPivot.NewRow();
r[0] = tbl.Columns[col].ToString();
for (int j = 1; j < tbl.Rows.Count; j++)
r[j] = tbl.Rows[j][col];
tblPivot.Rows.Add(r);
}
return tblPivot;
}
and set it as new DataSource:
dataGridView1.DataSource = oldDataTable.Pivot();

Sum of column values in C#

I use these following code to calculating summation of a specific row in the database and show it in a new row under that intention column. but i will encounter an error.
Object reference not set to an instance of an object
Please help me to solve this.
Thanks in advance.
int sum = 0;
for (int i = 0; i < dt.Rows.Count; i++)
{
sum += int.Parse(dataGridView1.Rows[i].Cells["Fee"].Value.ToString());
}
DataSet ds = new DataSet();
adapter.Fill(ds);
DataRow row = ds.Tables["Entry"].NewRow();
ds.Tables["Entry"].Rows.Add(row);
I want to know how can I see the sum in a new row.
i think the error is in the loop statement:
Instead of:
for (int i = 0; i < dt.Rows.Count; i++)
{
sum += int.Parse(dataGridView1.Rows[i].Cells["Fee"].Value.ToString());
}
use this:
for (int i = 0; i < dt.Rows.Count - 1; i++)
{
sum += int.Parse(dataGridView1.Rows[i].Cells["Fee"].Value.ToString());
}
you are starting at Index zero so you should deduct one for the total number of rows. It will return Object reference not set to an instance of an object when it reaches on:
sum += int.Parse(dataGridView1.Rows[dt.Rows.Count].Cells["Fee"].Value.ToString());
because such row does not exists.
UPDATE 1
after the loop, insert this statement:
dataGridView1.Rows.Add("", "", sum)
UPDATE 2
int sum = 0;
for (int i = 0; i < dt.Rows.Count - 1; i++)
{
sum += int.Parse(dataGridView1.Rows[i].Cells["Fee"].Value.ToString());
}
DataSet ds = new DataSet();
adapter.Fill(ds);
DataRow row = ds.Tables["Entry"].NewRow();
row[0] = "";
row[1] = "";
row[2] = sum;
ds.Tables["Entry"].Rows.Add(row);
'ds' doesn't have a table 'Entry', that's why you get a 'Object reference not set to an instance of an object' error.
you can use compute method in datatable. get result from compute method then create new row from datatable then assign to appropriate field. then add the new row to datatable.
Though your question is not very clear but Check out the loop either access value from datatable or from grid
Like
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["Fee"].Value !=null)
sum += int.Parse(dt.Rows[i]["Fee"].Value.ToString());
}
And also make sure dt.Rows[i]["Fee"] does not contain null values
Even you can use Compute method to do the sum.
I suggest you to use the debugger and see where exactly this error occurs :)
It can also happen if the DB returns null for one "FEE" cell.
Run it and see where are you exactly and look at the values, if you see a null you'll need if != null.

Categories

Resources