我有以下代码:
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;
使用在表单构造函数中执行的代码,用数据表中的列填充lGrid。但是,当我将它移动到控件构造函数时,绑定不起作用,并且i = 0.为什么会这样,我该怎么办呢?
行。构造函数是最简单的
公共部分类Form1:表单 {
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);
}
}
答案 0 :(得分:1)
使用think if you
lDataGrid.Bind();
然后你会得到Count()
或检查AfterDataBinding事件上的Count。