Bind RadGridView to DataTable programatically

2 posts, 0 answers
  1. Greg
    Greg avatar
    7 posts
    Member since:
    Jan 2009

    Posted 23 Sep Link to this post

    Hello,

     

    I'm trying to use RadGridView to export a datatable to Excel.  I've created a method that takes a datatable as a parameter, creates a RadGridView, sets the dataSource to the datatable, and then exports.  Problem is that the RadGridview doesn't seem to be getting populated with the contents of the dataTable.  I feel like I'm missing something like 'gridView.DataBind();' but I can't find anything like that in the documentation.  Code is below:

    public static void ExportToExcel(DataTable myDT)

            {             using (Telerik.WinControls.UI.RadGridView grid = new Telerik.WinControls.UI.RadGridView())

                {

                    grid.AutoGenerateColumns = true;

                    grid.DataSource = myDT;

                    //grid.LoadElementTree();

                    //grid.Refresh();

                    GridViewSpreadExport spreadExporter = new GridViewSpreadExport(grid);                 SpreadExportRenderer exportRenderer = new SpreadExportRenderer();

                    spreadExporter.RunExport("c:\\exportedFile.xlsx", exportRenderer);

                }

            }

  2. Dess
    Admin
    Dess avatar
    1601 posts

    Posted 27 Sep Link to this post

    Hello Greg,

    Thank you for writing.  

    The provided code snippet is greatly appreciated. Note that it is important to initialize the RadGridView.BindingContext before setting the DataSource property:

    public Form1()
    {
        InitializeComponent();
        DataTable dt = new DataTable();
        dt.Columns.Add("Id");
        dt.Columns.Add("Name");
        for (int i = 0; i < 10; i++)
        {
            dt.Rows.Add(i, "Item" + i);
        }
        using (Telerik.WinControls.UI.RadGridView grid = new Telerik.WinControls.UI.RadGridView())
        {
            grid.AutoGenerateColumns = true;
            grid.BindingContext = new System.Windows.Forms.BindingContext();
            grid.DataSource = dt;
            GridViewSpreadExport spreadExporter = new GridViewSpreadExport(grid);                
            SpreadExportRenderer exportRenderer = new SpreadExportRenderer();
            string fileName = @"..\..\exported" + DateTime.Now.ToLongTimeString().Replace(":", "_") + ".xlsx";
            spreadExporter.RunExport(fileName, exportRenderer);
            Process.Start(fileName);
        }
    }

    I hope this information helps. Should you have further questions I would be glad to help.

    Regards,
    Dess
    Telerik by Progress
    Check out the Windows Forms project converter, which aids the conversion process from standard Windows Forms applications written in C# or VB to Telerik UI for WinForms.For more information check out this blog post and share your thoughts.
  3. UI for WinForms is Visual Studio 2017 Ready
Back to Top