1. Buat New Project
(Contoh : ImportCSVToDataGridView).
(Contoh : ImportCSVToDataGridView).
2. Rancang Form 1, 2 buah textbox, 2 buah command button, 1 buah DatagridVIEW, 1 buah label.
3. Dari Toolbox pilih OpenFileDialog pada menu Dialogs.
7. Selamat mencoba
4. Setelah Form selesai dirancang, selanjutnya kita bisa mulai ke coding nya.
berikut ini codingnya :
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 ImportCSVToDataGridView { public partial class Form1 : Form { char delimiter; public Form1() { InitializeComponent(); } private void BtnBrowse_Click(object sender, EventArgs e) { openFileDialog1.InitialDirectory = "c:"; openFileDialog1.Filter = "CSV files (*.csv)|*.CSV"; openFileDialog1.FilterIndex = 2; openFileDialog1.ShowDialog(); textBox1.Text = openFileDialog1.FileName; } private void BtnLoad_Click(object sender, EventArgs e) { string fileRow; string[] fileDataField; int count = 0; if (textBox1.Text != "" && textBox2.Text != "") { delimiter = Convert.ToChar(textBox2.Text); try { if (System.IO.File.Exists(textBox1.Text)) { System.IO.StreamReader fileReader = new StreamReader(textBox1.Text); if (fileReader.Peek() != -1) { fileRow = fileReader.ReadLine(); fileDataField = fileRow.Split(delimiter); count = fileDataField.Count(); count = count - 1; //Reading Header information for (int i = 0; i <= count; i++) { DataGridViewTextBoxColumn columnDataGridTextBox = new DataGridViewTextBoxColumn(); columnDataGridTextBox.Name = fileDataField[i]; columnDataGridTextBox.HeaderText = fileDataField[i]; columnDataGridTextBox.Width = 120; dataGridView1.Columns.Add(columnDataGridTextBox); } } else { MessageBox.Show("File is Empty!!"); } //Reading Data while (fileReader.Peek() != -1) { fileRow = fileReader.ReadLine(); fileDataField = fileRow.Split(delimiter); dataGridView1.Rows.Add(fileDataField); //DataLoaded = true; } fileReader.Close(); } else { MessageBox.Show("No File is Selected!!"); } } catch (Exception exceptionObject) { MessageBox.Show(exceptionObject.ToString()); } } else { MessageBox.Show("Please fill the empty text box"); } } } }
5. Klik Save dan Kemudian Run (F5).
6. Jika program sebelumnya tidak terdapat salah penulisan maka program akan berjalan seperti gambaran berikut.
Share this
All sharing is only for you guys...
-----------------------------------