【问题标题】:Why is my binding failing?为什么我的绑定失败?
【发布时间】:2012-08-20 20:58:00
【问题描述】:

我收到“无法绑定到数据源上的属性或列”(在具有“”的行上附加评论):

List<QHQuad> listQH = PlatypusData.GetQHForPlatypusAndDay(platypusId, dow);
foreach (var quad in listQH)
{
    int QHCell = quad.QH;
    if ((QHCell >= 1) || (QHCell <= QUARTER_HOUR_COUNT))
    {
        string PH1CellToPopulate = string.Format("textBoxA_{0}", QHCell);
        string PH2CellToPopulate = string.Format("textBoxB_{0}", QHCell);
        string PH3CellToPopulate = string.Format("textBoxC_{0}", QHCell);
        var tb = (TextBox)this.Controls.Find(PH1CellToPopulate, true).First();
        tb.DataBindings.Add(new Binding("Text", quad, "Ph1")); // <-- here!
        tb = (TextBox)this.Controls.Find(PH2CellToPopulate, true).First();
        tb.DataBindings.Add(new Binding("Text", quad, "Ph2"));
        tb = (TextBox)this.Controls.Find(PH3CellToPopulate, true).First();
        tb.DataBindings.Add(new Binding("Text", quad, "Ph3")); 
    }
}

在故障点,quad 包含四个值:QHCell,即 1; Ph1,为空字符串; Ph2,为空字符串;和Ph3,即“1”

更新

我认为可见性不是问题,因为我可以访问 quad.QH;此外,该课程是公开的。

我得到的更完整的异常是“System.ArgumentException 未被用户代码消息处理=无法绑定到数据源上的属性或列 Ph1。 参数名称:dataMember"

如果我改变问题行:

tb.DataBindings.Add(new Binding("Text", quad, "Ph1"));

...到这个:

tb.DataBindings.Add(new Binding("Text", listQH, "quad.Ph1"));

我明白了,“无法创建字段 quad 的子列表”

更新 2

我认为这是因为我这样做的方式,绑定数据没有意义:

最初我的班级有 384 名成员,96 个这种“四边形”:

int
string
string
string

然后我将其更改为使用具有 4 个成员的类的 96 个实例(上面的那些 - “四元组”,即 QH、Ph1、Ph2 和 Ph3)。

因此,尝试绑定到这些瞬态类实例对我来说并不是很明智 - 我必须保留该类的 96 个实例。

我仍然可能是错的,但这就是我认为这里数据绑定失败的原因:我将我的代码优雅化为遗忘。

【问题讨论】:

  • 如果您收到带有文本“无法绑定...”的“ArgumentException”? #1 原因是“Ph1”不可访问。不公开或拼写相同或类似。对这些内容进行三重验证。

标签: c# winforms data-binding dynamic


【解决方案1】:

根据您对 sharp_net 的评论,数据绑定适用于属性,而不是字段。

从此改变你的班级:

public class QHQuad {
  public int QH;
  public string Ph1;
  public string Ph2;
  public string Ph3;
}

到这里:

public class QHQuad {
  public int QH {get; set;}
  public string Ph1 {get; set;}
  public string Ph2 {get; set;}
  public string Ph3 {get; set;}
}

您还应该考虑实现INotifyPropertyChanged 接口。

【讨论】:

    【解决方案2】:

    当我拼错列名时,我可以重现错误“ex.Message =“无法绑定到数据源上的属性或列 numpmt。\r\n参数名称:dataMember”。

    请验证您的列名是否正确。

    【讨论】:

    • 我不这么认为;这是类: public class QHQuad { public int QH;公共字符串 Ph1;公共字符串Ph2;公共字符串Ph3; }
    【解决方案3】:

    我收到此错误“无法绑定到数据源上的属性或列。 参数名称:dataMember。" -- 但仅在发布模式下运行时。

    可以在此处查找引发此错误的参考源: http://referencesource.microsoft.com/#System.Windows.Forms/ndp/fx/src/winforms/Managed/System/WinForms/BindToObject.cs.html,发生在 CheckBinding() 中。

    当数据源实际上为空时,我收到了错误,仅在发布模式下。 绑定源已经在设计器中创建,所以 MyForm.Designer.cs 某处说

    this.myBindingSource.DataSource = typeof(MyClass);
    

    和 MyForm.cs 某处说

    this.myBindingSource.DataSource = null;
    

    同样,错误仅在发布模式下发生,它不会停止能够继续的应用程序,除非用户在错误对话框中单击“退出”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-10
      • 2011-09-07
      • 1970-01-01
      相关资源
      最近更新 更多