C# order column by date - header column datetime - c#

we try to sort the column of my datagridview in C# from the most recent to the other, but i didn't find a solution.
Below the image of my little program
references
my last test it's to use:
for (int i=1; i<dsForecast.Columns.Count; i++)
{
DataColumn col = dsForecast.Columns[i];
dtListDate.Add(DateTime.Parse(col.ColumnName));
}
Dictionary<DateTime, int> dList = new Dictionary<DateTime, int>();
for (int i = 0; i < dtListDate.Count; i++)
dList.Add(dtListDate[i], i);
dtListDate.Sort((a, b) => a.CompareTo(b));
foreach (DataColumn c in dsForecast.Columns)
this.dgwForecast.Columns[c.ColumnName].DisplayIndex = dsForecast.Columns.IndexOf(c);
Can anyone help me to find a solution for this?
i want a result like this,result
I undestrand that the solution is to move the columnn with its contents, but how?
Can someone Help me?

Related

Datagrid loop through the lines C#

I have the code, that randomly select row from datagrid. But I need to select not randomly, but step by step in the loop.
For example:
Row1
Row2 <- Selected
Row3
It must go in loop Row3 - Row1 - Row2 - Row3 - Row1 ...
If some one can help me with that, I will be very grateful to you.
Here is my code with random:
Random rnd = new Random();
int rowMax = dataSender.Rows.Count;
int row = rnd.Next(0, rowMax);
var arg = new DataGridViewCellEventArgs(0, row);
dataSender_CellClick(dataSender, arg);
dataSender.CurrentCell = dataSender.Rows[row].Cells[0];
All what I want every time I use this code it got to move selected row to next row.
From Row2 to Row3. If there are only 3 rows, then from Row3 return to Row1
Your question is a little unclear, but if you're at say row 2, you then want to move to row 3?
If so, you could do something like this maybe:
Random rnd = new Random();
int rowMax = dataSender.Rows.Count;
int row = rnd.Next(0, rowMax);
for (int i = 0; i < rowMax; i++)
{
var arg = new DataGridViewCellEventArgs(0, row);
dataSender_CellClick(dataSender, arg);
dataSender.CurrentCell = dataSender.Rows[row].Cells[0];
row++;
if (row == rowMax)
{
row = 0;
}
}
So after your code finishes the dealing with the current row, you could increment the row integer by 1 and then check to see if it is equal to the maximum. If it is, then you can set row = 1.
Again, if I've mis-interpreted I'm sorry, but in that case please could you make your question a little clearer

Sort a Dynamic CSV string C#

Please I need help to sort the following string in csv format alphabetically
Input
First, Second,Third,Fourth, Fifth
Beth,Charles,Danielle,Adam,Eric\n
17945,10091,10088,3907,10132\n
2,12,13,48,11
Output (After sorting)
First, Second,Third,Fourth, Fifth
Adam,Beth,Charles,Danielle,Eric\n
3907,17945,10091,10088,10132\n
48,2,12,13,11
This is what I have tried.
First I converted the csv into datatable
var rows = csv.Split('\n', StringSplitOptions.RemoveEmptyEntries);
var dtCsv = new DataTable();
for (int i = 0; i < rows.Count(); i++)
{
string[] rowValues = rows[i].Split(','); //split each row with comma to get individual values
{
if (i == 0)
{
for (int j = 0; j < rowValues.Count(); j++)
{
dtCsv.Columns.Add(rowValues[j]); //add headers
}
}
else
{
//DataRow dr = dtCsv.NewRow();
for (int k = 0; k < rowValues.Count(); k++)
{
//dr[k] = rowValues[k].ToString();
dtCsv.Columns.Add(rowValues[k]);
}
// dtCsv.Rows.Add(dr); //add other rows
}
}
}
Then I tried to convert back to csv hoping i can be able to sort the datatable, but I am hooked.
I appreciate in advcance.
Please I would appreciate a diferent approach if possible.
Although the model of data that you presented is not normal and accurate as Row, Column model, you can do it as per the below snippet code:
static void Main(string[] args)
{
Dictionary<int, List<string>> myDummyDic = ReadDataFromCsv();
foreach (var item in myDummyDic[0])
{
Console.WriteLine(item);
}
}
private static Dictionary<int, List<string>> ReadDataFromCsv()
{
Dictionary<int, List<string>> myDummyDic = new();
var result = File.ReadLines("data.csv")
.Select(line => line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList());
int rowC = 0;
foreach (var item in result)
{
List<string> lst = new();
for (int i = 0; i < item.Count; i++)
{
lst.Add(item[i]);
}
lst.Sort();
myDummyDic.Add(rowC++, lst);
}
return myDummyDic;
}
The output result:
Note that if you want to Transpose your CSV file entirely then I suggest you use Cinchoo ETL for that purpose.
Consider the following Question and Answers :
How to transpose matrix?
An approach without external library
Another approach using Cinchoo ETL to Transpose

How to query DataTable

I have a datatable like that:
column1 column2 column3
a b c
d e f
I want to get index numbers of the cell "e" and i wrote these
int[] indexrowcol = new int[2];
for (int i = 0; i < dt.Columns.Count ; i++)
{
for (int j = 0; j < dt.Rows.Count; j++)
{
if (dt.Rows[i][j] == "e")
{
indexrowcol[0] = j; indexrowcol[1] = i;
}
}
}
How to write the same thing with usin LINQ? thanks.
I don't believe you have your original code implemented correctly to get what you're after. But at least it's more or less clear what you're trying to do. Here's some commented link code that can accomplish it.
var valToSearch = "e";
int[] indexrowcol = dt.AsEnumerable() // allows you to use linq
.SelectMany((row,rix) => // like 'Select', but stacks up listed output
row.ItemArray.Select( // ItemArray gets the row as an array
(col,cix) => new { rix, cix, value = col.ToString() }
)
)
.Where(obj => obj.value == valToSearch)
.Select(obj => new int[] { obj.rix, obj.cix })
.FirstOrDefault();
When I use the above code on the following DataTable, I get the result [1,1], which is the same result I get using your original code when I correct for the i/j reversal that existed at the time of this writing.
var dt = new DataTable();
dt.Columns.Add("Column1");
dt.Columns.Add("Column2");
dt.Columns.Add("Column3");
DataRow rw = dt.NewRow();
rw["Column1"] = "a";
rw["Column2"] = "b";
rw["Column3"] = "c";
dt.Rows.Add(rw);
rw = dt.NewRow();
rw["Column1"] = "d";
rw["Column2"] = "e";
rw["Column3"] = "f";
dt.Rows.Add(rw);
The reason your original code isn't quite right is that you use 'i' for columns and 'j' for rows, but then call dt.Rows[i][j], which is backwards. I highly recommend that your variables can be matched to what they are associated with. This is why I use names such as col, row, cix (column index), and rix to keep things straight.
In that vein, you might want to also output something other than an int[2]. Maybe a class or struct, or even just leave it as an anonymous object (get rid of the 'select' part of my query). Though I don't know your end use case, so I'll leave you alone on that.

How to add all table columns values to the Hasthable using selenium Webdriver c#

I am new in Selenium Webdriver. I want to get all Value from a html Table with 2 column and add them in a Hashtable. I don't know where to begin.
Any help would be appreciated.
Try this:
var hashTable = new Hashtable();
var table = Driver.FindElement(By.Id("table"));
int rowCount = table.FindElements(By.TagName("tr")).Count;
for (int i = 0; i < rowCount; i++)
{
hashTable.Add($"row{i}", table.FindElements(By.TagName("tr"))[i].Text);
}

Replicate record in a DataTable based on value of a column using C#

I have a record in a dataTable as shown below.
1 Test 7Dec2014 15:40 one,two,three
Since the last column has 3 comma separated values, the resultant DataTable should like below with replicated records.
1 Test 7Dec2014 15:40 one
2 Test 7Dec2014 15:40 two
3 Test 7Dec2014 15:40 three
Please help me with an optimized way to achieve the above result.
The optimized way I found for the above problem is as below. If anybody has a better solution please let me know.
string[] strValues;
for (int i = 0; i < dtTable.Rows.Count; i++)
{
strValues= dtTable.Rows[i]["Column_Name"].ToString().Split(',');
if (strValues.Length > 1)
{
dtTable.Rows[i]["Column_Name"] = strValues[0];
for (int j = 1; j < strValues.Length; j++)
{
var TargetRow = dtTable.NewRow();
var OriginalRow = dtTable.Rows[i];
TargetRow.ItemArray = OriginalRow.ItemArray.Clone() as object[];
TargetRow["Column_Name"] = strValues[j];
dtTable.Rows.Add(TargetRow);
}
}
}

Categories

Resources