Databinding a DataGridView control which is not in Form.Controls collection?

前端 未结 1 1164
深忆病人
深忆病人 2021-01-16 09:26

I have a custom control which inherits from DataGridView. It augments the control with some additional functionality (which exports the contents of each cell). I wo

相关标签:
1条回答
  • 2021-01-16 10:08

    David Hall's comment led me to here, which led me to look into the BindingContext of the grid. Sure enough, it's null, but by creating a new BindingContext for the grid control, binding the grid to the DataTable now populates the "Columns" collection.

      public Form1()
      {
         InitializeComponent();
    
         DataTable dataTable = new DataTable() { TableName = "Bob" };
             :
    
         DataGridView grid = new DataGridView { Name = "Tom" };
    
         grid.BindingContext = new BindingContext();
         grid.DataSource = dataTable;
    
         int n1 = grid.Columns.Count; // returns three
      }
    

    Curiously enough, the order in which you set the binding context or the data source appears not to matter !

    0 讨论(0)
提交回复
热议问题