文本文件数据如下所示:
FacilityID:12787 FacilityName:ACME Medical Center FacilityLocation:XYZ
FacilityID:27875 FacilityName:Medical Center FacilityLocation:kh
private void ReadFile(string fileName)
{
var rows = System.IO.File.ReadAllLines(fileName);
Char[] separator = new Char[] { ':' };
DataTable tbl = new DataTable(fileName);
if (rows.Length != 0)
{
foreach (string headerCol in rows[0].Split(separator[0]))
{
tbl.Columns.Add(new DataColumn(headerCol));
}
if (rows.Length > 1)
{
for (int rowIndex = 1; rowIndex < rows.Length; rowIndex++)
{
var newRow = tbl.NewRow();
var cols = rows[rowIndex].Split(separator);
for (int colIndex = 0; colIndex < cols.Length; colIndex++)
{
newRow[colIndex] = cols[colIndex];
}
tbl.Rows.Add(newRow);
}
}
}
}
在上面代码中编写的数据表中添加数据。 但它没有正确填充。 &#34; Datatable Wrongly Filled&#34;
FacilityID:12787
FacilityName:ACME Medical Center
FacilityLocation:XYZ
FacilityID:27875
FacilityName:Medical Center
FacilityLocation:kh
我应如何修改数据表应填写的代码,如下所示
FacilityID FacilityName FacilityLocation
12787 ACME Medical Center XYZ
27875 Medical Center kh
答案 0 :(得分:0)
网上已有的一些内容可能对您有所帮助 请仔细阅读以下链接:
http://www.codeproject.com/KB/database/ReadTextFile.aspx http://aspalliance.com/1107_CodeSnip_Reading_CSV_Files_Using_Dataset.all http://www.c-sharpcorner.com/UploadFile/mgold/ConnectODBCText11262005070206AM/ConnectODBCText.aspx
答案 1 :(得分:0)
private string GetID(string str)
{
if (!string.IsNullOrEmpty(str.Split(':')[1]))
{
return str.Split(':')[1].Replace("FacilityName", string.Empty);
}
return string.Empty;
}
private string GetName(string str)
{
if (!string.IsNullOrEmpty(str.Split(':')[2]))
{
return str.Split(':')[2].Replace("FacilityLocation", string.Empty);
}
return string.Empty;
}
private string GetLocation(string str)
{
if (!string.IsNullOrEmpty(str.Split(':')[3]))
{
return str.Split(':')[3];
}
return string.Empty;
}
private string Button Click()
{
string rows = "FacilityID:12787 FacilityName:ACME Medical Center FacilityLocation:XYZ";
DataTable tbl = new DataTable("test");
if (rows.Length != 0)
{
tbl.Columns.Add("FacilityID");
tbl.Columns.Add("FacilityName");
tbl.Columns.Add("FacilityLocation");
var newRow = tbl.NewRow();
newRow[0] = GetID(rows);
newRow[1] = GetName(rows);
newRow[2] = GetLocation(rows);
tbl.Rows.Add(newRow);
dataGridView1.DataSource = tbl.DefaultView;
}
}