How to Convert String Data to Data Table in C# asp.net? - c#

So far I have tried to convert DataTable to String as follow:-
public static string convertDataTableToString(DataTable dataTable)
{
string data = string.Empty;
int rowsCount = dataTable.Rows.Count;
for (int i = 0; i < rowsCount; i++)
{
DataRow row = dataTable.Rows[i];
int columnsCount = dataTable.Columns.Count;
for (int j = 0; j < columnsCount; j++)
{
data += dataTable.Columns[j].ColumnName + "~" + row[j];
if (j == columnsCount - 1)
{
if (i != (rowsCount - 1))
data += "$";
}
else
data += "|";
}
}
return data;
}
Now I want to convert returned string into DataTable again.

You can use String.Split to break your string into rows and cells. If the column setup is always the same (as it should be), then you can simply add the columns on your first iteration through the cells.
Here's a simple example:
public static DataTable convertStringToDataTable(string data)
{
DataTable dataTable = new DataTable();
bool columnsAdded = false;
foreach(string row in data.Split('$'))
{
DataRow dataRow = dataTable.NewRow();
foreach(string cell in row.Split('|'))
{
string[] keyValue = cell.Split('~');
if (!columnsAdded)
{
DataColumn dataColumn = new DataColumn(keyValue[0]);
dataTable.Columns.Add(dataColumn);
}
dataRow[keyValue[0]] = keyValue[1];
}
columnsAdded = true;
dataTable.Rows.Add(dataRow);
}
return dataTable;
}
Alternatively you could get a list of all columns prior to the loop, but this way is likely easier for your purpose.

Related

How to compare 2 dataTable in c#

How can I compare the 2 dataTable in c#
For example
dataTable1
a,a,a,a,1,a,a,a,a,a
a,a,a,a,1,a,a,a,a,a
a,a,a,a,2,a,a,a,a,a
a,a,a,a,2,a,a,a,a,a
a,a,a,a,3,a,a,a,a,a
dataTable2
b,b,b,b,1,b,b,b,b,b
b,b,b,b,1,b,b,b,b,b
b,b,b,b,1,b,b,b,b,b
b,b,b,b,2,b,b,b,b,b
b,b,b,b,2,b,b,b,b,b
How do I run the 1st row in dataTable1 [5] which is = 1, if dataTable2 [5] also consists 1 then print out the line. Continue until finish. Then Continue loop to second one in dataTable1 check with dataTable2
Here is my code
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CompareLinuxWithWindow
{
class Program
{
static void Main(string[] args)
{
DataTable dt1 = ConvertToDataTable(#"C:\Users\manchunl\Desktop\Sample1.txt", 10);
DataTable dt2 = ConvertToDataTable2(#"C:\Users\manchunl\Desktop\Sample2.txt", 10);
foreach (DataRow row in dt1.AsEnumerable())
{
string temp_dt1 = "";
string[] words = temp_dt1.Split(',');
string.Join(",", row.ItemArray.Select(x => x.ToString()));
temp_Linux = (string.Join(",", row.ItemArray.Select(x => x.ToString())));
}
foreach (DataRow row in dt2.AsEnumerable())
{
string temp_dt2 = "";
string.Join(",", row.ItemArray.Select(x => x.ToString()));
temp_dt2 = (string.Join(",", row.ItemArray.Select(x => x.ToString())));
}
Console.WriteLine();
Console.WriteLine("Press enter to exit.");
Console.Read();
}
public static DataTable ConvertToDataTable(string filePath, int numberOfColumns)
{
DataTable tbl = new DataTable();
for (int col = 0; col < numberOfColumns; col++)
tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));
string[] lines = System.IO.File.ReadAllLines(filePath);
foreach (string line in lines)
{
var cols = line.Split(null);
DataRow dr = tbl.NewRow();
for (int cIndex = 0; cIndex < numberOfColumns; cIndex++)
{
dr[cIndex] = cols[cIndex];
}
tbl.Rows.Add(dr);
}
return tbl;
}
public static DataTable ConvertToDataTable2(string filePath, int numberOfColumns)
{
DataTable tbl = new DataTable();
for (int col = 0; col < numberOfColumns; col++)
tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));
string[] lines = System.IO.File.ReadAllLines(filePath);
foreach (string line in lines)
{
var cols = line.Split(',');
DataRow dr = tbl.NewRow();
for (int cIndex = 0; cIndex < numberOfColumns; cIndex++)
{
dr[cIndex] = cols[cIndex];
}
tbl.Rows.Add(dr);
}
return tbl;
}
}
}
You can try using the loop as below, please pay attention to comments as those are important
// assumption is that both dt1 and dt2 has same number of rows
// otherise while accessing dt2 we can get index out of range exception
for (int i = 0; i < dt1.Rows.Count; i++)
{
DataRow dr1 = dt1.Rows[i];
DataRow dr2 = dt2.Rows[i];
// accessing the column below would return a system.object variable,
// need to convert it to the right type using one of the convert calls, e.g. Convert.ToInt16(dr1["ColumnName"])
if (dr1["ColumnName"] == dr2["ColumnName"])
{
// do whatever you want to do here
}
}
You can return the data table which will be the difference of two input data table and later you can perform operations on the resulting data table.
CODE
/// <summary>
/// Compare two DataTables and return a DataTable with DifferentRecords
/// </summary>
/// <param name="FirstDataTable">FirstDataTable</param>
/// <param name="SecondDataTable">SecondDataTable</param>
/// <returns>DifferentRecords</returns>
public DataTable getDifferentRecords(DataTable FirstDataTable, DataTable SecondDataTable)
{
//Create Empty Table
DataTable ResultDataTable = new DataTable("ResultDataTable");
//use a Dataset to make use of a DataRelation object
using (DataSet ds = new DataSet())
{
var dataTable = new DataTable[] { FirstDataTable.Copy(), SecondDataTable.Copy() };
dataTable[0].TableName = "FirstTable";
dataTable[1].TableName = "SecondTable";
//Add tables
ds.Tables.AddRange(dataTable);
//Get Columns for DataRelation
DataColumn[] firstColumns = new DataColumn[ds.Tables[0].Columns.Count];
for (int i = 0; i < firstColumns.Length; i++)
{
firstColumns[i] = ds.Tables[0].Columns[i];
}
DataColumn[] secondColumns = new DataColumn[ds.Tables[1].Columns.Count];
for (int i = 0; i < secondColumns.Length; i++)
{
secondColumns[i] = ds.Tables[1].Columns[i];
}
//Create DataRelation
DataRelation r1 = new DataRelation(string.Empty, firstColumns, secondColumns, false);
ds.Relations.Add(r1);
DataRelation r2 = new DataRelation(string.Empty, secondColumns, firstColumns, false);
ds.Relations.Add(r2);
//Create columns for return table
for (int i = 0; i < FirstDataTable.Columns.Count; i++)
{
ResultDataTable.Columns.Add(FirstDataTable.Columns[i].ColumnName,
FirstDataTable.Columns[i].DataType);
}
//If FirstDataTable Row not in SecondDataTable, Add to ResultDataTable.
ResultDataTable.BeginLoadData();
foreach (DataRow parentrow in ds.Tables[0].Rows)
{
DataRow[] childrows = parentrow.GetChildRows(r1);
if (childrows == null || childrows.Length == 0)
{
ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
}
}
//If SecondDataTable Row not in FirstDataTable, Add to ResultDataTable.
foreach (DataRow parentrow in ds.Tables[1].Rows)
{
DataRow[] childrows = parentrow.GetChildRows(r2);
if (childrows == null || childrows.Length == 0)
ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
}
ResultDataTable.EndLoadData();
}
return ResultDataTable;
}
You need to first loop on the first data table
Then get row at specific index
Check whether current row exist in second data table
Get row from second data table at same index.
Read the column value from row to string variable.
Check if both value from both row are equal or not.
DataTable dt1 = ConvertToDataTable(#"C:\Users\manchunl\Desktop\Sample1.txt", 10);
DataTable dt2 = ConvertToDataTable2(#"C:\Users\manchunl\Desktop\Sample2.txt", 10);
for (int i = 0; i < dt1.Rows.Count; i++)
{
DataRow dr1 = dt1.Rows[i];
if (dt2.Rows.Count > i)
{
DataRow dr2 = dt2.Rows[i];
string value1 = Convert.ToString(dr1["Column5"]);
string value2 = Convert.ToString(dr2["Column5"]);
if (!string.IsNullOrEmpty(value1) && !string.IsNullOrEmpty(value2) && value1 == value2)
{
Console.WriteLine(value1);
}
else
{
//Do code when no matched.
}
}
}

Reading .txt file content to DataTable with Column headers on first line

I am trying to load data from a .txt file which looks like this:
|ABC|DEF|GHI|
|111|222|333|
|444|555|666|
With code:
using (StringReader reader = new StringReader(new StreamReader(fileStream, Encoding.Default).ReadToEnd()))
{
string line;
//reader.ReadLine(); //skip first line
while (reader.Peek() != -1)
{
line = reader.ReadLine();
if (line == null || line.Length == 0)
continue;
string[] values = line.Split('|').Skip(1).ToArray();
if (!isColumnCreated)
{
for (int i = 0; i < values.Count(); i++)
{
table.Columns.Add(values[i]);
}
isColumnCreated = true;
}
DataRow row = table.NewRow();
for (int i = 0; i < values.Count(); i++)
{
row[i] = values[i];
}
table.Rows.Add(row);
products++;
}
}
The problem is, when I generate a DataTable, I have first line as Column, but first line:
|ABC|DEF|GHI|
is visible also in the rows:
How to put first line as column headers and rest as rows?
I do not want to use CSVHelper for that if it possible.
Just need to skip when the first line after header is created
string line;
bool bheader= false;
//reader.ReadLine(); //skip first line
while (reader.Peek() != -1)
{
line = reader.ReadLine();
if (line == null || line.Length == 0)
continue;
string[] values = line.Split('|').Skip(1).ToArray();
if (!isColumnCreated)
{
for (int i = 0; i < values.Count(); i++)
{
table.Columns.Add(values[i]);
}
isColumnCreated = true;
bheader = true;
}
if(bheader ==false){
DataRow row = table.NewRow();
for (int i = 0; i < values.Count(); i++)
{
row[i] = values[i];
}
table.Rows.Add(row);
products++;
}
}
bheader = false;
}
The issue with your current code is that you handle when isColumnCreated is false, but not true. If you change this:
if (!isColumnCreated)
{
for (int i = 0; i < values.Count(); i++)
{
table.Columns.Add(values[i]);
}
isColumnCreated = true;
}
DataRow row = table.NewRow();
for (int i = 0; i < values.Count(); i++)
{
row[i] = values[i];
}
table.Rows.Add(row);
products++;
to this
if (!isColumnCreated)
{
for (int i = 0; i < values.Count(); i++)
{
table.Columns.Add(values[i]);
}
isColumnCreated = true;
}
DataRow row = table.NewRow();
else if (isColumnCreated)
{
for (int i = 0; i < values.Count(); i++)
{
row[i] = values[i];
}
table.Rows.Add(row);
}
it should work just fine. By only creating a row if the column headers have been created you're creating a situation wherein only on the first pass do you do anything with the first row, then it gets dumped.
I would think you want to add the columns or add a row.
if (!isColumnCreated)
{
for (int i = 0; i < values.Count(); i++)
{
table.Columns.Add(values[i]);
}
isColumnCreated = true;
}
}
else
{
DataRow row = table.NewRow();
for (int i = 0; i < values.Count(); i++)
{
row[i] = values[i];
}
table.Rows.Add(row);
}
This would work
DataTable dt = new DataTable();
using (System.IO.StreamReader sr = new System.IO.StreamReader("PathToFile"))
{
string currentline = string.Empty;
bool doneHeader = false;
while ((currentline = sr.ReadLine()) != null)
{
if (!doneHeader)
{
foreach (string item in currentline.Split('YourDelimiter'))
{
dt.Columns.Add(item);
}
doneHeader = true;
continue;
}
dt.Rows.Add();
int colCount = 0;
foreach (string item in currentline.Split('YourDelimiter'))
{
dt.Rows[dt.Rows.Count - 1][colCount] = item;
colCount++;
}
}
}
Another method, more LINQ oriented.
Use File.ReadAllLines to parse all the File lines into a string array.
Create a List<string[]> containing all the data Rows. The columns values are composed splitting the string row using a
provided Delimiter.
The first Row values are used to build a DataTable Columns elements.
The first Row is removed from the List.
All the other Rows are added to the DataTable.Rows collection.
Set a DataGridView.DataSource to the new DataTable.
char Delimiter = '|';
string[] Lines = File.ReadAllLines("[SomeFilePath]", Encoding.Default);
List<string[]> FileRows = Lines.Select(line =>
line.Split(new[] { Delimiter }, StringSplitOptions.RemoveEmptyEntries)).ToList();
DataTable dt = new DataTable();
dt.Columns.AddRange(FileRows[0].Select(col => new DataColumn() { ColumnName = col }).ToArray());
FileRows.RemoveAt(0);
FileRows.ForEach(row => dt.Rows.Add(row));
dataGridView1.DataSource = dt;

How to read Excel to Datatable using NPOI C#

I'm Trying to read Excel to DataTable using NPOI.Every thing working fine but only issue is If we have any Column cell is empty in that row it is not reading .In Excel i have 4 row's with (each row have some empty values for cells).
Excel File Image : enter image description here
After Reading That Excel To data table :enter image description here
I want like this in data table
private DataTable GetDataTableFromExcel(String Path)
{
XSSFWorkbook wb;
XSSFSheet sh;
String Sheet_name;
using (var fs = new FileStream(Path, FileMode.Open, FileAccess.Read))
{
wb = new XSSFWorkbook(fs);
Sheet_name = wb.GetSheetAt(0).SheetName; //get first sheet name
}
DataTable DT = new DataTable();
DT.Rows.Clear();
DT.Columns.Clear();
// get sheet
sh = (XSSFSheet)wb.GetSheet(Sheet_name);
int i = 0;
while (sh.GetRow(i) != null)
{
// add neccessary columns
if (DT.Columns.Count < sh.GetRow(i).Cells.Count)
{
for (int j = 0; j < sh.GetRow(i).Cells.Count; j++)
{
DT.Columns.Add("", typeof(string));
}
}
// add row
DT.Rows.Add();
// write row value
for (int j = 0; j < sh.GetRow(i).Cells.Count; j++)
{
var cell = sh.GetRow(i).GetCell(j);
DT.Rows[i][j] = sh.GetRow(i).GetCell(j);
}
i++;
}
return DT;
}
Plese hlp me.
you may have to try something along this line. its workable code to read the excel using NPOI.
// read the current row data
XSSFRow headerRow = (XSSFRow)sheet.GetRow(0);
// LastCellNum is the number of cells of current rows
int cellCount = headerRow.LastCellNum;
// LastRowNum is the number of rows of current table
int rowCount = sheet.LastRowNum + 1;
bool isBlanKRow = false;
//Start reading data after first row(header row) of excel sheet.
for (int i = (sheet.FirstRowNum + 1); i < rowCount; i++)
{
XSSFRow row = (XSSFRow)sheet.GetRow(i);
DataRow dataRow = dt.NewRow();
isBlanKRow = true;
try
{
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (null != row.GetCell(j) && !string.IsNullOrEmpty(row.GetCell(j).ToString()) && !string.IsNullOrWhiteSpace(row.GetCell(j).ToString()))
{
dataRow[j] = row.GetCell(j).ToString();
isBlanKRow = false;
}
}
}
catch (Exception Ex)
{
}
if (!isBlanKRow)
{
dt.Rows.Add(dataRow);
}
}

changing Datatype of DataTable using decimal

I am comparing two Datatables and built a new table
I want to sort the values in the new table since it has -ve values(if not converted to decimal then -ve sign will not be considered)
I want to convert it to Decimal type from string and return the table for sorting. I am getting error as input string is not in correct format how solve this?And sort -ve values in Asc order
private static DataTable CompareTwoDataTable(DataTable table1, DataTable table2)
{
DataTable table3 = new DataTable();
DataRow dr = null;
string filterExp = string.Empty;
for (int i = 0; i < table1.Rows.Count; i++)
{
string col = table1.Rows[i]["Parameter Name"].ToString();
if (table2.Columns.Contains(col))
{
if (!table3.Columns.Contains(col))
{
table3.Columns.Add(col, typeof(string));
filterExp = filterExp + col + " asc ,";
}
for (int j = 0; j < table2.Rows.Count; j++)
{
if (table3.Rows.Count != table2.Rows.Count)
{
dr = table3.NewRow();
table3.Rows.Add(dr);
}
table3.Rows[j][col] = (table2.Rows[j][col].ToString());
}
}
}
DataView dv = new DataView(table3);
filterExp = filterExp.TrimEnd(',');
dv.Sort = filterExp;
table3 = dv.ToTable();
return table3;
}
`
private static DataTable CompareTwoDataTable(DataTable table1, DataTable table2)
{
DataTable table3 = new DataTable();
DataRow dr = null;
string filterExp = string.Empty;
for (int i = 0; i < table1.Rows.Count; i++)
{
string col = table1.Rows[i]["Par Name"].ToString();
if (table2.Columns.Contains(col))
{
if (!table3.Columns.Contains(col))
{
table3.Columns.Add(col, typeof(double));
filterExp = filterExp + col + " asc ,";
}
for (int j = 0; j < table2.Rows.Count; j++)
{
if (table3.Rows.Count != table2.Rows.Count)
{
dr = table3.NewRow();
table3.Rows.Add(dr);
}
table3.Rows[j][col] = table2.Rows[j][col];
}
}
}
`

Rows not showing up in DataTable c#

I am trying to copy data from my datagridview to a datatable so i can export to a csv file
here is the code
public DataTable createdatatablefromdgv()
{
DataTable dsptable = new DataTable();
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
DataColumn dspcolumn = new DataColumn(dataGridView1.Columns[i].HeaderText);
dsptable.Columns.Add(dspcolumn);
}
int noOfColumns = dataGridView1.Columns.Count;
foreach (DataGridViewRow dgvr in dataGridView1.Rows)
{
DataRow dataRow = dsptable.NewRow();
for (int i = 0; i < noOfColumns; i++)
{
dataRow[i] = dgvr.Cells[i].Value.ToString();
}
}
return dsptable;
}
It seems like it copies the data from the the grid to to the table but when I return the datatable all there is the columns no rows
You are not adding dataRow to data table after assigning values to its columns.
public DataTable createdatatablefromdgv()
{
DataTable dsptable = new DataTable();
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
DataColumn dspcolumn = new DataColumn(dataGridView1.Columns[i].HeaderText);
dsptable.Columns.Add(dspcolumn);
}
int noOfColumns = dataGridView1.Columns.Count;
foreach (DataGridViewRow dgvr in dataGridView1.Rows)
{
DataRow dataRow = dsptable.NewRow();
for (int i = 0; i < noOfColumns; i++)
{
dataRow[i] = dgvr.Cells[i].Value.ToString();
}
dsptable.Rows.Add(dataRow); //Add this statement to add rows to Data Table
}
return dsptable;
}
The above answer is correct but a little explanation as to why you encountered this problem. One would think that by calling NewRow() on the DataTable you would add a new row to the DataTable and then be able to access it.
What NewRow actually does is give you an instance of a DataRow which you can then use column names as apose to column identifiers (integers).
This allows you to do something like this
DataRow dataRow = dsptable.NewRow();
foreach(DataColumn dc in dsptable.Columns)
{
dataRow[dc.ColumnName] = dgvr.Cells[dc.ColumnName].Value.ToString()
}
Alternatively you could just call Rows.Add() which takes an object array or a as you were trying to do a DataRow.
List<string> rowData = new List<string>();
for (int i = 0; i < noOfColumns; i++)
{
rowData.Add(dgvr.Cells[i].Value.ToString());
}
dsptable.Rows.Add(rowData.ToArray());
This should explain adding rows to a datatable more simply :)

Categories