C#.txt内容存入DataTable中
小弟新手,我想把.txt文档内容临时存入DataTable中,请问下面的代码对不?
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog of = new OpenFileDialog();
of.Filter = "*.txt|*.txt";
if (of.ShowDialog() == DialogResult.OK)
{
using (StreamReader sr = new StreamReader(of.FileName, Encoding.Default))
{
int intColCount = 0;
bool blnFlag = true;
DataTable mydt = new DataTable();
DataColumn mydc;
DataRow mydr;
string strline;
string[] aryline;
while ((strline = sr.ReadLine()) != null)
{
aryline = strline.Split(new char[] { '\t' }, StringSplitOptions.None);
if (blnFlag)
{
intColCount = aryline.Length;
for (int i = 0; i < aryline.Length; i++)
{
mydc = new DataColumn(aryline[i]);
mydt.Columns.Add(mydc);
}
}
mydr = mydt.NewRow();
for (int i = 0; i < intColCount; i++)
{
mydr[i] = aryline[i];
}
mydt.Rows.Add(mydr);
}
}
}
MessageBox.Show("保存到DataTable成功!");
}
为什么我在运行时 mydt.Columns.Add(mydc); 这段代码报错
小弟新手,最好能有大神给出完整代码
------解决方案--------------------
你单步调试一下:
会不是因为txt没有内容,导致没有创建列,就添加行了呢?