关于读取TXT文件的问题
就是我在datgridview里先添加了数据,而后我读取txt文件到里面的时候如何不覆盖先添加的数据,求指教!添加的代码
public static List<Person> alldata = new List<Person>();
public Form1()
{
InitializeComponent();
}
private void btn_添加_Click(object sender, EventArgs e)
{
if (tb_学号.Text==""||tb_姓名.Text==""||tb_课程名.Text==""||tb_分数.Text=="")
{
MessageBox.Show("信息不能为空!");
return;
}
Person person = new Person();
person.Id = tb_学号.Text;
person.Name = tb_姓名.Text;
person.Lesson = tb_课程名.Text;
person.Grade = tb_分数.Text;
alldata.Add(person);
dataGridView1.DataSource = null;
dataGridView1.DataSource = alldata;
}
读取txt文件的代码
private void button2_Click(object sender, EventArgs e)--------------------编程问答-------------------- 把button2_Click中的alldata.Clear();这行去掉就可以, --------------------编程问答-------------------- 顺便说一下,你直接绑定alldata很容易出问题,最好创建一个BindingSource对象,然后把dataGridView1.DataSource邦定到BindingSource对象,再把alldata邦定到BindingSource对象,这样可以避免很多问题, --------------------编程问答-------------------- 就是您能说具体点吗?就是您说的绑定对象。最好给点代码的提示,谢谢 --------------------编程问答--------------------
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "TXT表格(txt)|*.txt";
ofd.RestoreDirectory = true;
ofd.Title = "加载数据";
string filepath = "";
if (ofd.ShowDialog() == DialogResult.OK)
{
filepath = ofd.FileName;
}
if (filepath == "") return;
alldata.Clear();
string[] dedao = File.ReadAllLines(filepath);
for (int i=0; i < dedao.Count(); i++)
{
string[] duixiang = dedao[i].Split('#');
Person person = new Person();
person.Id = duixiang[0];
person.Name = duixiang[1];
person.Lesson = duixiang[2];
person.Grade = duixiang[3];
alldata.Add(person);
}
dataGridView1.DataSource = null;
dataGridView1.DataSource = alldata;
}
+1
补充:.NET技术 , C#