ComponentOne True DBGrid for WinForms
Tutorial 19: Using Range Selection
True DBGrid for WinForms Tutorials > Tutorial 19: Using Range Selection

In this tutorial, you will learn how to use the SelectedRows and SelectedCols objects copy a range from the grid in such a format that it can be pasted into Microsoft Excel.

Complete the following steps:

  1. Start with the project created in Tutorial 1: Binding True DBGrid to a DataSet.
  2. Add a command button to the form, place it in the lower left corner of the form, and set its Text property to "Copy".
  3. Next add the following code to the Click event of Button1:

    To write code in Visual Basic

    Visual Basic
    Copy Code
    ' String to be copied to the clipboard.
    Dim strTemp As String
     
    Dim row As Integer
    Dim col As C1.Win.C1TrueDBGrid.C1DataColumn
    Dim cols As Integer, rows As Integer
    If Me.C1TrueDBGrid1.SelectedRows.Count > 0 Then
        For Each row In Me.C1TrueDBGrid1.SelectedRows
     
            ' Copy everything here.
            For Each col In Me.C1TrueDBGrid1.SelectedCols
                strTemp = strTemp & col.CellText(row) & vbTab
            Next
        strTemp = strTemp & vbCrLf
        Next
        System.Windows.Forms.Clipboard.SetDataObject(strTemp, False)
        MessageBox.Show ("Range of " & Me.C1TrueDBGrid1.SelectedCols.Count & " x " & C1TrueDBGrid1.SelectedRows.Count & " cells have been copied to the clipboard in TAB delimited format")
    Else
        MessageBox.Show ("Please select a range of cells")
    End If
    

    To write code in C#

    C#
    Copy Code
    // String to be copied to the clipboard.
    string strTemp;
     
    int row;
    C1.Win.C1TrueDBGrid.C1DataColumn col;
    int cols, rows;
    if (this.c1TrueDBGrid1.SelectedRows.Count > 0 ) 
    {
        foreach (row in this.c1TrueDBGrid1.SelectedRows)
        {
     
            // Copy everything here.
            foreach (col in this.c1TrueDBGrid1.SelectedCols)
            {
                strTemp = strTemp + col.CellText(row) + "\t";
            } 
            strTemp = strTemp + "\n";
         } 
        System.Windows.Forms.Clipboard.SetDataObject(strTemp, false);
        MessageBox.Show ("Range of " + this.c1TrueDBGrid1.SelectedCols.Count.ToString() + " x " + this.c1TrueDBGrid1.SelectedRows.Count.ToString() + " cells have been copied to the clipboard in TAB delimited format");
    } 
    else 
    {
        MessageBox.Show ("Please select a range of cells");
    }
    

Run the program and observe the following:

You've successfully completed using range selection; this concludes the tutorial.