I have three arrays as mentioned below. Trying to populate the datatable. But the output was not expected.
needed in this Format
AnalyteNames = new string[] { "NA", "K", "CL" };
Units = "MML";
values= new string[]{"14", "15","16"}
The below was the written code.
int count = 0;
for (int col = 0; col < dataSave.Columns.Count; col++)
{
int i = 0;
if (col == 0)
{
for (int row = 1; row < dataSave.Rows.Count - 1; row++)
{
dr[col] = CheckedAnalytes[i];
i++;
}
}
if (count == 1)
{
i = 0;
for (int row = 1; row < dataSave.Rows.Count - 1; row++)
{
dr[col] = SelectedUnits;
}
}
if (count == 2)
{
i = 0;
for (int row = 1; row < dataSave.Rows.Count - 1; row++)
{
dr[col] = values[i];
i++;
}
}
count++;
}
Assuming three arrays with the same length:
var analyteNames = new string[] { "NA", "K", "CL" };
var units = new string[]{"MML", "MML", "MML"};
var values = new string[]{"14", "15","16"};
And a data table with three columns:
var dt = new DataTable();
dt.Columns.Add("analyteNames", typeof(string));
dt.Columns.Add("units", typeof(string));
dt.Columns.Add("values", typeof(string));
You can use a single loop, using the DataRowCollection
Add
method overload that accepts params object[]
:
for(var i = 0; i < analyteNames.Length; i++)
{
dt.Rows.Add(analyteNames[i], units[i], values[i]);
}
If it was me I'll populate a Custom List insert Values into it and the populate DataTable()
Custom List
public class Values
{
public int value1
{
get;
set;
}
public string value2
{
get;
set;
}
public string value3
{
get;
set;
}
}
Next Populate the List
List<Values> list = new List<Values>();
list.Add(new Values{
value1 = 1,
value2 = "",
value3 = ""
});
Next Populate your DataTable()
var dt = new DateTable();
dt.Columns.Add(Header1, typeof(int));
dt.Columns.Add(Header2, typeof(string));
dt.Columns.Add(Header3, typeof(string));
foreach(var item in list)
{
dt.Rows.Add(item.value1,item.value2,item.value3);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.