2017-10-15 4 views
0

Salut, je suis txt comme celui-ci (email: mot de passe) et que vous souhaitez télécharger en datagridview avec 2 colonnefichier d'importation txt à datagridview C#

ce que je l'ai fait

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 "); 
      } 
     } 

rien importé mon datagridview

+0

Vous feriez mieux de construire un enumerab le, comme 'DataTable', à partir de vos données, puis simplement le lier à la grille. La liaison de données est presque toujours préférée à la manipulation directe des lignes de la grille. – Crowcoder

+0

Je vois 3 appels ReadLine() '. Ce que vous devez faire est 'While 'pas' for'. – Crowcoder

+0

pouvez-vous le modifier pour moi s'il vous plaît? –

Répondre

1

Voici le code à l'aide d'un 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

merci beaucoup @jdweng –