Click here to Skip to main content
15,923,120 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:

Can anyone help please,i want to import CSV File into DataGrid using WPF and C#, i have file with 5 columns , first columns is string ,second columns is byte, third is ushort, fourth int32,fifth is int32

in below code am importing only first column fields in datagrid, can anyone help how to get all data in DataGrid,

private DataTable ReadCSV(string FileName)

          DataTable csvDataTable = new DataTable();
              //no try/catch - add these in yourselfs or let exception happen
              String[] csvData = File.ReadAllLines(FileName);

              //if no data
              if (csvData.Length == 0)
                  return csvDataTable;

              String[] headings = csvData[0].Split(';');

              //for each heading
              for (int i = 0; i < headings.Length; i++)
                  ////replace spaces with underscores for column names
                  //headings[i] = headings[i].Replace(" ", "_");

                  //add a column for each heading


              //populate the DataTable
              for (int i = 1; i < csvData.Length; i++)
                  //create new rows
                  DataRow row = csvDataTable.NewRow();

                  for (int j = 0; j < headings.Length; j++)
                      //fill them
                      row[j] = csvData[i].Split(';')[j];


                  //add rows to over DataTable

                  dataGrid1.ItemsSource = csvDataTable.DefaultView;


          catch (Exception ex)
          //return the CSV DataTable

          return csvDataTable;

Updated 30-Aug-12 21:46pm

1 solution

You should probarbly add the type of column in the table you are creating:[^]
Share this answer
getanswer 31-Aug-12 4:28am    
hi, thanks for reply, can you help me please , i tried but getting error, "Column name already belongs to DataTable", thanks
Kenneth Haugland 31-Aug-12 4:42am    
All columnnames must be unique, otherwise you'll get that error.
getanswer 31-Aug-12 4:45am    
hi, yes i have all columns unique name,

am taking Heading from this csvDataTable.Columns.Add(headings[i]);

i think this is irrespctive of variable, either string or ushort or int.

Kenneth Haugland 31-Aug-12 4:51am    
csvDataTable.Columns.Add(headings[i].ToString(), , typeof(String))?
getanswer 31-Aug-12 4:56am    
same error, "Column name already belongs to DataTable",

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900