none
Issues while accessing a Data Set RRS feed

  • Question

  • Hello,

    I am having a lot of trouble while trying to access a data set.

    What I want to do are the following:

    1. Declare a parameter as Data Set

    2. Access its library to its data grid rows and columns.

    3. Output as rows as data to Notepad by using its Data Set.

    So far, I have the following code snippet:

    Imports System.IO
    Imports Names_Build_001.Names2KDataSetTableAdapters
    Public Class Form1
        Private strOutput As String = "C:\Users\johnd\Documents\Output 01.txt"
        Private tblAdpMangr As tblNamesTableAdapter
        Private tblDtaSet As Names2KDataSet
        Private dtaRow As DataRow
        Private dtaCol As DataColumn
        Private lngID As Long
        Private strFirstName As String
    
        Private Sub TblNamesBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles TblNamesBindingNavigatorSaveItem.Click
            Me.Validate()
            Me.TblNamesBindingSource.EndEdit()
            Me.TableAdapterManager.UpdateAll(Me.Names2KDataSet)
    
        End Sub
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            'TODO: This line of code loads data into the 'Names2KDataSet.tblNames' table. You can move, or remove it, as needed.
            Me.TblNamesTableAdapter.Fill(Me.Names2KDataSet.tblNames)
    
        End Sub
    
        Private Sub OutputNamesButton_Click(sender As Object, e As EventArgs) Handles OutputNamesButton.Click
    
            FileOpen(1, strOutput, OpenMode.Output, OpenAccess.Default, OpenShare.Default)
    
            Do Until tblDtaSet.tblNames.Rows.Count
                Print(1, lngID)
                Print(1, vbTab)
                Print(1, strFirstName)
                Print(1, vbNewLine)
                FileClose(1)
            Loop
    
    
        End Sub
    End Class
    

    When I run it, I received the following error message:

    System.NullReferenceException
      HResult=0x80004003
      Message=Object reference not set to an instance of an object.
      Source=Names Build 001
      StackTrace:
       at Names_Build_001.Form1.OutputNamesButton_Click(Object sender, EventArgs e) in c:\users\johnd\source\repos\Names Build 001\Names Build 001\Form1.vb:line 29
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       at Names_Build_001.My.MyApplication.Main(String[] Args) in :line 81


    jp

    Friday, January 26, 2018 8:56 PM

Answers

  • Private Sub OutputNamesButton_Click(sender As Object, e As EventArgs) Handles OutputNamesButton.Click lngCountZ = 0 lngNameID = 0 'For...next sturcture FileOpen(1, strOutput, OpenMode.Output, OpenAccess.Default, OpenShare.Default) For lngCountZ = 0 To Me.TblNamesDataGridView.Rows.Count - 1 lngX = Me.TblNamesDataGridView.Item(0, lngCountZ).Value strWrdRt = Me.TblNamesDataGridView.Item(1, lngCountZ).Value Print(1, lngX) Print(1, vbTab) Print(1, strWrdRt) Print(1, vbNewLine) Next 'Do Until...loop structure FileOpen(2, strOutputTwo, OpenMode.Output, OpenAccess.Default, OpenShare.Default) Do Until lngNameID = Me.TblNamesDataGridView.Rows.Count lngX = Me.TblNamesDataGridView.Item(0, lngNameID).Value strWrdRt = Me.TblNamesDataGridView.Item(1, lngNameID).Value Print(2, lngX) Print(2, vbTab) Print(2, strWrdRt) Print(2, vbNewLine) lngNameID += 1 Loop FileClose(2) FileClose(1) End Sub

    I do hope I am correct on my answer.  

    Regards,

    JohnDBCTX


    jp

    • Marked as answer by JohnDBCTX Saturday, January 27, 2018 2:20 AM
    Saturday, January 27, 2018 2:19 AM
  • I got it.  Add a running increment calculation.

       Private Sub OutputDataBoundTextBoxToNotepad_Click(sender As Object, e As EventArgs) Handles OutputDataBoundTextBoxToNotepad.Click
    
            FileOpen(3, strOutputThree, OpenMode.Output, OpenAccess.Default, OpenShare.Default)
            For intData = 0 To TblNamesBindingNavigator.Items.Count - 1
                strX = FirstNameTextBox.Text
                Print(3, strX)
                Print(3, vbNewLine)
                intData += 1   'Increment running calculation added
                Me.TblNamesBindingSource.MoveNext()
            Next
            Me.TblNamesTableAdapter.Dispose()
    
            FileClose(3)
    
        End Sub

    I do hope this should help anyone who has issues with bound data text box and binding navigator controls.

    Regards,

    JohnDBCTX


    jp

    • Marked as answer by JohnDBCTX Saturday, January 27, 2018 7:18 AM
    Saturday, January 27, 2018 7:18 AM

All replies

  • It is a long error message because its data set is set to nothing.

    From which library do I need to access its data set, so that I can print out its entire data onto notepad?

    Regards,

    JohnDBCTX


    jp

    Friday, January 26, 2018 9:00 PM
  • Try

    Do Until Names2KDataSet.tblNames.Rows.Count -1
        Print(1, lngID)
        Print(1, vbTab)
        Print(1, strFirstName)
        Print(1, vbNewLine)
        FileClose(1)
    Loop


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Friday, January 26, 2018 9:07 PM
    Moderator
  • Private Sub OutputNamesButton_Click(sender As Object, e As EventArgs) Handles OutputNamesButton.Click lngCountZ = 0 lngNameID = 0 'For...next sturcture FileOpen(1, strOutput, OpenMode.Output, OpenAccess.Default, OpenShare.Default) For lngCountZ = 0 To Me.TblNamesDataGridView.Rows.Count - 1 lngX = Me.TblNamesDataGridView.Item(0, lngCountZ).Value strWrdRt = Me.TblNamesDataGridView.Item(1, lngCountZ).Value Print(1, lngX) Print(1, vbTab) Print(1, strWrdRt) Print(1, vbNewLine) Next 'Do Until...loop structure FileOpen(2, strOutputTwo, OpenMode.Output, OpenAccess.Default, OpenShare.Default) Do Until lngNameID = Me.TblNamesDataGridView.Rows.Count lngX = Me.TblNamesDataGridView.Item(0, lngNameID).Value strWrdRt = Me.TblNamesDataGridView.Item(1, lngNameID).Value Print(2, lngX) Print(2, vbTab) Print(2, strWrdRt) Print(2, vbNewLine) lngNameID += 1 Loop FileClose(2) FileClose(1) End Sub

    I do hope I am correct on my answer.  

    Regards,

    JohnDBCTX


    jp

    • Marked as answer by JohnDBCTX Saturday, January 27, 2018 2:20 AM
    Saturday, January 27, 2018 2:19 AM
  • For the record, going against the DataGridView tere is a .NET way of doing this.

    Create a code module and place this code into it.

    Imports System.IO
    Public Module ExtensionMethods
        <Runtime.CompilerServices.Extension>
        Public Function CreateRowsArray(ByVal sender As DataGridView, Optional ByVal Delimitor As String = ",") As String()
            Return (From row In sender.Rows.Cast(Of DataGridViewRow)() Where (Not CType(row, DataGridViewRow).IsNewRow) Let RowItem = String.Join(Delimitor, Array.ConvertAll(CType(row, DataGridViewRow).Cells.Cast(Of DataGridViewCell)().ToArray(), Function(c As DataGridViewCell) (If(c.Value Is Nothing, "", c.Value.ToString())))) Select RowItem).ToArray()
        End Function
        <Runtime.CompilerServices.Extension>
        Public Sub ExportRows(ByVal pGrid As DataGridView, ByVal pFileName As String, Optional ByVal pDelimiter As String = ",")
            File.WriteAllText(pFileName, String.Join(Environment.NewLine, pGrid.CreateRowsArray(pDelimiter)))
        End Sub
    End Module
    
    

    To write to a text file, tab delimited we do the following which write to Data1.txt in the same folder as your executable which of course you could change the path and file name as desired.

    DataGridView1.ExportRows(IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data1.txt"), vbTab)


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Saturday, January 27, 2018 3:08 AM
    Moderator
  • Thanks for the info tip.

    Now for the data bound text boxes that include a binding navigator control, I got this code snippet below:

    Imports System.IO
    Imports System.Linq
    
    Public Class Form2
        Private strOutputThree As String = "C:\Users\johnd\Documents\Output 03.txt"
        Private intData As Integer
        Private strX As String
    
        Private Sub TblNamesBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles TblNamesBindingNavigatorSaveItem.Click
            Me.Validate()
            Me.TblNamesBindingSource.EndEdit()
            Me.TableAdapterManager.UpdateAll(Me.Names2KDataSet)
    
        End Sub
    
        Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            'TODO: This line of code loads data into the 'Names2KDataSet.tblNames' table. You can move, or remove it, as needed.
            Me.TblNamesTableAdapter.Fill(Me.Names2KDataSet.tblNames)
    
        End Sub
    
        Private Sub OutputDataBoundTextBoxToNotepad_Click(sender As Object, e As EventArgs) Handles OutputDataBoundTextBoxToNotepad.Click
            intData = 0
    
            FileOpen(3, strOutputThree, OpenMode.Output, OpenAccess.Default, OpenShare.Default)
    
            For intData = 0 To TblNamesBindingNavigator.Items.Count - 1
                strX = FirstNameTextBox.Text
                Print(3, strX)
                Print(3, vbNewLine)
                Me.TblNamesBindingSource.MoveNext()
                If intData = TblNamesBindingNavigator.Items.Count Then
                    Me.TblNamesBindingSource.MoveLast()
                    Exit For
                End If
            Next
            Me.TblNamesTableAdapter.Dispose()
    
            FileClose(3)
        End Sub
    End Class

    The output resulted in a print out of the last record six times following the entire list.

    John
    Jack
    Jill
    Phil
    Mary
    Jane
    Jane
    Jane
    Jane
    Jane
    Jane
    Jane

    Note that the last record end up repeating the same number of times as the record count.  

    Instead it is supposed to be the corrected output:

    John
    Jack
    Jill
    Phil
    Mary
    Jane

    For the data bound text boxes, I use the following libraries:

    Table Adapter

    Binding Source

    Binding Navigator

    How could I fix this logical error, so that it does not print out the last record the same number of times as the record count?

    Regards,

    JohnDBCTX


    jp

    Saturday, January 27, 2018 4:18 AM
  • I got it.  Add a running increment calculation.

       Private Sub OutputDataBoundTextBoxToNotepad_Click(sender As Object, e As EventArgs) Handles OutputDataBoundTextBoxToNotepad.Click
    
            FileOpen(3, strOutputThree, OpenMode.Output, OpenAccess.Default, OpenShare.Default)
            For intData = 0 To TblNamesBindingNavigator.Items.Count - 1
                strX = FirstNameTextBox.Text
                Print(3, strX)
                Print(3, vbNewLine)
                intData += 1   'Increment running calculation added
                Me.TblNamesBindingSource.MoveNext()
            Next
            Me.TblNamesTableAdapter.Dispose()
    
            FileClose(3)
    
        End Sub

    I do hope this should help anyone who has issues with bound data text box and binding navigator controls.

    Regards,

    JohnDBCTX


    jp

    • Marked as answer by JohnDBCTX Saturday, January 27, 2018 7:18 AM
    Saturday, January 27, 2018 7:18 AM
  • I have copied and pasted your two routines; there were errors.

    I wish you can explain these routines by clarifying them if you can.

    Here is the error output.

    System.NotImplementedException
      HResult=0x80004001
      Message=The method or operation is not implemented.
      Source=Names Build 001
      StackTrace:
       at Names_Build_001.Form2.CreateRowsArray(DataGridView dtaGrView, String Delimitor) in C:\Users\johnd\source\repos\Names Build 001\Names Build 001\Form2.vb:line 57
       at Names_Build_001.Form2.DelimiterButton_Click(Object sender, EventArgs e) in C:\Users\johnd\source\repos\Names Build 001\Names Build 001\Form2.vb:line 52
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       at Names_Build_001.My.MyApplication.Main(String[] Args) in :line 81

    If only I could plug in those parameters to those routines, then it would make much sense.

    Regards,

    JohnDBCTX


    jp

    Saturday, January 27, 2018 9:59 AM
  • Here is a working example that shows export by DataGridView or typed DataTable.

    In the project above, there is a code module offering two choices, export via the DataGridView or by the typed DataTable.

    Imports System.IO
    Imports System.Text
    Public Module ExtensionMethods
        <Runtime.CompilerServices.Extension>
        Public Function CreateRowsArray(ByVal pGrid As DataGridView, Optional ByVal pDelimitor As String = ",") As String()
            Return (From row In pGrid.Rows.Cast(Of DataGridViewRow)() Where (Not CType(row, DataGridViewRow).IsNewRow) Let RowItem = String.Join(pDelimitor, Array.ConvertAll(CType(row, DataGridViewRow).Cells.Cast(Of DataGridViewCell)().ToArray(), Function(c As DataGridViewCell) (If(c.Value Is Nothing, "", c.Value.ToString())))) Select RowItem).ToArray()
        End Function
        <Runtime.CompilerServices.Extension>
        Public Sub ExportRows(ByVal pGrid As DataGridView, ByVal pFileName As String, Optional ByVal pDelimiter As String = ",")
            File.WriteAllText(pFileName, String.Join(Environment.NewLine, pGrid.CreateRowsArray(pDelimiter)))
        End Sub
    
        <Runtime.CompilerServices.Extension>
        Public Sub ExportRows(ByVal pDataTable As Database1DataSet.CustomerDataTable, ByVal pFileName As String)
            Dim result = String.Join(Environment.NewLine, (From cust In pDataTable Select $"{cust.FirstName,-12} {cust.LastName}").ToArray)
    
            File.WriteAllText(pFileName, result)
    
        End Sub
    End Module

    Form code

    Public Class Form1
        Private Sub CustomerBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles CustomerBindingNavigatorSaveItem.Click
            Me.Validate()
            Me.CustomerBindingSource.EndEdit()
            Me.TableAdapterManager.UpdateAll(Me.Database1DataSet)
    
        End Sub
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            'TODO: This line of code loads data into the 'Database1DataSet.Customer' table. You can move, or remove it, as needed.
            Me.CustomerTableAdapter.Fill(Me.Database1DataSet.Customer)
            Dim dt As DataTable = Me.Database1DataSet.Customer
            Console.WriteLine(dt.Rows.Count)
        End Sub
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            CustomerDataGridView.ExportRows(IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data1.txt"), vbTab)
            Process.Start(IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data1.txt"))
        End Sub
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            Me.Database1DataSet.Customer.ExportRows(IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data2.txt"))
            Process.Start(IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data2.txt"))
        End Sub
    End Class

    After pressing either of the buttons the file is shown.

    Data1.txt which is tab delimited (ugly because of the data doesn't fit nicely into tabs)

    Maria	Anders
    Ana	Trujillo
    Antonio	Moreno
    Thomas	Hardy
    Christina	Berglund
    Hanna	Moos
    Marta	Sommer
    Laurence	Lebihan
    Elizabeth	Lincoln

    Data2.txt, space delimited, looks better but that is up to you.

    Maria        Anders
    Ana          Trujillo
    Antonio      Moreno
    Thomas       Hardy
    Christina    Berglund
    Hanna        Moos
    Marta        Sommer
    Laurence     Lebihan
    Elizabeth    Lincoln

    Note the highlighted parameter, that is the typed DataTable which I loaded the DataGridView with, you would change that to your typed DataTable used in the TableAdapter.Fill method.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    Saturday, January 27, 2018 12:19 PM
    Moderator