Ran*_*ndy 1 c# data-binding textbox winforms entity-framework-6
I have a Windows Form with a number of Textboxes. I bind them to a DataSource as the Form Loads.
public partial class FormSettings : Form
{
private readonly DbContext _context = new DbContext();
public FormSettings()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
_context.OrderEntrySettings.Load();
SettingsBindingSource.DataSource = _context.OrderEntrySettings.Local.ToBindingList();
Binding saNbinding = new Binding("Text", SettingsBindingSource, "InvoiceNumber");
InvoiceNumberTextBox.DataBindings.Add(saNbinding);
Binding pthNbinding = new Binding("Text", SettingsBindingSource, "SalesOrderExportPath");
PathTextBox.DataBindings.Add(pthNbinding);
<snip>
…
</snip>
}
Run Code Online (Sandbox Code Playgroud)
One of the Textboxes is bound to a Directory Path (string) Property. If I type in a new directory in the Path Textbox and hit my save button, The path saves just fine.
But, If I change the Text Property on the Textbox to the SelectedPath from a FolderBrowserDialog dialog and then hit save, the Textbox Text shows the directory I selected but the Entity is not modified and nothing gets saved back to the database.
As a workaround, I set both the Path Textbox Text and set the Property from the context to the SelectedPath.
Why does a Bound Textbox not modify its associated property if the Text value is set programmatically?
这是原因。结合类有一个叫做财产DataSourceUpdateMode有3个选择- Never,OnPropertyChanged并且OnValidation,在最后的是一个默认值。以Text编程方式设置属性时,没有验证/验证事件,因为它们仅在控件处于焦点并已被编辑时才触发,因此绑定不会更新数据源。
话虽这么说,以下是您可以选择的选项:
(A)不要以编程方式设置控件属性,而是设置数据源属性。
(B)将绑定更改DataSourceUpdateMode为OnPropertyChanged。但是,这将导致在用户键入的每个字符上更新数据源属性。
(C)使用以下代码段:
yourTextBox.Text = ...;
yourTextBox.DataBindings["Text"].WriteValue();
Run Code Online (Sandbox Code Playgroud)