Link to home
Start Free TrialLog in
Avatar of eleos111
eleos111

asked on

How to Fill a dataset from datagrid

Hi.

In a Windows Application I have a datagrid that has some data displayed with databound from a dataview. The user is allowed to use some filters that are applied in the dataview. So far is easy. Now I want the user to be able to mark rows in the datagrid (using CTRL+click, or Shift+click) and when he press a button these marked rows be stored in a new dataset. How can I do that?
Thanks in advance.
Avatar of iboutchkine
iboutchkine

If hold down the ctrl key when clicking on rows in a datagrid you can
select multiple rows.  You can not select multiple cells.

'Determine selected rows

 Public Function GetSelectedRows(ByVal dg As DataGrid) As System.Collections.ArrayList
          Dim al As New ArrayList()
          Dim cm As CurrencyManager = Me.BindingContext(dg.DataSource, dg.DataMember)
          Dim dv As DataView = CType(cm.List, DataView)
          Dim i As Integer
 
          For i = 0 to dv.Count - 1
               If dg.IsSelected(i) Then
                    al.Add(i)
               End If
          End Next
 
          Return al
 
     End Function 'GetSelectedRows
 
     
      Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
           Dim s As String = "Selected rows:"
          Dim o As Object
 
          For Each o In GetSelectedRows(dataGrid1)
               s += " " + o.ToString()
          Next o
          MessageBox.Show(s) 'here you can addtot the datatable
      End Sub 'button1_Click


Let me know if you need help adding to the datatable
Avatar of eleos111

ASKER

Thanks for the reply.
Of course can mark only rows. That is what I want to do.
So, in 's' will be stored all the datagrid index for the selected rows. And there is an easy way to store the full data of that in a dataset? For example, does exist something like that? :

for Each o in GetSelectedRows(datagrid1)
       MyNewDataset.MyTableName.AddMyTableNameRow(DataGrid1.SelectedRow(o))
next o

Or should I read one by one the ids(that correspond to the dataset) from the datagrid using the above index and then find the corresponding data from the old dataset?
ASKER CERTIFIED SOLUTION
Avatar of iboutchkine
iboutchkine

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Ok, thanks a lot for the help.

Finally I used this one:    

        Dim dr2 As DataRow
        For Each o In GetSelectedRows(dgListEstate)

            dr2 = DsEstates2.ViewEstates.NewRow
            For i = 0 To dr2.ItemArray.Length - 1
                dr2(i) = dvEstates.Item(o).Row.Item(i)
            Next
            DsEstates2.ViewEstates.Rows.Add(dr2)
        Next o

Instead of the loop there I was trying with that line:
 dr2 = dvEstates.Item(o.ToString()).Row
but I was getting an error that row is already in use in another table. :)