Binding a gridview via a dynamic DataTable - c#

I have a GridView and I need to bind it with a dynamic Data Table.
I have a List<List<string>> and a List<List<DateTime>>.
I need a DataTable with 3 columns, namely FileName, LastAccessTimeForServer1, LastAccessTimeForServer2.
The List<List<string>> would contain 2 lists of filenames(common for both the servers), while List<List<DateTime>> would contain 2 lists of last access times (different for both the files).
Below is the code which I have tried, which doesn't make much sense to me.
Completely perplexed.
string serviceName = DropDownList1.SelectedItem.Text;
List<string> serviceNameArray = new List<string>();
for (int x = 1; x <= 2; x++)
{
if (x < 2)
{
serviceNameArray.Add(#"\\Server10" + x + #"\WebSite" + "\\" + serviceName);
}
else
{
serviceNameArray.Add(#"\\Server1" + x + #"\WebSite" + "\\" + serviceName);
}
}
List<List<string>> ultimateList = new List<List<string>>();
List<int> numList = new List<int>();
//Call the Search method
for (int y = 0; y < 2; y++)
{
ultimateList.Add(Search(serviceNameArray[y]));
}
for (int z = 0; z < 2; z++)
{
numList.Add(ultimateList[z].Count);
}
//FInd the Last Write Time for all the files.
for (int xx = 0; xx < 2; xx++)
{
listOfDateTimes.Add(new List<DateTime>());
for (int yy = 0; yy < numList[xx]; yy++)
{
listOfDateTimes[xx].Add(File.GetLastWriteTime(ultimateList[xx][yy]));
}
}
DataTable dtForGridView = new DataTable();
DataColumn dc1 = new DataColumn("File Name", typeof(string));
DataColumn dc2 = new DataColumn("LastAccessTimeForServer1", typeof(DateTime));
DataColumn dc3 = new DataColumn("LastAccessTimeForServer2", typeof(DateTime));
dtForGridView.Columns.Add(dc1);
dtForGridView.Columns.Add(dc2);
dtForGridView.Columns.Add(dc3);
for (int k = 0; k <=2; k++)
{
for (int d = 0; d < numList[k]; d++)//numList[k] will give the number of rows in each column
{
dtForGridView.Rows.Add(ultimateList[d][k], listOfDateTimes[k]);
}
}
//Binding the GridView
GridView1.DataSource = dtForGridView;
GridView1.DataBind();
The final grid should look like:
FileName LastAccessTimeForServer1 LastAccessTimeForServer1
a.txt Time1 Time2
b.txt Time3 Time4
Experts please help in finding a solution.
Any pointers will be highly appreciated.
Regards
Anurag

Related

I need to change IDs in a .txt file based on an excel document

I got a large.txt file where I need to change IDs based on an excel file. The excel table is build like this:
Old ID
new ID
1A1
160
1A10
207
1A11
174
I have in total 354 IDs to be changed.
The problem is that my algorithm changes 1A10 instead of to 207 to 1600 and 1A11 instead of 174 to 1601.. It just sees 1A1 in the .txt file and directly changes it to 160 and then adds 0 or 1 after that.
Any suggestions how to change that? See code below
(...)
ExcelApp.Application excelApp = new ExcelApp.Application();
DataRow myNewRow;
DataTable myTable;
//create book,pages and range variables
ExcelApp.Workbook excelBook = excelApp.Workbooks.Open(#"matching.xlsx");
ExcelApp._Worksheet excelSheet = excelBook.Sheets[1];
ExcelApp.Range excelRange = excelSheet.UsedRange;
//calculate rows and columns
int rows = excelRange.Rows.Count;
int cols = excelRange.Columns.Count;
//define DataTable Name and Column Name
myTable = new DataTable("TranslationTable");
myTable.Columns.Add("Plasma", typeof(string));
myTable.Columns.Add("Thrombus", typeof(string));
//reading columns and rows into DataTable
for (int i = 2; i < rows; i++)
{
myNewRow = myTable.NewRow();
myNewRow["Plasma"] = excelRange.Cells[i, 1].Value2.ToString();
myNewRow["Thrombus"] = excelRange.Cells[i, 3].Value2.ToString();
myTable.Rows.Add(myNewRow);
}
//rewrite Plasma file
StreamReader sr = new StreamReader(#"C:\Users\wviegener\Desktop\Stroke\dataExchange\proteinGroups_Plasma.txt");
String[] row = Regex.Split(sr.ReadToEnd(), "\r\n");
sr.Close();
String old_ID;
String new_ID;
StreamWriter sw = new StreamWriter(#"C:\Users\wviegener\Desktop\Stroke\dataExchange\proteinGroups_Plasma_new.txt");
for(int i = 0; i < row.Length; i++)
{
for (int j = 0; j < myTable.Rows.Count - 1; j++)
{
old_ID = myTable.Rows[j][0].ToString();
new_ID = myTable.Rows[j][1].ToString();
row[i] = row[i].Replace(old_ID,"Thr" + new_ID);
row[i] = row[i].Replace("WDH", "" );
}
sw.WriteLine(row[i]);
the txt files look like this:
proteinGroups_Plasma.txt:
LFQ intensity 1A11_20220429 LFQ intensity 1A12_20220429
proteinGroups_Plasma_new.txt:
LFQ intensity Thr1672_20220429 LFQ intensity Thr312_20220429
If you did something like,
public static IEnumerable<KeyValuePair<string, string>> ReadReplacements()
{
ExcelApp.Application excelApp = new ExcelApp.Application();
//create book,pages and range variables
ExcelApp.Workbook excelBook = excelApp.Workbooks.Open(#"matching.xlsx");
ExcelApp._Worksheet excelSheet = excelBook.Sheets[1];
ExcelApp.Range excelRange = excelSheet.UsedRange;
//calculate rows and columns
int rows = excelRange.Rows.Count;
int cols = excelRange.Columns.Count;
//reading columns and rows into DataTable
for (int i = 2; i < rows; i++)
{
yield return new KeyValuePair<string, string>(
excelRange.Cells[i, 1].Value2.ToString(),
$"Thr{excelRange.Cells[i, 3].Value2.ToString())}";
}
yield return new KeyValuePair<string, string>("WDH", "");
}
IReadOnlyDictionary<string, string> replacements = new Dictionary<string, string>(
ReadReplacements()
.OrderBy(pair => pair.Key.Length));
and then deleted your datatable, and used replacements instead, you could be confident that the order of replacements would not corrupt your data.
This won't address the collision when a Thrombus replacement value contains a subsequent Plasma replacement key. This may not be possible with your business case.
Thats the code now. Works finally
using System;
using System.Data;
using System.Text.RegularExpressions;
using ExcelApp = Microsoft.Office.Interop.Excel;
namespace Stroke
{
class Program
{
static void Main(string[] args)
{
ExcelApp.Application excelApp = new ExcelApp.Application();
DataRow myNewRow;
DataTable myTable;
//create book,pages and range variables
ExcelApp.Workbook excelBook = excelApp.Workbooks.Open(#"C:\Users\wviegener\Desktop\Stroke\dataExchange\matching.xlsx");
ExcelApp._Worksheet excelSheet = excelBook.Sheets[1];
ExcelApp.Range excelRange = excelSheet.UsedRange;
//calculate rows and columns
int rows = excelRange.Rows.Count;
int cols = excelRange.Columns.Count;
//define DataTable Name and Column Name
myTable = new DataTable("TranslationTable");
myTable.Columns.Add("Plasma", typeof(string));
myTable.Columns.Add("Thrombus", typeof(string));
//reading columns and rows into DataTable
for (int i = 2; i < rows; i++)
{
myNewRow = myTable.NewRow();
myNewRow["Plasma"] = excelRange.Cells[i, 1].Value2.ToString();
myNewRow["Thrombus"] = excelRange.Cells[i, 3].Value2.ToString();
myTable.Rows.Add(myNewRow);
}
//reverse Datatable
DataView dv = myTable.DefaultView;
dv.Sort = ("Plasma desc");
DataTable sortedTable = dv.ToTable();
//rewrite Plasma file
StreamReader sr = new StreamReader(#"C:\Users\wviegener\Desktop\Stroke\dataExchange\proteinGroups_Plasma.txt");
String[] row = Regex.Split(sr.ReadToEnd(), "\r\n");
sr.Close();
String old_ID;
String new_ID;
//TODO Erstes und letzes Element nicht ausgetasucht
StreamWriter sw = new StreamWriter(#"C:\Users\wviegener\Desktop\Stroke\dataExchange\proteinGroups_Plasma_new.txt");
for (int i = 0; i < row.Length; i++)
{
for (int j = 0; j < sortedTable.Rows.Count - 1; j++)
{
old_ID = sortedTable.Rows[j][0].ToString();
new_ID = sortedTable.Rows[j][1].ToString();
row[i] = row[i].Replace(old_ID, "Thr" + new_ID);
row[i] = row[i].Replace("WDH", "");
}
sw.WriteLine(row[i]);
}
sw.Close();
}
}
}

C # fill datatable using loops - how?

First of all, I'm just a beginner in C#, so.....don't laugh :-)
OK, I have DataTable named "Changeable" with Columns (Id, A, B, C, D, Fdiv).
The values of A, B, C, D are integers (numbers), Fdiv is decimal number with 13 decimal places and Id is AutoNumber.
I have four(4) counters( loops) like code below, with all possible No. of combination is 21^4
for ( int A = 10; A <= 31; A++)
{
for ( int B = 10; B <= 31; B++)
{
for ( int C = 10; C <= 31; C++)
{
for ( int D = 10; D <= 31; D++)
{
while (A == 31)
{
Fdiv = A/B * C/D
//Code to fill all 5 values in
// DataTable "Changeable", automatic
}
}
}
}
}
How to do this?
Filling a data table with a loop.
private void AddDataToDGV()
{
DataTable dt = new DataTable();
//create some columns for the datatable
DataColumn dc = new DataColumn("ItemName");
DataColumn dc2 = new DataColumn("ItemValue");
DataColumn dc3 = new DataColumn("Blah");
DataColumn dc4 = new DataColumn("Bleh");
//add the columns to the datatable
dt.Columns.Add(dc);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
dt.Columns.Add(dc4);
//create 5 rows of irrelevant information
//this is the actual answer to your question
for (int i = 0; i < 5; i++)
{
DataRow dr = dt.NewRow();//create a new row based on the existing "row model"
dr["ItemName"] = "Item" + i + "Name";
dr["ItemValue"] = "Item" + i + "Value";
dr["Blah"] = "Item" + i + "Blah";
dr["Bleh"] = "Item" + i + "Bleh";
dt.Rows.Add(dr);//add the row to the DataTable
}
}

How to reverse rows in a DataGridView

I am using a data grid, but the values do not display as I would like them to. My current code is below, how would I go about inverting the rows?
string[] strOutput = strLine.Split('_', ',','=');
int totalRows = Convert.ToInt16(strOutput[4]);
int totalCols = Convert.ToInt16(strOutput[5]);
int itemIndex = 8;
for (int i = 0; i < totalCols; i++){
dataGridView1.Columns.Add("Col", "Col");
}
dataGridView1.Rows.Add(totalRows);
for (int i = 0; i < totalRows; i++) {
for (int j = 0; j < totalCols; j++) {
dataGridView1.Rows[i].Cells[j].Value = strOutput[itemIndex];
itemIndex += 2;
}
}
dataGridView1.Visible = true;
To invert i.e. reverse DataGridViewRows you can use this:
void ReverseDGVRows(DataGridView dgv)
{
List<DataGridViewRow> rows = new List<DataGridViewRow>();
rows.AddRange(dgv.Rows.Cast<DataGridViewRow>());
rows.Reverse();
dgv.Rows.Clear();
dgv.Rows.AddRange(rows.ToArray());
}
If you only need to do it once you could instead either:
loop over the lines of the source file in reverse
or instead of Adding the rows (to the end) Insert at the top:
dtnew.Rows.Insert(0, currentDataRowView.Row);
Inverting rows:
"DataGridView.Rows".- will give you "DataGridViewRowCollection"
Iterate the collection in reverse order and create a new datatable. (for loop from max size to zero)
Assign the new datatable to datagridview source.
This rough code written in note pad for your idea. I do not have IDE now.
DataGridViewRowCollection dgRowColllection = dataGridView1.Rows;
DataTable dtnew = new DataTable();
for(i = dataGridView1.RowCount; i < 1 ; i--)
{
DataRowView currentDataRowView = dgRowColllection[i].Row;
dtnew.Rows.Add(currentDataRowView.Row);
}
dataGridView1.source = dtnew;
Can't comment on Pavan's answer because I don't have 50 reputation, but are you getting the error because the loop should be something like:
int totalRows = Convert.ToInt16(strOutput[4]);
int totalCols = Convert.ToInt16(strOutput[5]);
int itemIndex = 8;
for (int i = 0; i < totalCols; i++)
{
dataGridView1.Columns.Add("Col", "Col");
}
dataGridView1.Rows.Add(totalRows);
for (int i = 0; i < totalRows; i++)
{
for (int j = 0; j < totalCols; j++)
{
dataGridView1.Rows[i].Cells[j].Value = strOutput[itemIndex];
itemIndex += 2;
}
DataGridViewRowCollection dgRowColllection = dataGridView1.Rows;
DataTable dtnew = new DataTable();
for (i = dataGridView1.Items.Count; i < 1; i--)
{
DataRowView currentDataRowView = dgRowColllection[i].Row;
dtnew.Rows.Add(currentDataRowView.Row);
}
dataGridView1.DataSource = dtnew;
}
dataGridView1.Visible = true;
}

How to add a column wise row value in data table from for loop

How to add a row in the data table
Code
DataTable dt = new DataTable();
dt.Clear();
DataColumn dc = new DataColumn("day1", typeof(String));
dt.Columns.Add(dc);
dc = new DataColumn("day2", typeof(String));
dt.Columns.Add(dc);
dc = new DataColumn("day3", typeof(String));
dt.Columns.Add(dc);
tString[0] = "Sat,mon,tue";
tString[1] = "Fri,,wed";
tString[2] = "Thu,";
int lengthA = tString.Length;
for (int i = 0; i <= lengthA - 1; i++)
{
string s = tString[i];
string[] words = s.Split(',');
foreach (string word in words)
{
dt.Rows.Add(word);
}
}
The issue in dt.Rows.Add(word) because it is inserting a row
Expected Output
Datatable value should be
day1, day2, day3
sun,mon,tue
Fri,Wed
Thu
Hot to achieve this, can any one help me
Just create a NewRow() and then add the values to its Item indexer for each column.
for (int i = 0; i <= lengthA - 1; i++)
{
string s = tString[i];
string[] words = s.Split(',');
// here is the new row
var row = dt.NewRow();
for(int w = 0; w < words.Length; w++)
{
// set each column
row[w] = words[w];
}
// don't forget to add the Row to the Rows collection
dt.Rows.Add(row);
}

Converting a List<double> to a DataTable is taking a lot of time

I'm building a small software for my clients where they need to read data from 3 list<double>. Each list contains around 50000 data points, they supply the lists to me as an array :
List<double>[] MyVars = new List<double>[3];
for (int x = 0; x < 3; x++)
{
string tempRowCell = "";
tempRowCell = grdMaapingView.GetRowCellValue(0,
grdMaapingView.VisibleColumns[x].FieldName).ToString();
grdMaapingView.GetRowCellValue(x,
grdMaapingView.VisibleColumns[x].Name.ToString());
MyModifiedTable.Columns.Add(tempRowCell, typeof(string));
MyVars[x] = Pressin.GetValuesByFilter(tempRowCell).Values.ToList();
}
for (int c = 0; c < MyModifiedTable.Columns.Count; c++)
{
foreach (double v in MyVars[c])
{
string temp = MyModifiedTable.Columns[c].ColumnName.ToString();
DataRow TempRow = MyModifiedTable.NewRow();
TempRow[temp] = v;
MyModifiedTable.Rows.Add(TempRow);
}
}
grdResults.DataSource = MyModifiedTable.DefaultView;
The problem is I'm reading of the data successfully but it takes a long 75 seconds to read it. What is the problem with the code I have written?
Please if you have any suggestion it's very welcome.

Categories