VB.Net - Write selected values from DGV to XML file

Good Afternoon,

I need some help with my VB.Net code.

When a button is clicked, my code below grabs "all" of the values from the DGV which is linked to an access database and writes "all" of them to a XML file.

Private Sub btnMUnitSelNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMUnitSelNext.Click

        Try

            'Create a datatable to store XML data
            Dim dt As New DataTable()
            For Each col As DataGridViewColumn In dtgMResults.Columns
                dt.Columns.Add(col.HeaderText)
            Next

            For Each row As DataGridViewRow In dtgMResults.Rows
                Dim dRow As DataRow = dt.NewRow()

                For Each cell As DataGridViewCell In row.Cells
                    dRow(cell.ColumnIndex) = cell.Value
                Next
                dt.Rows.Add(dRow)
            Next

                'Create a dataset
                Dim DS As New DataSet()

                'Add datatable to this dataset
                DS.Tables.Add(DT)


                'Write dataset to XML file
                DS.WriteXml("C:\XMLFile.xml")

                MessageBox.Show("XML data written successfully")
        Catch ex As Exception
            MessageBox.Show("Exception: " + ex.Message)
        End Try

    End Sub

Open in new window


What I can’t seem to figure out is that I want "ONLY" the values the user selects from the DGV to be written to the XML file.

In my DGV I have the selection mode of “FullRowSelect” enabled, so essentially when the user selects a row only those “selected” values should be written to the XML file.

Can anyone help me accomplish this?

Kind Regards,
N
LVL 1
KevinAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

David L. HansenProgrammer AnalystCommented:
This gets the selected rows' data and puts it into a datatable.
dim dt as new datatable

'Do a loop here using this approach (looping through each selectedRow
dt.Rows(i)(j) = dtgMResults.SelectedRows(i).Cells(j).Value

Open in new window


Then you should be able to just use:
dt.WriteXml

I certainly can help with the looping logic if you need.
0
KevinAuthor Commented:
Thanks David, this is still very new to me.

I've done the below for the looping as you suggested but am getting the exception "There is no row at position 0".

Private Sub btnMUnitSelNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMUnitSelNext.Click

        Try

            Dim dt As New DataTable()
            For Each col As DataGridViewColumn In dtgMResults.Columns
                dt.Columns.Add(col.HeaderText)
            Next

            For i As Integer = 0 To dtgMResults.RowCount() - 1
                For j As Integer = 0 To dtgMResults.ColumnCount() - 1
                    dt.Rows(i)(j) = dtgMResults.SelectedRows(i).Cells(j).Value
                Next
            Next

dt.WriteXml("C:\XMLFile.xml")

                MessageBox.Show("XML data written successfully")
        Catch ex As Exception
            MessageBox.Show("Exception: " + ex.Message)
        End Try

Open in new window


My understanding of this is that indexes are zero based so this is why I would need to subtract a 1 for both the row and column, right?

Kindly advise.

regards,
N
0
David L. HansenProgrammer AnalystCommented:
I've gotten that error before when I've referred to a blank DGV. That's not the case here is it? If not, just as a test, begin looping at position 1 (instead of zero) after you've selected multiple rows and see if that helps. Some breakpoints to allow for viewing of specific nodes in the grid wouldn't hurt either.
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

KevinAuthor Commented:
Hi David,

My DGV is certainly not blank. I tried changing the position to a 1 but get the same exception, only it says "There is no row at position 1".

I have MultiSelect disabled for my DGV as the user should only select one row. Nevertheless I tried enabling it and tested by selecting more then one row, but got the same exception.

I threw some breakpoints in and lines 10 and 11 are counting correctly. But the values for i and j on line 12 are showing as 0.

So looks like my selection on the DGV is not being recognized.

Any ideas as to why?
0
KevinAuthor Commented:
I'm wondering something. Should I be using "SelectedCells" instead of "SelectedRows"?

Only one row in my DGV should be ever be selected. So would one row of say 6 columns be considered as cells?

Am just wondering if I am using the correct syntax or not.
0
David L. HansenProgrammer AnalystCommented:
Come to think of it, if the user can only select one row then it makes things much easier!
For j As Integer = 0 To Me.DataGridView1.ColumnCount() - 1
            dt.Rows(0)(j) = dtgMResults.SelectedRows(0).Cells(j).Value
Next

Open in new window

0
David L. HansenProgrammer AnalystCommented:
This is probably more useful:
Dim dt As New DataTable()
For Each col As DataGridViewColumn In dtgMResults.Columns
   dt.Columns.Add(col.HeaderText)
Next

dt.Rows.Add()
For j As Int32 = 0 To Me.DataGridView1.ColumnCount() - 1
   dt(0)(j) = DataGridView1.SelectedRows(0).Cells(j).Value
Next

dt.WriteXml("C:\XMLFile.xml")

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
David L. HansenProgrammer AnalystCommented:
Did that work?
0
KevinAuthor Commented:
Nope getting another exception ("Cannot serialize the DataTable. DataTable name is not set".) now when i try your last solution.

The solution before that is the exception about the position.
0
KevinAuthor Commented:
Scratch that. I got it to work.

Was getting the serialize exception cause i needed to give my table a name.

So added "dt.TableName = "tblUnits"

And it worked.

Dim dt As New DataTable()
            For Each col As DataGridViewColumn In dtgMResults.Columns
                dt.Columns.Add(col.HeaderText)
            Next

            dt.Rows.Add()
            For j As Int32 = 0 To Me.dtgMResults.ColumnCount() - 1
                dt(0)(j) = dtgMResults.SelectedRows(0).Cells(j).Value
            Next

            dt.TableName = "tblUnits"

dt.WriteXml("C:\XMLFile.xml")

Open in new window


Thanks so much for your help.
N
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.