ComponentOne FlexGrid for WinForms
Loading Grids from Databases
Using the C1FlexGrid Control > Saving, Loading, and Printing > Loading Grids from Databases

You can also load grid data from a database. This is different from data binding, which keeps a live connection between one or more controls and the underlying data source. To load data from a database, you can use DataReader objects, as shown below:

To write code in Visual Basic

Visual Basic
Copy Code
Private Sub _btnData_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles _btnData.Click
 
    '  Prepare DataReader.
    Dim strConn As String = "data source=MYMACHINE;initial catalog=Northwind;"
    Dim myConn As New SqlClient.SqlConnection(strConn)
    Dim myCMD As New SqlClient.SqlCommand("SELECT * FROM Employees", myConn)
    myConn.Open()
    Dim myReader As SqlClient.SqlDataReader = myCMD.ExecuteReader()
 
    '  Build the grid structure from the DB schema.
    Dim dt As DataTable = myReader.GetSchemaTable()
    _flex.Cols.Count = 1
    Dim dr As DataRow
    For Each dr In  dt.Rows
        Dim c As C1.Win.C1FlexGrid.Column = _flex.Cols.Add()
        c.Caption =(c.Name <= CStr(dr("ColumnName")))
        c.DataType = CType(dr("DataType"), Type)
    Next dr
 
    '  Populate the grid.
    _flex.Rows.Count = 1
    Dim row As Integer = 1
    Dim cols As Integer = dt.Columns.Count
    Dim v As Object() = CType(Array.CreateInstance(GetType(Object), cols), Object())
    While myReader.Read()
        myReader.GetValues(v)
        _flex.AddItem(v, row + 1, 1)
    End While
 
    '  Cleanup.
    _flex.AutoSizeCols()
    myReader.Close()
    myConn.Close()
End Sub

To write code in C#

C#
Copy Code
private void _btnData_Click(object sender, System.EventArgs e)
{
    // Prepare DataReader.
    string strConn = "data source=MYMACHINE;initial catalog=Northwind;";
    System.Data.SqlClient.SqlConnection myConn = new System.Data.SqlClient.SqlConnection(strConn);
    System.Data.SqlClient.SqlCommand myCMD = new System.Data.SqlClient.SqlCommand("SELECT * FROM Employees", myConn);
    myConn.Open();
    System.Data.SqlClient.SqlDataReader myReader = myCMD.ExecuteReader();
 
    // Build the grid structure from the DB schema.
    DataTable dt = myReader.GetSchemaTable();
    _flex.Cols.Count = 1;
    foreach (DataRow dr in dt.Rows)
    {
        Column c = _flex.Cols.Add();
        c.Caption = c.Name = (string)dr["ColumnName"];
        c.DataType = (Type)dr["DataType"];
    }
 
    // Populate the grid.
    _flex.Rows.Count = 1;
    int row = 1;
    int cols = dt.Columns.Count;
    object[] v = (object[])Array.CreateInstance(typeof(object), cols);
    while (myReader.Read())
    {
        myReader.GetValues(v);
        _flex.AddItem(v, row++, 1);
    }
 
    // Cleanup.
    _flex.AutoSizeCols();
    myReader.Close();
    myConn.Close();
}
See Also