How to add data to datatable - c#

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);
}

Related

Sum DataTable Columns

Trying to do a sum of each column in a DataTable that i have set up. The First 2 columns in the datatable contain text and the rest of the columns contain numeric values that i would like to sum.
I get a error saying there is no row at position 17.
when i scroll down the DataTable viewer you can see there is no row at 17 and cant see why the foreach is hitting this row.
I have the following code
for (int i = 2; i < DT.Columns.Count; i++)
{
foreach (DataRow DR in DT.Rows)
{
ColumnTotal = ColumnTotal + int.Parse(DR[i].ToString());
}
DT.Rows[DT.Rows.Count + 1][i] = ColumnTotal;
ColumnTotal = 0;
}
Can anyone advise me on what i am doing wrong and how i can improve on it.
Thanks
You are trying to assign in 17-th row but it does not exist. So first create it and then populate it like below:
var row = DT.NewRow();
for (int i = 2; i < DT.Columns.Count; i++)
{
ColumnTotal = 0;
foreach (DataRow DR in DT.Rows)
{
ColumnTotal = ColumnTotal + int.Parse(DR[i].ToString());
}
row[i] = ColumnTotal;
}
DT.Rows.Add(row);
You can not set the value in row like this
DT.Rows[DT.Rows.Count + 1][i] = ColumnTotal;
Because it has no 17th row, You may need to add a new row.
Do something like,
DataRow newRow = DT.NewRow();
for (int i = 2; i < DT.Columns.Count; i++)
{
foreach (DataRow DR in DT.Rows)
{
ColumnTotal = ColumnTotal + int.Parse(DR[i].ToString());
}
newRow[i] = ColumnTotal;
ColumnTotal = 0;
}
DT.Rows.Add(newRow);
simple my dear friend
Datatable Dt=new DataTable();
Dt.Columns.Add("Name");
Dt.Columns.Add("Amount");
Dt.Columns.Add("Id");
Dt.Rows.Add("Harsh","100", "1");
Dt.Rows.Add("Miller","200", "2");
now to calculate use this
object Sum = Dt.Compute(" SUM(Amount) ","");
double NetTotal = Double.Parse(Sum.ToString());

Repost (sort of) -- Invalid Cast AGAIN (DataTable Row Summation)

I have the ability to total each column and add the row -- using this block of code :
DataRow totalRow = t.NewRow();
int colCount = 1;
for (int j = 1; j < t.Columns.Count; j++)
{
if (t.Columns[j].ColumnName == "Client")
{
t.Columns.Cast<DataColumn>().Skip(1);
}
else
{
int colTotal = 0;
for (int i = 1; i < t.Rows.Count; i++)
{
colTotal += Convert.ToInt32(t.Rows[i][j]);
totalRow[t.Columns[j].ColumnName] = colTotal;
}
}
++colCount;
}
t.Rows.Add(totalRow); <br>
**WHY O WHY Can't I just alter this OR use this block (below) to total the rows and insert a new column with the totals of each row??? I don't know why I'm having such a block on this--I'm sure it's relatively simple I just am not seeing it! It is driving me nuts -- I've been at this for 3 days --its sad.
int sum = 0;
foreach (DataRow rows in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
for (int j = 0; j < dt.Rows.Count; j++)
{
int number = Convert.ToInt32(dt.Rows[j].Field<int>(i));
sum += number;
}
}
rows["testrow"] = sum;
}
dataGridView1.DataSource = dt;
}
The error is still "Specified cast in not valid" -- The datatable is coming from an excel sheet. I can use it on a self-made DataTable just fine. I don't understand.
This block of code works just fine and gives me the sum of the rows in a new column
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("amount1", typeof(int));
dt.Columns.Add("amount2", typeof(int));
dt.Columns.Add("amount3", typeof(int));
dt.Columns.Add("amount4", typeof(int));
dt.Columns.Add("Row Totals", typeof(int));
DataRow dr = dt.NewRow();
dr[0] = 100;
dr[1] = 200;
dr[2] = 300;
dr[3] = 400;
dr[4] = 0;
dt.Rows.Add(dr);
int sum = 0;
for (int i = 0; i < dt.Columns.Count; i++)
{
for (int j = 0; j < dt.Rows.Count; j++)
{
// int sum = 0;
int number = dt.Rows[j].Field<int>(i);
sum += number;
}
}
It seems likely that it's not an int but a long (or byte) you can cast a long to int but you can't unbox a long to an int which the code in question tries to do.
if that's the case you can do something like
var sum = (from column in dt.Columns.AsEnumerable<DataColum>().Skip(1)
from row in dt.Rows.AsEnumerable<DataRow>().Skip(1)
where column.ColumnName != "Client"
select (long)row[column]).Sum();
Drum roll please ---
Thank you guys for comments and suggestions they did help me get to this point understanding what exactly was going on behind the scenes.
System.Data.DataTable dt = ds.Tables[0];
dt.Columns.Add("testrow", typeof(int));
DataRow dr = dt.NewRow();
int sum = 0;
for (int i = 1; i < dt.Columns.Count; i++)
{
for (int j = 1; j < dt.Rows.Count; j++)
{
if (j == dt.Rows.Count - 1)
{
dt.Rows[i][j] = Convert.ToInt32(sum);
sum = 0;
}
else
{
object number = dt.Rows[i][j];
sum += Convert.ToInt32(number);
}
}
dataGridView1.DataSource = dt;
}

Convert SQLCEResultSet resultview to datatable

Is it possible to convert a sqlceresultset.resultview to datatable?
Not tested, but this should do what you need:
public DataTable ResultSetToDataTable(SqlCeResultSet set)
{
DataTable dt = new DataTable();
// copy columns
for (int col = 0; col < set.FieldCount; col++)
{
dt.Columns.Add(set.GetName(col), set.GetFieldType(col));
}
// copy data
while (set.Read())
{
DataRow row = dt.NewRow();
for (int col = 0; col < set.FieldCount; col++)
{
int ordinal = set.GetOrdinal(GetName(col));
row[col] = set.GetValue(ordinal);
}
dt.Rows.Add(row);
}
return dt;
}
There's no built-in way to do this (that I know of), probably because a SqlCeResultSet does not store actual data like a DataTable does.

fill gridview cell-by-cell

I want to populate GridView below with images:
<asp:GridView ID="GrdDynamic" runat="server" AutoGenerateColumns="False">
<Columns>
</Columns>
</asp:GridView>
The code below iterates through directory, then I collect image titles and want them to be populated in gridview. code in bold is not working well, gridview is only filled with the last image in list.
List<string> imagelist = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
foreach (String image in Directory.GetFiles(Server.MapPath("example/")))
{
imagelist.Add("~/example/" + Path.GetFileName(image));
}
loadDynamicGrid(imagelist);
}
private void loadDynamicGrid(List<string> list)
{
DataTable dt = new DataTable();
DataColumn dcol = new DataColumn(NAME, typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("NAME1", typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("NAME2", typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("NAME3", typeof(System.String));
dt.Columns.Add(dcol);
DataRow drow = dt.NewRow();
dt.Rows.Add();
dt.Rows.Add();
**for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
foreach (string value in list)
{
dt.Rows[i][j] = value;
}
}
}**
foreach (DataColumn col in dt.Columns)
{
ImageField bfield = new ImageField();
bfield.DataImageUrlField = NAME;
bfield.HeaderText = col.ColumnName;
GrdDynamic.Columns.Add(bfield);
}
GrdDynamic.DataSource = dt;
GrdDynamic.DataBind();
}
how to fill gridview cell-by-cell only with available amount of images?
i know it is easy, i tried various methods like: dt.Rows.Add(list); and some other attempts, but they didn't work. i'm very stupid.
i'd be glad for any help.
You're repeatedly setting every cell to every string with your foreach. You need to addess a specific element in list that will correspond to the specific cell. Try something like this:
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
//below line assumes list has more than i*j elements
//how you want to handle anything outside that case
//is not clear
dt.Rows[i][j] = list[(i * dt.Columns.Count) + j] ;
}
}
Edit: Reading your question more carefully, your problem is fundamentally outside of that loop. Even if you applied the above fix, you still wouldn't get what you're hoping for. What you need to do is loop over the list, and add each item in the list a row, and add that row to the table. Something like this:
int currColIndex = 0;
DataRow drow = dt.NewRow();
foreach(string value in list)
{
if(currColIndex >= dt.Columns.Count)
{
dt.Rows.Add(drow);
drow = dt.NewRow();
currColIndex = 0;
}
drow[currColIndex++] = value;
}
if(currColIndex != dt.Columns.Count)
{
dt.Rows.Add(drow);
}

Why does converting a datasource to a datatable prevent formating

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.

Categories

Resources