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;
}
Related
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;
}
I want to create a 9x9 GridView, list the numbers 1 through 9 in columns and rows, and then put the values into an array.
I want to create it using for and Array, but I do not know what to do.
The current state is that the value is displayed below the column and all the values appear only on one row.
I want to complete one program and help.
aspx.
<asp:GridView ID="GridView1" runat="server">
<Columns></Columns>
aspx.cs.
public partial class GridEX : System.Web.UI.Page{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
int i = 1;
if (!Page.IsPostBack)
{
for (; i <= 9; i++)
{
dt.Columns.Add(i + "단");
}
for (int k = 1; k <= 9; k++)
{
DataRow dr = dt.NewRow();
for (int m = 1; m <= 9; m++)
{ dr[m] = i; }
dt.Rows.Add(dr);
dt.Rows.Add(i * k);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
What I want image:
DataTable dt = new DataTable();
dt.Columns.Add("Factor1");
dt.Columns.Add("Factor2");
dt.Columns.Add("Result");
for(int i=2; i<=9; i++)
{
for (int j=1; j<=10; j++)
{
dt.Rows.Add(i, j, i*j);
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
You may have your reasons for wanting to use a Gridview here, but in my opinion, it is not the right way to achieve your goal. DataBinding is a useful tool but it does come with processing overhead, at the very least it is another iteration.
You can use a DataTable to achieve the same thing without the binding overhead.
ASPX
<asp:Table ID="MulitiplicationTable" runat="server"></asp:Table>
C#
for(int row = 0; row < 10; row++)
{
TableRow newRow = new TableRow();
MulitiplicationTable.Rows.Add(newRow);
for (int column = 0; column < 10; column++)
{
TableCell newCell = new TableCell();
newRow.Cells.Add(newCell);
//Empty cell for our first cell...
if ((row + column) == 0)
{
newCell.Text = " ";
}
//Our Column and row headers are also
//Special Cases
else if(row == 0)
{
newCell.Text = column.ToString();
newCell.CssClass = "columnHead";
}
else if(column == 0)
{
newCell.Text = row.ToString();
newCell.CssClass = "rowHead";
}
//Now do the math
else
{
newCell.Text = (row * column).ToString();
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable table9x9 = new DataTable();
if (table9x9.Columns.Count == 0)
{
for (int i = 0; i < 10; i++)
{
if (i == 0)
table9x9.Columns.Add(" ");
else
table9x9.Columns.Add(i+"");
}
}
for (int row = 1; row <= 9; row++)
{
DataRow dr = table9x9.NewRow();
for (int column = 0; column <= 9; column++)
{
if (column == 0)
dr[" "] = row;
else
dr[column + ""] = row * column;
}
table9x9.Rows.Add(dr);
}
GridView2.DataSource = table9x9;
GridView2.DataBind();
}
}
Output:
I have an Excel file with 2 columns [file in my pc]? Now iam getting 2 columns with 8 rows with below code.but continuously i should get 5*2=10 more of same columns with 8 rows in datagridview.
I have written the code which gives result only 2 columns but I should get 10 more columns with 8 rows.below is my code
for (int Cnum = 1; Cnum <= ShtRange.Columns.Count; Cnum++)
{
dt.Columns.Add((ShtRange.Cells[1, Cnum] as Excel.Range).Value2.ToString());
}
for (int Rnum = 2; Rnum <= 9; Rnum++)
{
dt.Rows.Add((ShtRange.Cells[Rnum, 1] as Excel.Range).Value2.ToString(),
(ShtRange.Cells[Rnum, 1] as Excel.Range).Value2.ToString());
}
}
for (int i = 0; i < 13; i++)
{
DataGridViewTextBoxCell txtbx = new DataGridViewTextBoxCell();
DataGridViewColumn txcol = new DataGridViewColumn();
txcol.CellTemplate = txtbx;
txcol.HeaderText = "column" + i.ToString();
dg1.Columns.Add(txcol);
}
dg1.Rows.Add(8);
int dgRw, dgCol;
dgRw = dgCol = 0;
foreach (DataRow dr in dt.Rows)
{
dg1[dgCol, dgRw].Value = dr[0].ToString();
dgRw++;
if (dgRw == 8)
{
dgCol++;
dgRw = 0;
}
1.) ***Ok, so I have my DataTable that is imported from an Excel SpreadSheet and it is filled.I would like to sift through the DataTable and sum each row. I have to skip the first column & the first rows because they are labels. I am trying to reach each row in the table and total it and output to a "Row Total" column .. I am getting a "invalid cast specified" when I am trying to assign the 'number' variable to try and sum each cells value.
Example:
Row(0) --------------------ItemA......ItemB.......ItemC..............RowTotal
Column(1) CompanyA .....12 ..........12.............10....................34
2.) Also, I haven't reached it yet -- there is a potential issue with my trying to output it to the last column in the DataTable.
noted by: dr[dt.Columns.Count - 1] = Convert.ToInt32(sum);
Any thoughts or suggestions?
DataRow dr = dt.NewRow();
int sum = 0;
dt.Columns.Add("Row Totals", typeof(int));
for (int i = 0; i < dt.Columns.Count; i++)
{
if (dt.Columns[i].ColumnName == "Client")
{
dt.Columns.Cast<DataColumn>().Skip(1);
}
else
{
for (int j = 0; j < dt.Rows.Count - 1; j++)
{
dt.Rows.Cast<DataRow>().Skip(1);
int number =0;
number = (dt.Rows[j].Field<int>(i));
sum += number;
dr[dt.Columns.Count - 1] = Convert.ToInt32(sum);
Console.WriteLine("Row : {0} , Column : {1} , Value : {2}", i,j, dt.Rows[i][j].ToString());
Console.WriteLine(sum);
}
Console.ReadLine();
}
}
UPDATE: 12/27/12 ************
So, a solution I'm trying is to just skip the rows and column I know are text. I am still getting the "specified cast not valid" when it tries to filter through each cell and sum it. Any more suggestions?
Thank you in advance.
DataRow dr = dt.NewRow();
int sum = 0;
int number = 0;
for (int i = 0; i < dt.Columns.Count-1; i++)
{
if (dt.Columns[i].ColumnName == "column1")
{
dt.Columns.Cast<DataColumn>().Skip(0);
}
if (dt.Columns[i].ColumnName == "column2")
{
dt.Columns.Cast<DataColumn>().Skip(1);
}
else
{
for (int j = 0; j < dt.Rows.Count; j++)
{
dt.Rows.Cast<DataRow>().Skip(0);
dt.Rows.Cast<DataRow>().Skip(1);
//if (number != -1 && number != 0)
//{
number = (dt.Rows[j].Field<int>(i));
sum += number;
dr[dt.Rows.Count] = Convert.ToInt32(sum);
//}
//else
//{
// number = 0;
//}
Console.WriteLine("Row : {0} , Column : {1} , Value : {2}", i, j, dt.Rows[i][j].ToString());
Console.WriteLine(sum);
}
Console.ReadLine();
dataGridView1.DataSource = dt;
}
**UPDATE 12/27 1:30pm
I have scratched all that previous code and am attempting a test sheet and output. It seems to be working except now I can't seem to get the items to total when I am adding them to the last row. I'm stuck in the "else"" section of the code.
for (int i = 0; i < dt.Columns.Count - 2; i++)
{
for (int j = 0; j < dt.Rows.Count - 1; j++)
{
string value = dt.Rows[i][j].ToString();
int num = 0;
bool res = int.TryParse(value, out num);
if (res == false)
{
num = 0;
}
else
{
int sum = 0;
sum += num;
DataRow dr;
dr["Totals"] = sum;
dt.Rows.Add(dr);
}
}
dataGridView1.DataSource = dt;
}
}
One possibility is that there is a blank value in your data table - you can't cast a null object to an integer, so the Field extension method may be failing.
Is it possible to have a horizontal columns in DataGridView, with ability to bind those columns?
You dont have to Flip the DataGridView instead Flip the DataSet to bind
Try this:
public DataSet FlipDataSet(DataSet my_DataSet)
{
DataSet ds = new DataSet();
foreach (DataTable dt in my_DataSet.Tables)
{
DataTable table = new DataTable();
for (int i = 0; i <= dt.Rows.Count; i++)
{ table.Columns.Add(Convert.ToString(i)); }
DataRow r;
for (int k = 0; k < dt.Columns.Count; k++)
{
r = table.NewRow();
r[0] = dt.Columns[k].ToString();
for (int j = 1; j <= dt.Rows.Count; j++)
{ r[j] = dt.Rows[j - 1][k]; }
table.Rows.Add(r);
}
ds.Tables.Add(table);
}
return ds;
}
For more details visit Displaying-Vertical-Rows-in-DataGrid-View