c# binding datagridview to datatable in form vs control

别说谁变了你拦得住时间么 提交于 2020-01-24 15:30:16

问题


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.



来源:https://stackoverflow.com/questions/5099673/c-sharp-binding-datagridview-to-datatable-in-form-vs-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!