True DBGrid for WinForms | ComponentOne
In This Topic
    Best Practices
    In This Topic

    In order to leverage the full potential of True DBGrid and turn it to your advantage, there are a number of best practices to keep in mind.

    The following topics will guide you through some of the best practices that can be followed while working with True DBGrid.

    Tip 1: Use the SetDataBinding method to keep layout of grid intact

    If the DataSource is reset through code, it will show all of the data in the grid and will not keep the initial layout created with the Designer.

    You can ensure that the grid layout remains as designed by using the SetDataBinding method with the HoldFields parameter set to True. For example:

    C#
    Copy Code
    this.c1TrueDBGrid1.SetDataBinding(this.DbDataSet, "Customer", true);
    

    Tip 2: Setting column styles through FetchCellStyle event

    Since columns can be moved and sorted, you should generally be careful about using the display column index and the column index as these may refer to different columns.

    You can ensure that a style is associated with a particular display column. In the following example, a style is associated with a display column through the FetchCellStyle event:

    C#
    Copy Code
    private void c1TrueDBGrid1_FetchCellStyle(object sender, FetchCellStyleEventArgs e)
    {
        if (this.c1TrueDBGrid1.Splits[0].DisplayColumns[e.Col].DataColumn.Value.GetType() == typeof(string))
        {
            e.CellStyle.ForeColor = Color.Red;
        }
    }
    

    Tip 3: Getting current column and row number of the Grid.

    It can be really useful to find out what cell a user is interacting with, or what cell is currently selected. Getting the column number and row number of the selected cell is very simple to do.

    For example, the following code determines and displays the row and column number of the current cell:

    C#
    Copy Code
    this.c1TrueDBGrid1.Row = this.c1TrueDBGrid1.RowContaining(c1TrueDBGrid1.Row);
    this.c1TrueDBGrid1.Col = this.c1TrueDBGrid1.ColContaining(c1TrueDBGrid1.Col);
    MessageBox.Show("The number of the column is " + this.c1TrueDBGrid1.Col + " the row row number is " + this.c1TrueDBGrid1.Row);
    

    Tip 4: Stop users from collapsing the grid into the normal data view when in the hierarchical data view

    When the grid is in the hierarchical data view you can easily stop users from collapsing the grid back to the normal data view.

    Using the Collapse event, set e.Cancel = True to prevent users from collapsing the expand icon. For example:

    C#
    Copy Code
    private void c1TrueDBGrid1_Collapse(object sender, BandEventArgs e)
    {
        e.Cancel = true;
    }