我正在根据下面显示的方法将文本文件中的数据添加到数据表中:假设这些是我在第一个文本文件中使用的行:
data1, data2
1,2
假设这些是我在第二个文本文件中使用的行:
data1, data2
3,4
我会将它们插入到数据表中,如下所示:
到目前为止,我已经完成了编码,并且可以成功运行。当第 3 个文本文件包含如下所示的数据时,会出现此问题:
data1, data0, data2
5,6,7
在这种情况下,我需要重新排列我的数据表,如下所示:
我尝试了很多方法,但它一直只将数据添加到数据表的末尾。有人可以帮忙吗。我在下面提供了我的编码:
private DataTable CreateDT1(string name, ListBox list)
{
DataTable dt = new DataTable();
string[] files = new string[list.Items.Count];//text files are taken to a list box
for (int x = 0; x < list.Items.Count; x++)
{
object s = list.Items[x];
files[x] = s.ToString();
}
int lineno = 0;
for (int i = 0; i < files.Length; i++)
{
int count = 0;
string file = files[i];
using (System.IO.StreamReader sr = new System.IO.StreamReader(file))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains(name))//i'm filtering some lines containing a given string
{
if (i == 0)
{
if (lineno == 0)//first line in the first test file. Eg: data1,data2
{
string[] split = line.Split(',');//splitting the line adding data to rows
int result = split.Length;
dt.Rows.Add();
for (int x = 0; x < result; x++)
{
DataColumn dc = new DataColumn(x.ToString(), Type.GetType("System.String"));
dt.Columns.Add(dc);
dt.Rows[lineno][x] = split[x];
}
}
else
{
string[] split = line.Split(',');//splitting the other lines in 1st text file and adding data to rows
int result = split.Length;
dt.Rows.Add();
for (int x = 0; x < result; x++)
{
dt.Rows[lineno][x] = split[x];
}
}
}
else
{
if (count != 0)//for other (2nd, 3rd, ..)text files. This refers to the lines other than the 1st line(5,6,7). First line (data1, data0, data2)of these text files are not accounted here.
{
string[] split = line.Split(',');
int result = split.Length;
dt.Rows.Add();
for (int x = 0; x < result; x++)
{
dt.Rows[lineno][x] = split[x];
}
}
else //this is the first line of other files
{
string[] split = line.Split(',');
int result = split.Length;
if (result + 1 > dt.Columns.Count)//if existing number of columns are less than the split result of the first line, add new columns accordingly. I need help at this point
{
for (int x = 0; x < result; x++)
{
Object a = dt.Rows[0][x];
if (split[x] == Convert.ToString(a))
{
dt.Rows[0][x] = split[x];
}
else
{
dt.Columns.Add(x.ToString() + split[x]).SetOrdinal(x + 1);
//dt.Columns.Add(x.ToString() + split[x]).SetOrdinal(x);
dt.Rows[0][x.ToString() + split[x]] = split[x];
}
}
lineno -= 1;
count += 1;
}
else
{
lineno -= 1;
count += 1;
}
}
}
lineno += 1;
}
}
}
}
return dt;
}