【问题标题】:c# binding datagridview to datatable in form vs controlc#将datagridview绑定到表单vs控件中的数据表
【发布时间】:2011-07-03 05:59:00
【问题描述】:

我有以下代码:

        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。为什么会这样,我该怎么办?

更新1

好的。构造函数是最简单的

公共部分类 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);
    }
}

【问题讨论】:

  • 这是 Winforms/WPF/ASP.NET 吗?
  • 你能把问题出现的两个构造函数贴出来吗?
  • @Robbie 这是winforms

标签: c# binding datagridview datatable bindingsource


【解决方案1】:

如果你想,就用想想

lDataGrid.Bind();

然后你会得到 Count()

或检查 AfterDataBinding 事件的计数。

【讨论】:

  • datagridview 似乎没有 Bind 方法,但在 DataBindingComplete 事件中检查计数确实有效,谢谢。谁能解释一下为什么它不像形式上那样立即绑定?
  • 原因是因为您在 MyControl 类而不是在表单控件上调用代码。如果我正确,您的应用程序启动实际上还没有绑定。有人可能会比我更好地解释这一点。如果您实际上在 IntitializeComponent() 调用中将控件作为表单的一部分,那么您将直接获得绑定。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-12
  • 2011-04-02
  • 1970-01-01
  • 2013-02-06
  • 2010-12-20
相关资源
最近更新 更多