C# DatagridView CSV Dosyasını İmport Etme
C# ta herhangi bir csv belgesinden datagridviewe veri import etmek için öncelikle formumuza toolboxtan textbox ve openfiledialog ekliyoruz.
İmport işlemini başlatmak için bir buton koyup click eventine giriyoruz. Aşağıdaki kodu yapıştırıyoruz. Koda göre openfiledialog ve textbox isimlerini düzenlemeyi unutmayın.
Projeyi çalıştırıp csv dosyanızı seçtikten sonra datagridviewe verinin import edildiğini görmüş olacaksınız.
openFileDialog1.ShowDialog();
textBox3.Text = openFileDialog1.FileName;
string filePath = textBox3.Text;
DataTable dt = new DataTable();
string[] lines = System.IO.File.ReadAllLines(filePath);
if (lines.Length > 0)
{
string firstLine = lines[0];
string[] headerLabels = firstLine.Split(';');
foreach (string headerWord in headerLabels)
{
dt.Columns.Add(new DataColumn(headerWord));
}
for (int i = 1; i < lines.Length; i++)
{
string[] dataWords = lines[i].Split(';');
DataRow dr = dt.NewRow();
int columnIndex = 0;
foreach (string headerWord in headerLabels)
{
dr[headerWord] = dataWords[columnIndex++];
}
dt.Rows.Add(dr);
}
}
if (dt.Rows.Count > 0)
{
dataGridView1.DataSource = dt;
}