h1.post-title { color:orange; font-family:verdana,Arial; font-weight:bold; padding-bottom:5px; text-shadow:#64665b 0px 1px 1px; font-size:32px; } -->

Pages

Fetch Text File Data into Datagridview in C#.Net

Today ,we will discuss about how to fetch data from Text File into Datagridview in C#.net
Text File Data Format
111;222
333;444
555;666
777;888
Code 
private void DispaydatafromTextFile(string txtFilePath)
 {
 //1st you must create columns to dgv, like:
 dataGridView1.Columns.Add("col1", "Column1");
 dataGridView1.Columns.Add("col2", "Column2");
 //and so on...
 using (StreamReader sr = new StreamReader(txtFilePath))
 {
 int row = 0;
 string line;
 while ((line = sr.ReadLine()) != null)
 {
 string[] columns = line.Split(';');
 dataGridView1.Rows.Add();
 for (int i = 0; i < columns.Length; i++)
 {
 dataGridView1[i, row].Value = columns[i];
 }
 row++;
 }
 }
 }
 private void button1_Click(object sender, EventArgs e)
 {
 DispaydatafromTextFile(@"C:\Test.txt");
 textBox1.Text = Convert.ToString(dataGridView1.CurrentRow.Cells[0].Value);
 textBox2.Text = Convert.ToString(dataGridView1.CurrentRow.Cells[1].Value);
 }
 private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
 {
 textBox1.Text = Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells[0].Value);
 textBox2.Text = Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells[1].Value);
 }