datatable not sorting no errors - c#

I am using the code below to sort my data the program runs with out any isses but the data in the rows is not being sorted.. and cant find a reason why this would be the case.
DataTable extractedData = new DataTable();
//data added to datatable extractedData
DataView dv = new DataView();
dv =extractedData.AsDataView();
dv.Sort = dv.Table.Columns[10].ColumnName + " DESC";
extractedData = dv.Table;
This code below is using apose.slides to add code into a presentation table.
string val = "";
int col = 0;
int row = 0;
for (int i = 1; i < table.Rows.Count; i++)
{
for (int j = 0; j < table.Columns.Count; j++)
{
if (j == 0)
{
val = extractedData.Rows[row][valuesUsed[col]].ToString();
string[] removeQuestion = val.Split('[', ']');
val = removeQuestion[1];
}
else
{
val = extractedData.Rows[row][valuesUsed[col]].ToString();
if (val == "-" || val == "")
{
val = extractedData.Rows[row][valuesUsed[col]].ToString();
}
else
{
val = Convert.ToString(Math.Round(Convert.ToDouble(extractedData.Rows[row][valuesUsed[col]]), MidpointRounding.AwayFromZero));
}
}
table[j, i].TextFrame.Text = val;
col++;
}
row++;
col = 0;
}

This will work :-
DataView dv = extractedData.DefaultView;
dv.Sort = extractedData.Columns[10].ColumnName + " DESC";
You were required to make the DataView the DataTables default view inorder for it to work.
Here's a link you should check out too.
http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx

Change the last line of your code to dv.toTable() instead of dv.Table.
DataTable extractedData = new DataTable();
//data added to datatable extractedData
DataView dv = new DataView();
dv = extractedData.DefaultView;
dv.Sort = "ColumnName DESC"; //mention exact name of your column
//or else
//dv.Sort = extractedData.Columns[9].ColumnName + " DESC";
extractedData = dv.toTable(); //Instead of dv.Table;
For information go through this link.

Related

Which Event Handler is called while adding items to the DataTable of a ComboBox at run time?

I have added the items to the DataTable of a ComboBox at run time by clicking a button.
I have set MaxDropDownItems = 6 on a button_Click event.
When I got the result, only 2 items are shown with ScrollBar.
What to do to get 6 items in the DropDown using MaxDropDownItems.
Expected: DropDown with 6 items
Code:
DataTable dt = new DataTable();
private DataTable GetDataTable()
{
DataColumn col = new DataColumn("tt", typeof(string));
dt.Columns.Add(col);
col = new DataColumn("nn", typeof(string));
dt.Columns.Add(col);
for (int j = 0; j < 2; j++)
{
System.Data.DataRow row = dt.NewRow();
row[0] = j + "";
row[1] = j + "";
dt.Rows.Add(row);
}
return dt;
}
Then in button_Click:
if (i == 0)
{
combobox.DataSource = GetDataTable();
combobox.MaxDropDownItems = 6;
}
else
{
System.Data.DataRow row = dt.NewRow();
row[0] = i + "";
row[1] = i + "";
dt.Rows.Add(row);
combobox.DataSource = dt;
}
i++;
combobox.Refresh();

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.
}
}
}

How to edit Row Value of Column in datatable [duplicate]

This question already has answers here:
How to Edit a row in the datatable
(7 answers)
Closed 8 years ago.
i have got the values of my datatable using the following method
DataTable table = new DataTable();
table = GetTable();
string expression;
expression = "B.Id = " + textBox1.Text;
DataRow[] foundRows;
foundRows = table.Select(expression);
for (int i = 0; i < foundRows.Length; i++)
{
sno.Text = foundRows[i][1].ToString();
name.Text = foundRows[i][2].ToString();
dcn.Text = foundRows[i][3].ToString();
stat.Text = foundRows[i][4].ToString();
}
so how do i change the value of foundRows[i][4]
You are already using the DataRow's indexer to get the first column, so i don't understand the problem. If you want to access the second field use foundRows[i][1]:
MessageBox.Show(foundRows[i][1].ToString());
If you want to loop all fields:
for(int i = 0; i < foundRows.Length; i ++)
{
for(int c = 0; c < table.Columns.Count; c++)
MessageBox.Show(foundRows[i][c].ToString());
}
I suggest to use the strongly typed Field-extension method which also supports nullable types.
MessageBox.Show(foundRows[i].Field<string>(0));
use this
DataTable table = new DataTable();
table = GetTable();
string expression;
expression = "B.Id = " + textBox1.Text;
DataRow[] foundRows;
foundRows = table.Select(expression);
for (int i = 0; i < foundRows.Length; i++)
{
sno.Text = foundRows[i][1].ToString();
name.Text = foundRows[i][2].ToString();
dcn.Text = foundRows[i][3].ToString();
stat.Text = foundRows[i][4].ToString();
}
DataTable table = new DataTable();
table = GetTable();
string expression;
expression = "B.Id = "+textBox1.Text;
DataRow[] foundRows;
foundRows = table.Select(expression);
for(int i = 0; i < foundRows.Length; i ++)
{
if(button1.Text == "Make Preasent!")
{
foundRows[i][4] = true;
table.AcceptChanges();
}
else
{
foundRows[i].SetField(4, false);
table.AcceptChanges();
}
}

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

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.

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];
}
}
}
`

Categories