Sum DataTable Columns - c#

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

Related

I need to go through each and every row of a datatable

I have a data table named dt which is a SQL table converted.
All the data was sent from the server so I had to encrypt it. Now I need to decrypt every cell.
I wanted to do it like this:
foreach (DataRow row in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
row[i] = r.Decrypt(row[i].ToString());
}
}
Decrypt works fine but row[i] = r.Decrypt(row[i].ToString()); give me the number of the column instead of its content, how do I get the content?
to make the post make more sense.
i want row[i] = r.Decrypt(a string representing the value of row[i]);
This is the correct way to interact with a datatable
foreach(DataRow row in dt .Rows)
{
foreach(DataColumn column in dt .Columns)
{
Console.WriteLine(row[column]);
}
}
In your case you are literally passing an int to your row, because You are using count property.
** Edit
This is in case Your datarow contains an object.
DataTable dt = new DataTable();
dt.Columns.Add("Column 1");
dt.Columns.Add("Column 2");
DataRow dataRow = dt.NewRow();
dataRow.ItemArray = new object[]{"line 1 column 1", "line 1 column 2"
};
dt.Rows.Add(dataRow);
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
var text = row[column.ToString()];
Console.WriteLine(text);
}
}
Result
If none of this work, We would have to see how Your data row is created.
As you mentioned that the other logic (Decrypt) is working fine and you just need to fetch the column content/values then you can try something like:
foreach(DataRow row in table.Rows)
{
foreach(DataColumn column in table.Columns)
{
// you can insert your logic to use column value row[column] here
Console.WriteLine(row[column]);
}
}
for (int i = 0; i < dt.Rows.Count ; i++)
{
for (int j = 1; j < dt.Columns.Count ; j++)
{
string cellValue = dt.Rows[i][j].ToString();
dt.Rows[i][j] = r.Decrypt(cellValue);
}
}

C# Adding dynamic column and rows in Datatable

I tried to add values to DataTable columns by vertically in loops.
But output doesn't looks good as expected.
DataTables dynamictable = new DataTable()
foreach (DataColumn cl in dataTable.Columns)
{
dynamictable.Columns.Add(cl.ToString());
List<string> plainList = dataTable.AsEnumerable().Select(x => x[cl].ToString()).ToList();
for (int i=0; i< plainList.Count(); i++)
{
DataRow row = dynamictable.NewRow();
row[cl.ToString()] = plainList[i];
enryptedTable.Rows.Add(row);
}
}
Actual Output got from my code:
Expected Output:
change your code to :
DataTable dynamictable = new DataTable();
int col = 0;
foreach (DataColumn cl in dataTable.Columns)
{
dynamictable.Columns.Add(cl.ToString());
List<string> plainList = dataTable.AsEnumerable().Select(x => x[cl].ToString()).ToList();
DataRow row = null;
for (int i = 0; i < plainList.Count(); i++)
{
row = dynamictable.NewRow();
row[col] = plainList[i];
dynamictable.Rows.Add(row);
}
col++;
}
//now set dynamictable to datagridview or .....

Query Excel where Rows and Columns are reversed

How can I query an Excel file where the rows and columns are reversed / rotated 90 degrees?
Can it be done with a SELECT query, or do I need to recurse the cells programmatically?
It's for a .NET app, so linq or other suggestions are welcome.
Transpose a Datatable with a code like this:
private DataTable GenerateTransposedTable(DataTable inputTable)
{
DataTable outputTable = new DataTable(inputTable.TableName);
outputTable.Columns.Add(inputTable.Columns[0].ColumnName);
foreach (DataRow inRow in inputTable.Rows)
{
string newColName = inRow[0].ToString();
outputTable.Columns.Add(newColName);
}
for (int rCount = 1; rCount <= inputTable.Columns.Count - 1; rCount++)
{
DataRow newRow = outputTable.NewRow();
newRow[0] = inputTable.Columns[rCount].ColumnName;
for (int cCount = 0; cCount <= inputTable.Rows.Count - 1; cCount++)
{
string colValue = inputTable.Rows[cCount][rCount].ToString();
newRow[cCount + 1] = colValue;
}
outputTable.Rows.Add(newRow);
}
return outputTable;
}
.NET does not include a method to transpose data tables. You have to make your own. This website Link has a tutorial on an example transpose method. I will copy and paste the code snippet below:
private DataTable Transpose(DataTable dt)
{
DataTable dtNew = new DataTable();
//adding columns
for(int i=0; i<=dt.Rows.Count; i++)
{
dtNew.Columns.Add(i.ToString());
}
//Changing Column Captions:
dtNew.Columns[0].ColumnName = " ";
for(int i=0; i<dt.Rows.Count; i++)
{
//For dateTime columns use like below
dtNew.Columns[i+1].ColumnName =Convert.ToDateTime(dt.Rows[i].ItemArray[0].ToString()).ToString("MM/dd/yyyy");
//Else just assign the ItermArry[0] to the columnName prooperty
}
//Adding Row Data
for(int k=1; k<dt.Columns.Count; k++)
{
DataRow r = dtNew.NewRow();
r[0] = dt.Columns[k].ToString();
for(int j=1; j<=dt.Rows.Count; j++)
r[j] = dt.Rows[j-1][k];
dtNew.Rows.Add(r);
}
return dtNew;
}

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

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

Categories

Resources