In winForms adding a CSV to a DataGrid was quite easy. I am now trying to add this to a Silverlight DataGrid. Here is my attempt - which yields 3 columns Capacity|Count|Items - mind you the values are correct 83|83|_ on each row. There are 83 rows, but the columns should be 23 with diff values in each. Thanks for looking and enjoy your bounty!
Code:
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
I decided to use the BindableDataGrid from CodePlex Since the binding is being set dynamically I had to come up with a Random string generator and assign that for the binding and all is well.
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()
Related
I'm newbie, I've a XAML file and code behind's, its load all data but I will lazy loading. I binding data in listview. I tried searching but did not produce the expected results, so there is no way that can be done.
code behind:
Public Sub MappingThumbnailSearchResult(thumbSearchResult As VI_ThumbnailSearchResultResponse, token As CancellationToken, ByRef dataDic As Dictionary(Of String, ObservableCollection(Of Object)))
Dim data As List(Of Object) = New List(Of Object)
Try
If thumbSearchResult.result_body Is Nothing OrElse thumbSearchResult.result_body.search_result Is Nothing Then Exit Sub
For Each item In thumbSearchResult.result_body.search_result
Try
If token.IsCancellationRequested Then Exit Sub
Dim thumbnailKey As String = ""
If Not item.thumbnail_key.Contains("\\") Then
thumbnailKey = item.thumbnail_key.ToString().Replace("\", "\\")
Else
thumbnailKey = item.thumbnail_key
End If
Dim imageResult = RequestAPI.GetInstance.GetThumbnailBase64(New VI_ThumbnailRequest With {.ThumbnailKey = thumbnailKey})
Dim hasThumb As Boolean = False
If imageResult IsNot Nothing Then
If imageResult.result_body.thumbnail IsNot Nothing Then
hasThumb = True
Dim base64Str As String = imageResult.result_body.thumbnail
item.thumbnail_base64 = imageResult.result_body.thumbnail
item.thumbnail_bitmap = BaseViewModel.BitmapFromSource(BaseViewModel.Base64ToImage(base64Str))
End If
End If
If Not hasThumb Then
'default image if have error when get thumbnail image
If item.system_type.Equals(EnumType.SystemType.face.ToString()) Then
item.thumbnail_base64 = BaseViewModel.ConvertBitmapToBase64(My.Resources.gender_unknown_2)
item.thumbnail_bitmap = My.Resources.gender_unknown_2
ElseIf item.system_type.Equals(EnumType.SystemType.people.ToString()) Then
item.thumbnail_base64 = BaseViewModel.ConvertBitmapToBase64(My.Resources.People)
item.thumbnail_bitmap = My.Resources.People
End If
End If
Dim tmpDate As DateTime
Dim shotDate As Date
If DateTime.TryParseExact(item.shot_date_time, RESPONSE_DATE_FORMAT2, Nothing, DateTimeStyles.AssumeLocal, tmpDate) Then
shotDate = tmpDate
Else
shotDate = DateTime.Now
End If
Dim dateKey As String = shotDate.ToString(PRIVATE_DATE_FORMAT)
If Not dataDic.ContainsKey(dateKey) Then
Dim thumbList = New ObservableCollection(Of Object)
Dim objThumb As Object = MappingVIThumbnailFromResponse(item, shotDate)
thumbList.Add(objThumb)
dataDic.Add(dateKey, thumbList)
Else
Dim objThumb As Object = MappingVIThumbnailFromResponse(item, shotDate)
dataDic.Item(dateKey).Add(objThumb)
End If
Catch ex As Exception
Dim b As Integer = 0
End Try
Next
Catch ex As Exception
Dim c As Integer = 0
End Try
End Sub
After, I binding data as below
Dim result As ObservableCollection(Of ListViewThumbnailViewModel) = New ObservableCollection(Of ListViewThumbnailViewModel)
If dataDic.Count > 0 Then
If token.IsCancellationRequested Then Return data
For Each pair As KeyValuePair(Of String, ObservableCollection(Of Object)) In dataDic
Dim _date As DateTime = DateTime.ParseExact(pair.Key, PRIVATE_DATE_FORMAT, CultureInfo.InvariantCulture)
result.Add(New ListViewThumbnailViewModel() With {.DateItem = _date, .ListThumbnail = pair.Value})
_viewModel.ResultSearch.TotalData += pair.Value.Count
Next
_viewModel.ResultSearch.ListResult = result
_viewModel.ResultSearch.ListResultActual = result
_viewModel.ResultSearch.PageSize = PageHelper.GetPageSizeWithZoom(_viewModel.ResultSearch.ZoomImage * 10, _viewModel.ResultSearch.PageSizeStart, _viewModel.ResultSearch.NumberChange)
_viewModel.ResultSearch.PageCurrent = 0
_viewModel.ResultSearch.TotalPage = PageHelper.GetTotalPageByPageSize(result.Count, _viewModel.ResultSearch.PageSize)
Else
_viewModel.ResultSearch.ListResult = Nothing
_viewModel.ResultSearch.ListResultActual = Nothing
End If
Catch ex As Exception
Throw New AIMatchingException(ex)
End Try
Return data
What should I do? please help me, thanks!!!
If ServerVersion > localVersion Then
Net.ServicePointManager.DefaultConnectionLimit = 20
Dim url As New Uri(sUrlToReadFileFrom)
Dim request As System.Net.HttpWebRequest = CType(System.Net.WebRequest.Create(url), System.Net.HttpWebRequest)
Dim response As System.Net.HttpWebResponse = CType(request.GetResponse(), System.Net.HttpWebResponse)
response.Close()
Dim iSize As Int64 = response.ContentLength
Dim iRunningByteTotal As Int64 = 0
Using client As New System.Net.WebClient()
Using streamRemote As System.IO.Stream = client.OpenRead(New Uri(sUrlToReadFileFrom))
Using streamLocal As Stream = New FileStream(sFilePathToWriteFileTo, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None)
Dim iByteSize As Integer = 0
Dim byteBuffer(iSize - 1) As Byte
iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)
Do While iByteSize > 0
streamLocal.Write(byteBuffer, 0, iByteSize)
iRunningByteTotal += iByteSize
Dim dIndex As Double = CDbl(iRunningByteTotal)
Dim dTotal As Double = CDbl(byteBuffer.Length)
Dim dProgressPercentage As Double = (dIndex / dTotal)
Dim iProgressPercentage As Integer = CInt(Math.Truncate(dProgressPercentage * 100))
bgDownloader.ReportProgress(iProgressPercentage)
iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)
Loop
streamLocal.Close()
End Using
streamRemote.Close()
End Using
End If
Using the above code in a BackgroundWorker on a VB.NET WPF Project. An error occurs when I try to start the code.
The calling thread cannot access this object because a different thread owns it.
This code works perfectly in WinForms project without any edits/modifications.
Thanks to #Cruled for providing the clue. It has been fixed.
What I did is add invokes on all things needs updating.
I'm having a bit of a problem. Granted, I'm not the best with VB, but I can't figure out for the life of my why this isn't working.
I have an Access database that I pull data from. I'm trying to dynamically create labels so I can present the data as prettily as I want. However, when trying to execute it, I'm getting an exception "System.NullReferenceException: Object reference not set to an instance of an object" on the line arrayLabels(i).Text = "Howdy"
I'm almost certain it's something stupidly simple that I'm just missing... but here's my code:
Private Sub TabControl2_Click(sender As Object, e As EventArgs) Handles TabControl2.Click, btnRefresh1.Click, btnRefresh2.Click, btnRefresh3.Click, ddSelectTech.SelectedIndexChanged, ddSelectTech2.SelectedIndexChanged
If TabControl2.SelectedIndex = 0 Then
'use this to count the number of rows
Dim numRows As Integer
'here be database stuff
Dim da2 As OleDb.OleDbDataAdapter
Dim ds2 As New DataSet
Dim con2 As New OleDb.OleDbConnection
con2.ConnectionString = dbProvider & dbSource
sqlStatusOpen = "SELECT * FROM work_orders WHERE status = 'In Progress';"
da2 = New OleDb.OleDbDataAdapter(sqlStatusOpen, con2)
con2.Open()
da2.Fill(ds2, "installations2")
con2.Close()
numRows = ds2.Tables("installations2").Rows.Count()
'create an array label based on the number of rows in the table
Dim arrayLabels(numRows) As Label
'loop it to actually make the labels, position them, and such
For i = 0 To (numRows - 1) 'just looping the number of rows
Dim x As Integer = 100
Dim y As Integer = 1 + (i * 10)
Try
TabPage3.Controls.Add(arrayLabels(i))
arrayLabels(i).Text = "Howdy"
arrayLabels(i).Location = New Point(x, y)
Catch ex As Exception
MessageBox.Show(ex.ToString, "Looky there, Franky, another error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Next
ElseIf TabControl2.SelectedIndex = 1 Then
ElseIf TabControl2.SelectedIndex = 2 Then
Else
End If
End Sub
Of course, if you think there are better ways to handle this, I'm open to suggestions.
Your code:
Dim arrayLabels(numRows) As Label
Creates an array with the type Label. But every entry in this array is null.
Try to initialize every label in your loop:
Dim label As New Label
label.Text = "Howdy"
label.Location = New Point(x, y)
TabPage3.Controls.Add(label)
And you don't need to save the labels inside an array.
Any Ideas on how to make this to "FOR LOOP" because the number of data that I want to show is not fixed or constant so I need to make it into for loop.
Public Sub ReportTransactionsLogs(ByVal LV As ListView)
Dim rReport As New ReportTransLog
Dim row As DataRow = Nothing
Dim ds As New DataSet
ds.Tables.Add("TransactionsLog")
With ds.Tables(0).Columns
.Add("Username")
.Add("ActionDate")
.Add("ActionTime")
.Add("Activity")
.Add("POInvoice")
End With
For Each LVI As ListViewItem In LV.Items
row = ds.Tables(0).NewRow
row(0) = LVI.Text
row(1) = LVI.SubItems(1).Text
row(2) = LVI.SubItems(2).Text
row(3) = LVI.SubItems(3).Text
row(4) = LVI.SubItems(4).Text
ds.Tables(0).Rows.Add(row)
Next
rReport.SetDataSource(ds.Tables(0))
ReportViewer.CrystalReportViewer1.ReportSource = rReport
End Sub
try like this..
For Each LVI As ListViewItem In LV.Items row = ds.Tables(0).NewRow
For i As Integer = 1 To ds.Table(0).Columns.Count()
If InlineAssignHelper(i, 0) Then
row(i) = LVI.Text
Else
row(i) =LVI.SubItems(i).Text
End If
Next
Next
I need to export a lot (nearly a million) of data everyday from SQLServer to Excel. The data is being processed through a stored procedure then I put them on the DataSet and tried to export using this code:
`
Private Sub ExportToExcel(ByVal dtTemp As System.Data.DataTable, ByVal filepath As String)
Dim strFileName As String = filepath
Dim _excel As New Excel.Application
Dim wBook As Excel.Workbook
Dim wSheet As Excel.Worksheet
wBook = _excel.Workbooks.Add()
wSheet = wBook.ActiveSheet()
Dim dt As System.Data.DataTable = dtTemp
Dim dc As System.Data.DataColumn
Dim dr As System.Data.DataRow
Dim colIndex As Integer = 0
Dim rowIndex As Integer = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
wSheet.Cells(1, colIndex) = dc.ColumnName
Next
For Each dr In dt.Rows
rowIndex = rowIndex + 1
colIndex = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
wSheet.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
wSheet.Columns.AutoFit()
wBook.SaveAs(strFileName)
ReleaseObject(wSheet)
wBook.Close(False)
ReleaseObject(wBook)
_excel.Quit()
ReleaseObject(_excel)
GC.Collect()
End Sub`
Is there any faster way for this?
How about DataSet to Clipboard then paste it to excel?
One way is to save the DataSet as an XML file:
myDataSet.WriteXml("c:\file.xml")
There is a much faster way involving SQL Data Pump (Import Export DTS). You can save a DTS Package (that exports data from SQL to Excel about 1000 rows per second) then run that package using SQL Server Agent. This way, you don't have to iterate to all the rows and columns one by one and you don't need to have a VB code.
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Linq
Imports Excel = Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Core
Imports Microsoft.VisualBasic.DateAndTime
Private Sub Btn_Add_Click(sender As Object, e As EventArgs) Handles btn_Add.Click
DataSetToExcel(ReturnDS("Select * from Membership"), "Test")
End Sub
Public Shared Function DataSetToExcel(myDS As DataSet, fileName As String)
Try
Dim Excel As Object = CreateObject("Excel.Application")
With Excel
.SheetsInNewWorkbook = 1
.Workbooks.Add()
.Worksheets(1).Select()
Dim i As Integer = 1
For col = 0 To myDS.Tables(0).Columns.Count - 1
.Cells(1, i).value = myDS.Tables(0).Columns(col).ColumnName
.Cells(1, i).EntireRow.Font.Bold = True
i += 1
Next
i = 2
Dim j As Integer = 1
For col = 0 To myDS.Tables(0).Columns.Count - 1
i = 2
For row = 0 To myDS.Tables(0).Rows.Count - 1
.Cells(i, j).Value = myDS.Tables(0).Rows(row).ItemArray(col)
i += 1
Next
j += 1
Next
Dim MyTime As String
MyTime = System.DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss")
.Application.DisplayAlerts = False
.ActiveCell.Worksheet.SaveAs(fileName & "_" & MyTime & ".xlsx")
.Workbooks.Close()
End With
Catch ex As Exception
End Try
Return ""
End Function
Public Shared Function ReturnDS(Query As String) As DataSet
Dim con = New SqlConnection(Crypto.ConString)
Dim cmd As New SqlCommand()
Dim myDA As New SqlDataAdapter()
Dim myDS As New DataSet 'The DataSet you created.
cmd.Connection = con
cmd.CommandText = Query
cmd.CommandType = CommandType.Text
myDA.SelectCommand = cmd
myDA.Fill(myDS)
Return myDS
End Function