c# binding datagridview to datatable in form vs co

2019-07-13 07:34发布

问题:

I have the following code:

        DataGridView lGrid = new DataGridView();
        BindingSource _bind = new BindingSource();
        DataTable Table = new DataTable();

        this.Controls.Add(lGrid);
        lGrid.AutoGenerateColumns = true;


        List<string> ColumnsNames = new List<string>();
        ColumnsNames.Add("ID");
        ColumnsNames.Add("NAME");

        foreach (string Name in ColumnsNames)
            Table.Columns.Add(Name);

        DataColumn col = Table.Columns["ID"];
        DataColumn[] keys = new DataColumn[1];
        keys[0] = Table.Columns["ID"];
        Table.PrimaryKey = keys;

        lGrid.DataSource = _bind;
        _bind.DataSource = Table;

        int i = lGrid.Columns.Count;

which populates lGrid with columns in datatable just fine with this code executing in the form constructor. However, when I move it to the control constructor binding doesn't work and i = 0. Why is it so and what can i do about it?

Update1

OK. the constructors are the most simple

public partial class Form1 : Form {

    public Form1()
    {
          InitializeComponent();
         //CODE GOES HERE
    }
}

VS

public class mycontrol : Control
{
    public mycontrol()
    {
        //CODE GOES HERE
    }
}


public partial class Form1 : Form
{

    public Form1()
    {
          InitializeComponent();

          mycontrol ll = new mycontrol();
          this.Controls.Add(ll);
    }
}

回答1:

Use think if you

lDataGrid.Bind();

then you will get the Count()

or check the Count on the AfterDataBinding Event.