将CSV导入DataGrid

时间:2013-06-08 23:16:54

标签: silverlight silverlight-5.0

winForms中向DataGrid添加CSV非常简单。我现在正尝试将其添加到Silverlight DataGrid。这是我的尝试 - 产生3列Capacity|Count|Items - 请注意每行的值是正确的83 | 83 | _ 。有83行,但列应为23,每行有diff值。感谢您寻找并享受您的赏金!

代码:

Try
  Dim ofd As New OpenFileDialog
  If ofd.ShowDialog Then
    If IO.File.Exists(ofd.File.FullName) Then
      Dim srsCol As New List(Of List(Of String))
      Using fs As IO.FileStream = ofd.File.OpenRead
        Using sr As New IO.StreamReader(fs)
          While Not sr.Peek = -1
            srsCol.Add(New List(Of String)(sr.ReadLine.Split(","c).ToList))
          End While
        End Using
      End Using
      dgStaff.ItemsSource = srsCol
    End If
  End If
Catch ex As Exception
  MessageBox.Show(ex.ToString)
End Try

1 个答案:

答案 0 :(得分:2)

我决定使用BindableDataGrid from CodePlex因为绑定是动态设置的,我必须想出一个随机字符串生成器并为绑定指定它,一切都很好。

csvDs.Tables.Clear()
Try
  Dim ofd As New OpenFileDialog
  If ofd.ShowDialog Then
    If IO.File.Exists(ofd.File.FullName) Then
      csvDs.Tables.Add(csvDt)
      Using fs As IO.FileStream = ofd.File.OpenRead
        Using sr As New IO.StreamReader(fs)
          Dim i As Integer
          While Not sr.EndOfStream
            If i = 0 Then
              Dim cols = sr.ReadLine.Split(","c)
              For ii As Integer = 0 To cols.Count - 1
                Dim rndValue As String = RndColName()
                Dim col As New BindableDataGrid.Data.DataColumn(rndValue)
                rndValues.Add(rndValue)
                col.DataType = GetType(System.String)
                col.Caption = ii.ToString
                col.ReadOnly = True
                col.AllowReorder = False
                col.AllowResize = False
                col.AllowSort = False
                csvDt.Columns.Add(col)
                AddItemsToCb(ii)
              Next
              Dim row As New BindableDataGrid.Data.DataRow
              For _i As Integer = 0 To cols.Count - 1
                Dim s As String = cols(_i).Replace("""", String.Empty)
                row(rndValues(_i)) = s
                csvValues.Add(s)
              Next
              csvDt.Rows.Add(row)
            Else
              Dim cols = sr.ReadLine.Split(","c)
              Dim row As New BindableDataGrid.Data.DataRow
              For _i As Integer = 0 To cols.Count - 1
                row(rndValues(_i)) = cols(_i).Replace("""", String.Empty)
              Next
              csvDt.Rows.Add(row)
            End If
            i += 1
          End While
        End Using
      End Using
      dgStaff.DataSource = csvDs
      dgStaff.DataMember = "csvTable"
      dgStaff.DataBind()