2017-10-15 151 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 –