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
}
}
Related
I have a datatable filled with information from an excel file. I have more than four columns but to bring an example I'm writing just four of them. I have to write a program in which if the value of the cell in the column C is 0, then I have to copy column B to column A. If the value of the cell in column C is > 0 then i have to copy the column B to A and should add another row in which i have to copy the value of the column C to A.
What i have till now is
for (int r = 2; r <= ws.UsedRange.Rows.Count; r++)
{ if (ws.UsedRange.Cells[r, 3].Text == "0")
{
DataRow row = dt.NewRow();
for (int c = 1; c < ws.UsedRange.Columns.Count; c++)
{
string cell = ws.Cells[r, c].Text;
row[c - 1] = cell;
}
}
So my questions are:
How can i copy a column to another in the same datatable? Copy B to A.
How can i add another row and copy the value of C to A only for that row?
Here is the full code:
public DataTable ReadExcel2(string file)
{
ExcelI.Application app = new ExcelI.Application(); //create an excel instance
ExcelI.Workbook wb = app.Workbooks.Open(file, ReadOnly: true); //open a file
ExcelI.Worksheet ws = wb.Worksheets[1]; //choose a sheet. The firt one
var rng = ws.UsedRange;
//takes the index of the columns that are going to be filtered
int service = ColumnIndexByName(ws.Cells[1, 1].EntireRow, "Service");
int status = ColumnIndexByName(ws.Cells[1, 1].EntireRow, "Status");
int code = ColumnIndexByName(ws.Cells[1, 1].EntireRow, "Code");
DataTable dt = new DataTable();
dt.Columns.Add("A", typeof(string));
for (int c = 1; c < ws.UsedRange.Columns.Count; c++)
{
string colName = ws.Cells[1, c].Text;
int i = 2;
while (dt.Columns.Contains(colName))
{
colName = ws.Cells[1, c].Text + "{" + i.ToString() + "}";
i++;
}
dt.Columns.Add(colName);
}
//do a loop to delete the rows that we dont need
for (int r = 2; r <= ws.UsedRange.Rows.Count; r++)
{
if (ws.UsedRange.Cells[r, 3].Text == "0")
{
DataRow row = dt.NewRow();
for (int c = 1; c < ws.UsedRange.Columns.Count; c++)
{
string cell = ws.Cells[r, c].Text;
row[c - 1] = cell;
}
dt.Rows.Add(row);
row["A"] = row["C"];
}
}
//Close the file
wb.Close();
//release the excel objects from use
Marshal.ReleaseComObject(wb);
Marshal.ReleaseComObject(ws);
//take the id of excel process
int pid = app.PID();
app.Quit();
StartProc("taskkill", $"/f /pid {pid}");
return dt;
}
To add row use dt.Rows.Add(row);, about "copy the column B to A" you mean copy value , just assign row[0] = row[2];, by the way , your example missing a bracket.
I think you should review your code according to conditions in your question, and you can do it yourself as well. Just pay attention to condition you wrote in question and conditional operator you checked in the code.
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);
}
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();
}
}
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
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];
}
}
}
`