【问题标题】:DataGrid DataBindings WinformsDataGrid 数据绑定 Winforms
【发布时间】:2018-01-01 15:59:52
【问题描述】:

DataGrid 数据绑定错误

class Test1
{
   public DataTable table1 = new DataTable();
   public BindingSource sr = new BindingSource();
}

class Test2
{

    Test1 ta =new Test1();

    DataTable table1 = new DataTable();
    table1.Columns.Add("Dosage", typeof(int));
    table1.Columns.Add("Drug", typeof(string));
    table1.Columns.Add("Patient", typeof(string));
    table1.Columns.Add("Date", typeof(DateTime));

    table1.Rows.Add(25, "Indocin", "David", DateTime.Now);
    table1.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
    table1.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
    table1.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
    table1.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);

    ta.table1 = table1 ;

   datagridview dgv = new datagridview();
   dgv.AutoGenerateColumns = true ;
   dgv.DataBindings.Add("DataSource",ta,"table1");
}

上面的代码给了我“无法绑定到 DataSource.Parameter 名称上的属性或列 table1:dataMember。” .我在这里犯了什么错误,我不明白。任何人都可以帮助我吗?

【问题讨论】:

  • 不要拨打DataGridViewa GridViewDataGrid,反之亦然!!这是错误且令人困惑的,因为它们是不同的控件。总是用正确的名字来称呼事物!

标签: c# winforms data-binding datagrid


【解决方案1】:

直接使用DataSource属性来绑定你的数据源

dgv.AutoGenerateColumns = false;
dgv.DataSource = ta.table1;

根据您发布的代码,您传递的对象数据源是错误的,它必须是 ta.table1 而不仅仅是 ta

   dgv.DataBindings.Clear();
   dgv.AutoGenerateColumns = false;
   dgv.DataBindings.Add("DataSource",ta.table1,"DataSource");

下面的行也改成

DataTable table1 = new DataTable("table1");

有关详细信息,请参阅 MSDN 文档https://msdn.microsoft.com/en-us/library/b6y3aby2(v=vs.110).aspx#Examples

【讨论】:

  • 我是使用数据绑定绑定数据源的情况。你能帮我找出 databindings.add() 方法的问题吗?
  • 在像上面那样改变之后,我得到了同样的错误。谢谢你的回复。
  • 将名称添加到表后也会发生相同的错误。DataTable table1 = new DataTable("table1");.
【解决方案2】:

或者,您总是可以创建一个对象列表并绑定该列表。使用您发布的参数(剂量、药物名称、患者名称和时间)创建一个“患者”类。然后创建对象并将它们添加到列表中,最后将 DGV 数据源设置为等于该列表。以下是一些可以帮助您的示例代码:

DataGridView dgvPatient = new DataGridView();      //Create DGV
List<Patient> patientList = new List<Patient>();   //Create list
//Create and populate your object patient
Patient p1 = new Patient(###, "DrugName", "PatientName", DateTime);
patientList.Add(p1);                              //Add to list

dgvPatient.DataSource = typeof(Patient);
dgvPatient.DataSource = patientList;              //Assign to DGV

这是一种不同的方法,但过去对我来说效果很好。希望这会有所帮助

【讨论】:

  • 嗨 Yahtzee 谢谢你的回复。根据你的建议,上面的建议对我有用。但是我需要使用 DataBindings.Add 方法绑定 DataGridView 的数据源属性,这对我不起作用。我不知道为什么它不起作用,我需要帮助。
猜你喜欢
  • 2013-03-18
  • 2014-12-05
  • 2011-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多