标签超出其他控件时TextBox重置文本

时间:2012-08-22 19:51:47

标签: winforms .net-3.5 c#-3.0

我有一个包含多个控件的表单。有一个情况,'textBoxOtherRelationship'被禁用,文本被设置为string.empty。但是当我接着另一个控件并标签出来时,数据再次出现,而控件仍然被禁用。

textBoxOtherRelationship.DataBindings.Add(new Binding("Text", _binder, "RelationshipNotes"));


  private void ComboBoxRelationShipSelectedValueChanged(object sender, EventArgs e)
        {
            if ((Constants.Relationship)comboBoxRelationShip.SelectedItem.DataValue == Constants.Relationship.Other)
            {
                textBoxOtherRelationship.Enabled = true;
                if (_formMode != ActionMode.ReadOnly)
                {
                    textBoxFirstName.BackColor = Color.White;
                }
            }
            else
            {
                textBoxOtherRelationship.Enabled = false;
                _model.RelationshipNotes = null;
                textBoxOtherRelationship.Text = string.Empty;
                if (_formMode != ActionMode.ReadOnly)
                {
                    textBoxFirstName.BackColor = Color.LightYellow;
                }
            }
        }

2 个答案:

答案 0 :(得分:1)

嗯..所以我在这里看到这一行:

textBoxOtherRelationship.DataBindings.Add(
  new Binding("Text", _binder, "RelationshipNotes"));

告诉我你在textBoxOtherRelationship上的Text属性和数据源_binder上名为“RelationshipNotes”的属性之间建立了绑定。

所以,我假设双向绑定工作得很好,当你在textBoxOtherRelationship中键入内容并且该控件失去焦点时,底层的RelationshipNotes属性也会更新,对吧?

现在,查看那里的代码,我认为在将Text属性设置为string.Empty时不会更新基础数据源,因为通常在文本框失去焦点之前不会发生你已经禁用了控件。

如果你添加:

textBoxOtherRelationship.DataBindings[0].WriteValue();

将值设置为string.Empty之后,string.Empty值将存储回数据源,因为数据绑定将知道有更新的内容。以编程方式,它没有。

我看到你有这条线:

            textBoxOtherRelationship.Enabled = false;
            _model.RelationshipNotes = null; <<<----------------------
            textBoxOtherRelationship.Text = string.Empty;

_model.RelationshipNotes最终应该绑定到该文本框的内容是什么?

答案 1 :(得分:1)

在控件失去焦点之前,SelectedIndexChanged事件不提交数据绑定,因此快速解决方法是在事件中首先写入值:

private void ComboBoxRelationShipSelectedValueChanged(object sender, EventArgs e)
{
  if (comboBoxRelationShip.DataBindings.Count > 0) {
    comboBoxRelationShip.DataBindings[0].WriteValue();

    if ((Constants.Relationship)comboBoxRelationShip.SelectedItem.DataValue ==
                                                 Constants.Relationship.Other) {
      textBoxOtherRelationship.Enabled = true;
      if (_formMode != ActionMode.ReadOnly) {
        textBoxFirstName.BackColor = Color.White;
      }
    } else {
      textBoxOtherRelationship.Enabled = false;
      _model.RelationshipNotes = null;
      textBoxOtherRelationship.Text = string.Empty;
      if (_formMode != ActionMode.ReadOnly) {
        textBoxFirstName.BackColor = Color.LightYellow;
      }
    }
  }
}