【问题标题】:.NET get BindingSource value from Control.NET 从 Control 获取 BindingSource 值
【发布时间】:2021-09-24 06:28:28
【问题描述】:

我在表格布局上有一些控件,每个控件都有一个绑定值(来自 DataTable 并与 BindingSource 绑定)。我的应用程序在交互后隐藏了一些控件,如果绑定的控件不可见,我希望每个隐藏控件的值设置为 nullDBNull.Value

基本上我有一个循环遍历我的表格布局中的所有控件。

foreach (System.Windows.Forms.Control c in tablelayout.Controls)
{
    if (c.Visible == false && c.DataBindings.Count > 0)
    {
        Binding binding = c.DataBindings[0]; // only one binding per control
        // here I would do something like (object)binding.Value = null; 
    }
}

这可能吗?我最后的解决方案是手动更改我变得不可见的每个控件的值...

【问题讨论】:

  • 您应该检查 Binding 的 FormatParse 事件。 -- 请注意,每次引发这些事件时,sender 对象就是绑定。它的Control 属性引用了绑定的控件。您可以验证控件的Visible 状态,然后根据此状态设置或返回一个值。
  • 这些事件通常用于您所描述的内容,以处理需要特殊格式的值或解析数据源或控件不直接支持的值(例如 Null / DBNull应用于 DateTimePicker 的值)。
  • 我找到了一种方法:在 foreach 中我设置了c.Text = null,然后我调用了bindingSource.EndEdit(),这会强制重新绘制绑定。这行得通。

标签: c# .net winforms ado.net


【解决方案1】:

我的解决方案:

foreach (System.Windows.Forms.Control c in tablelayout.Controls)
{
    if (c.Visible == false && c.DataBindings.Count > 0)
    {
        c.Text = null; // sets the Text to null
        bindingSource.EndEdit(); // redraws the BindingSource, so its committing the new value
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多