I need to retrieve data according to Row by row,
Example:
Id | Username | Password
001 | Xyz | Abc
002 | ghdfdhjs | dsjkhfjds
As of now, I am getting Single column values(001, Xyz, Abc), which is not giving me desired result.
I need to return result, in such a way by which single row contains all column values (001, Xyz, Abc)
Trial Code:
DataTableCollection tableCollection = result.Tables;
DataTable table = tableCollection["test"];
var rows = table.Rows;
int rowCount = rows.Count;
int colCount = table.Columns.Count;
var results = new object[rowCount, colCount];
for (int i = 0; i < rowCount; i++)
{
var row = rows[i];
for (int j = 0; j < colCount; j++)
{
results[i, j] = row[j];
}
}
return results;
Reference:
I am trying to manage it by foreach loop with the help of DataRow, which is not working
object[] temp = { };
for (int i = 0; i < rowCount; i++)
{
DataRow row = table.Rows[i];
foreach (object [] item in row.ItemArray)
{
temp = item;
}
}
return temp;
Cast Exception : System.InvalidCastException : Unable to cast object
of type 'System.String' to type 'System.Object[]'
Can someone suggest correct way to get it,
Related
I have some logical block in my C# program, as I am new to C# programming.
I have a data-table with duplicate header column names. I have to change my duplicate header like concatenate the name of the prior column to make these headers unique. Table names are coming dynamically.
Current datatable dTable
ID |Name|Age| School | Name | state| Part| Country|Division|Part
Expected dTable
ID |Name|Age| School | Name+school | state| Part| Country|Division|Part+Division
What I have tried and blocked here below
public DataTable RemoveDuplicateRows(DataTable dTable)
{
string[] columnNames = dTable.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
for (int i = 0; i < columnNames.Length; i++)
{
columnNames[i] = columnNames[i].Split('.')[0].Trim();
}
for (int i = 0; i < columnNames.Length; i++)
{
// create nested loop for compare current values with actual value of arr
for (int j = i + 1; j < columnNames.Length; j++)
{
if (columnNames[i] == columnNames[j])
{
var previous = columnNames[i - 1];
var current = columnNames[i];
columnNames[i] = current + previous;
// blocked here
// only one header is concatenating
// how can I add this newly edited columns to my datatable
}
}
}
return dTable; //cant get updated column headers
}
Apologies for somewhat confusing explanation. I am using Microsoft.Office.Interop.Excel. Purpose for code below is to
1) Iterate all rows in Column B of excel sheet named oSheet1
2) Iterate all rows in Column 0 of datagridview (DTG)
3) If data from Column B and Column 0 matches, then export data in Column 1 of DTG into Column C of excel.
Hence, the data in column 1 of DTG is in reference with data in Column 0 of DTG. And data in Column C of excel will eventually be in reference with Column B of excel. I've inserted some images for easy understanding
I've tried multiple codes for hours and kept getting error. Below are my codes along with errors experienced:
Error: Cannot perform in runtime binding on null reference
for (int i = 1; i <= oSheet1.Columns.Count; i++)
{
string cellvalue = oSheet1.Cells[i, 2].Value.ToString(); //error here
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((string)row.Cells[0].Value == cellvalue)
{
for (int j = 0; j < dataGridView1.Rows.Count; j++)
{
oSheet1.Cells[i, 3] = dataGridView1.Rows[j].Cells[1].Value.ToString();
}
}
}
Error: Exception from H result
for (int i = 1; i <= oSheet1.Columns.Count; i++)
{
object cellvalue = oSheet1.get_Range("B:B" + Convert.ToString(i));
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[0].Value == cellvalue)
{
for (int j = 0; j < dataGridView1.Rows.Count; j++)
{
oSheet1.Cells[i, 3] = dataGridView1.Rows[j].Cells[1].Value.ToString();
}
}
}
}
I would appreciate any help. Thank you!!
Try UsedRange.
var range = oSheet1.UsedRange;
int startingRowIndex = range.Row + 1; //to skip the header
for (int rowIndex = startingRowIndex; rowIndex < range.Row + range.Rows.Count; rowIndex++)
{
string cellvalue = range.Cells[rowIndex, 2].Value?.ToString();
...
}
Also, you should perform a null check against the Value property just in case the cell is empty, or uses a null-conditional operator as shown in the code above.
I want to basically go this is row 1, row 2, 3, 4...until the last row and add that as a new column on my datagrid table, I am not trying to find the total amount of rows.
Here is my current code (I think this is terribly wrong but this is a lot of new code):
for (int i = 0; i < table.Rows.Count; i++)
{
string rowNum = table.Rows[i].ToString();
table.Columns.Add("Book num", typeof(string), rowNum);
}
The following code will add 1 new column to your table, and then populate each row in that column with the index number of that row.
If you don't want to start with 0, just change int i = 0; to int i = 1;
table.Columns.Add("Book num", typeof(string));
int i = 0;
foreach (DataRow dr in table.Rows)
{
dr["Book num"] = i;
i++;
}
Try for total rows,
int TotalRows = 0;
for (int i = 0; i < table.Rows.Count; i++)
{
if(i == 0)
{
TotalRows = 1;
}
else
{
TotalRows + = i;
}
string rowNum = table.Rows[i].ToString();
table.Columns.Add("Book num", typeof(string), rowNum);
}
Here is a DataTable dt, which has lots of data.
I want to get the specific Cell Value from the DataTable, say Cell[i,j]. Where,
i -> Rows and j -> Columns. I will iterate i,j's value with two forloops.
But I can't figure out how I can call a cell by its index.
Here's the code:
for (i = 0; i <= dt.Rows.Count - 1; i++)
{
for (j = 0; j <= dt.Columns.Count - 1; j++)
{
var cell = dt.Rows[i][j];
xlWorkSheet.Cells[i + 1, j + 1] = cell;
}
}
The DataRow has also an indexer:
Object cellValue = dt.Rows[i][j];
But i would prefer the strongly typed Field extension method which also supports nullable types:
int number = dt.Rows[i].Field<int>(j);
or even more readable and less error-prone with the name of the column:
double otherNumber = dt.Rows[i].Field<double>("DoubleColumn");
You probably need to reference it from the Rowsrather than as a cell:
var cellValue = dt.Rows[i][j];
You can iterate DataTable like this:
private void button1_Click(object sender, EventArgs e)
{
for(int i = 0; i< dt.Rows.Count;i++)
for (int j = 0; j <dt.Columns.Count ; j++)
{
object o = dt.Rows[i].ItemArray[j];
//if you want to get the string
//string s = o = dt.Rows[i].ItemArray[j].ToString();
}
}
Depending on the type of the data in the DataTable cell, you can cast the object to whatever you want.
To get cell column name as well as cell value :
List<JObject> dataList = new List<JObject>();
for (int i = 0; i < dataTable.Rows.Count; i++)
{
JObject eachRowObj = new JObject();
for (int j = 0; j < dataTable.Columns.Count; j++)
{
string key = Convert.ToString(dataTable.Columns[j]);
string value = Convert.ToString(dataTable.Rows[i].ItemArray[j]);
eachRowObj.Add(key, value);
}
dataList.Add(eachRowObj);
}
You can call the indexer directly on the datatable variable as well:
var cellValue = dt[i].ColumnName
If I have understood your question correctly you want to display one particular cell of your populated datatable? This what I used to display the given cell in my DataGrid.
var s = dataGridView2.Rows[i].Cells[j].Value;
txt_Country.Text = s.ToString();
Hope this helps
I have a requirement where I need to change the data orientation of a datatable. Suppose I have the data spread vertically:
Year | 0-20 | 21-40 | 41-60 | >61 | Total
% total | 11.5 | 26.5 | 42.0 | 20.0 | 100.0
I want a method to change the orientation to horizontal like:
Year | % Total
0-20 | 11.5
21-40 | 26.5
41-60 | 42.0
>61 | 20.0
Total | 100.0
I am using C# with .net 3.5. I really can't change the original dataset. I have to do something in my code to handle it. This converted dataset will be fed to an existing function to do further processing. Any help would be appreciated.
Taken from here
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 = null;
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;
}
It sounds like you want to pivot a DataTable.
Here's a method that'll help take each of your columns and turn them into rows. It's up to you to make the finer details work as per your requirements.
private DataTable PivotTable(DataTable origTable)
{
DataTable newTable = new DataTable();
DataRow dr = null;
//Add Columns to new Table
for (int i = 0; i <= origTable.Rows.Count; i++)
{
newTable.Columns.Add(new DataColumn(origTable.Columns[i].ColumnName, typeof(String)));
}
//Execute the Pivot Method
for (int cols = 0; cols < origTable.Columns.Count; cols++)
{
dr = newTable.NewRow();
for (int rows = 0; rows < origTable.Rows.Count; rows++)
{
if (rows < origTable.Columns.Count)
{
dr[0] = origTable.Columns[cols].ColumnName; // Add the Column Name in the first Column
dr[rows + 1] = origTable.Rows[rows][cols];
}
}
newTable.Rows.Add(dr); //add the DataRow to the new Table rows collection
}
return newTable;
}