2017-10-15 147 views
0

您好我有TXT文件像这样(电子邮件:密码),并希望将其与2列导入txt文件到datagridview的C#

我做了什么

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的我的datagridview

+0

你会更好构建enumerab le,就像'DataTable'一样,从你的数据中把它绑定到网格上。数据绑定几乎总是首选直接操纵网格行。 – Crowcoder

+0

我看到3'ReadLine()'调用。你需要做的是'虽然'不'为'。 – Crowcoder

+0

你能为我编辑吗? –

回答

1

下面是使用代码的DataTable

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; 
      } 
     } 
    } 
} 
+0

非常感谢你@jdweng –