嗨我有这样的txt文件(电子邮件:密码),并希望将其上传到带有2列的datagridview
我做了什么
bool flag = this.openFileDialog1.ShowDialog() != DialogResult.Cancel;
if (flag)
{
try
{
StreamReader streamReader = new StreamReader(openFileDialog1.FileName);
dataGridView1.AllowUserToAddRows = false;
string text = streamReader.ReadLine();
string[] array = text.Split(new char[]
{
':'
});
for (text = streamReader.ReadLine(); text != null; text = streamReader.ReadLine())
{
dataGridView1.Rows.Add();
for (int i = 0; i <= array.Count<string>() - 1; i++)
{
array = text.Split(new char[]
{
':'
});
dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[i].Value = array[i].ToString();
}
}
streamReader.Close();
}
catch (Exception var_7_106)
{
MessageBox.Show("Error+ err.Message ");
}
}
我的datagridview中没有导入任何内容
答案 0 :(得分:1)
以下是使用数据表的代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
bool flag = this.openFileDialog1.ShowDialog() != DialogResult.Cancel;
if (flag)
{
DataTable dt = new DataTable();
dt.Columns.Add("Col A", typeof(string));
dt.Columns.Add("Col B", typeof(string));
try
{
StreamReader streamReader = new StreamReader(openFileDialog1.FileName);
dataGridView1.AllowUserToAddRows = false;
string text = "";
for (text = streamReader.ReadLine(); text != null; text = streamReader.ReadLine())
{
string[] array = text.Split(new char[] { ':' });
dataGridView1.Rows.Add(array);
}
streamReader.Close();
}
catch (Exception err)
{
MessageBox.Show("Error" + err.Message );
}
dataGridView1.DataSource = dt;
}
}
}
}