使用DataTable WPF,C#将.CSV文件导入DataGrid [英] Import .CSV File into DataGrid using DataTable WPF,C#

查看:275
本文介绍了使用DataTable WPF,C#将.CSV文件导入DataGrid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好

任何人都可以帮忙,我想使用WPF和C#将CSV文件导入DataGrid,我有5列的文件,第一列是字符串,第二列是字节,第三列是ushort,第四列int32,第五列是int32

在下面的代码中,我只导入了datagrid中的第一列字段,任何人都可以帮助您获取DataGrid中的所有数据,

谢谢

Hello

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,

thanks

private DataTable ReadCSV(string FileName)
      {

          DataTable csvDataTable = new DataTable();
          try
          {
              //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
                  csvDataTable.Columns.Add(headings[i]);

              }

              //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

                  csvDataTable.Rows.Add(row);
                  dataGrid1.ItemsSource = csvDataTable.DefaultView;

              }
          }

          catch (Exception ex)
          {
              System.Windows.Forms.MessageBox.Show(ex.Message.ToString());
          }
          //return the CSV DataTable

          return csvDataTable;


      }

推荐答案

您应该在创建的表中随意添加列的类型:
http://msdn.microsoft.com/en-us/library/hfx3s9wd%28v = vs.80%29.aspx [ ^ ]
You should probarbly add the type of column in the table you are creating:
http://msdn.microsoft.com/en-us/library/hfx3s9wd%28v=vs.80%29.aspx[^]


这篇关于使用DataTable WPF,C#将.CSV文件导入DataGrid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆