FlexGrid for WinForms | ComponentOne
Save, Load and Print / Load
In This Topic
    Load
    In This Topic

    FlexGrid not only lets you save the grid to various formats but also lets you load data from various formats such text, excel, XML or databases.

    Load from Text File

    To load data from a text file, FlexGrid provides LoadGrid method of the Extensions class. The method has parameters that let you choose delimiter, encoding etc. You can also load text files saved using SaveGrid method. When loading text files, rows and columns are added to the grid if needed to accommodate the file contents. The method supports formats such as comma-delimited text files (CSV format), tab-delimited text files, and even MS Excel files (.xls).

    Following code shows how to populate data in the WinForms FlexGrid by loading it from a text file.

    private void btnLoadTxt_Click(object sender, EventArgs e)
    {
        c1FlexGrid1.LoadGrid("../.../ExportedGrid.txt", FileFormatEnum.TextComma );
    }
    
    Private Sub btnLoadTxt_Click(ByVal sender As Object, ByVal e As EventArgs)
        c1FlexGrid1.LoadGrid("../.../ExportedGrid.txt", FileFormatEnum.TextComma)
    End Sub
    
    Note: To use the LoadGrid method, add C1.Win.C1FlexGrid.ImportExport for .NET Framework, and C1.Win.FlexGrid.ImportExport for .NET

    Load from Excel File

    To load grid from an excel file, you can use the abovementioned LoadGrid method and simply set the format parameter to FileFormatEnum.Excel. You don't need to have Microsoft Excel installed on your computer. However, the LoadGrid method can only load the data from first worksheet of a workbook.

    To get an additional control over how you load your data from an excel file, you can use the LoadExcel method instead. In this case, the process of loading excel files converts most data types and formatting information, including row and column dimensions, fonts, colors, formats, and cell alignment. However, there are still some exceptions. For example, the grid loads the values in excel cells, but cannot load the underlying formulas. Other features such as frozen and merged cells, images, data maps, and cell borders are not translated either.

    Use the code below to load contents in the WinForms FlexGrid from an excel file.

    private void btnLoadExcl_Click(object sender, EventArgs e)
    {
        c1FlexGrid1.LoadExcel("../.../ExportedGrid.xlsx");
    }
    
    Private Sub btnLoadExcl_Click(ByVal sender As Object, ByVal e As EventArgs)
        c1FlexGrid1.LoadExcel("../.../ExportedGrid.xlsx")
    End Sub
    
    Note: To use the LoadExcel method, add C1.Win.C1FlexGrid.ImportExport for .NET Framework, and C1.Win.FlexGrid.ImportExport for .NET.

    Load from Database

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

    Below code demonstrates how to load contents in the WinForms FlexGrid from the database.

    private void btnLoadDB_Click(object sender, 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();
           c1FlexGrid1.Cols.Count = 1;
            foreach (DataRow dr in dt.Rows)
            {
                Column c =c1FlexGrid1.Cols.Add();
                c.Caption = c.Name = (string)dr["ColumnName"];
                c.DataType = (Type)dr["DataType"];
            }
    
            // Populate the grid.
           c1FlexGrid1.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);
               c1FlexGrid1.AddItem(v, row++, 1);
            }
    
            // Cleanup.
           c1FlexGrid1.AutoSizeCols();
            myReader.Close();
            myConn.Close();
        }
    }
    
    Private Sub btnLoadDB_Click(sender As Object, e As EventArgs) Handles btnLoadDB.Click
        'Prepare DataReader.
    
        Dim strConn As String = "Data Source=(localdb)\MSSQLLocalDB; Initial Catalog = Inventory"
        Dim myConn As New System.Data.SqlClient.SqlConnection(strConn)
        Dim myCMD As New SqlCommand("SELECT * FROM Users", myConn)
    
        myConn.Open()
        Dim myReader As SqlClient.SqlDataReader = myCMD.ExecuteReader()
    
        '  Build the grid structure from the DB schema.
        Dim dt As System.Data.DataTable = myReader.GetSchemaTable()
        C1FlexGrid1.Cols.Count = 1
        Dim dr As System.Data.DataRow
        For Each dr In dt.Rows
            Dim c As C1.Win.C1FlexGrid.Column = C1FlexGrid1.Cols.Add()
            c.Caption = CStr(dr("ColumnName"))
            c.Name = CStr(dr("ColumnName"))
            c.DataType = CType(dr("DataType"), Type)
        Next dr
    
        '  Populate the grid.
        C1FlexGrid1.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)
            C1FlexGrid1.AddItem(v, row, 1)
            row += 1
        End While
    
        '  Cleanup.
        C1FlexGrid1.AutoSizeCols()
        myReader.Close()
        myConn.Close()
    End Sub
    

    Load from XML

    To deserialize grid contents from an XML document, you can simply call ReadXml method of the C1FlexGrid class. The ReadXml method allows you to parse path of the XML document as its parameters along with the choice of the FlexGrid element to be loaded using XmlOptions enumeration. Using XmlOptions parameter, you can load ColumnInfo, RowInfo, Ranges, Control, Styles, Maps, Tree, Glyphs, and Images from XML.

    Use the following code to load contents in the WinForms FlexGrid from an XML document.

    private void btnReadXML_Click(object sender, EventArgs e)
    {
        if (File.Exists("ExportedGrid.xml"))
            c1FlexGrid1.ReadXml("ExportedGrid.xml", XmlOptions.All);
        else
            MessageBox.Show("No Layout File Found");
    }
    
    Private Sub btnLoadXML_Click(ByVal sender As Object, ByVal e As EventArgs)
        if (File.Exists("ExportedGrid.xml"))
            c1FlexGrid1.ReadXml("../.../ExportedGrid.xml", XmlOptions.All)
        else
            MessageBox.Show("No Layout File Found")
    End Sub
    

    Further, sorted, filtered, or grouped elements of FlexGrid that are saved to an XML file can be retrieved using the ReadXml method. The XML file loads the elements in the same order as they were stored.

    See Also

    Documentation