0

I created a DataGridView in VB.Net without any data source and kept it editable so that user can input the data. Created just 2 columns using built-in "Edit Columns" option in form designer.

Below is my code on click event, I would like to save/get the data as XML that is input by users into the datagridview.

    Dim dt As DataTable = CType(DataGridView1.DataSource, DataTable)
    Dim stream As Stream = New MemoryStream()
    dt = CType(DataGridView1.DataSource, DataTable)

    dt.WriteXml(stream) ''Giving Error at this point

    Dim count As Integer = CInt(stream.Length)
    Dim arr As Byte() = New Byte(count - 1) {}
    stream.Seek(0, SeekOrigin.Begin)
    stream.Read(arr, 0, count)
    Dim utf As UnicodeEncoding = New UnicodeEncoding()
    MsgBox(utf.GetString(arr).Trim())

Now, this gives an error on button click:

Object reference not set to an instance of an object.

Pravesh Agrawal
  • 806
  • 1
  • 10
  • 25
  • If you don't set the datasource with anything how do you expect it to be a DataTable? – Steve Apr 11 '20 at 17:07
  • So what is the best way to achieve it without using datasource, I already mention that in my question. – Pravesh Agrawal Apr 11 '20 at 17:30
  • If you don't want to use a datasource (consider that you can create a DataTable with two columns and fill it without using a database) then you need to loop over your rows and column and build the strings that you want to write and manually build the XML. Are you sure that you don't want to use a DataSource? – Steve Apr 11 '20 at 18:35

0 Answers0