데이터 바인딩시 예상대로 작동하도록 ComboBox를 가져 오는 데 문제가 있으며 문제가있는 곳을 잘 모릅니다.데이터 바운드 업데이트 후 데이터 바운드 업데이트 후에 ComboBox가 공백이 됨
아래 코드에서 ComboBox가 만들어지고 데이터 바인딩 된 값 목록이 제공되고 데이터가 폼에 바인딩됩니다. 아이디어는 ComboBox가 옵션 목록을 표시해야하며 하나를 선택하면 데이터 소스를 업데이트하고 상태 텍스트 상자에 표시해야한다는 것입니다.
이 모든 것은 제대로 작동하는 것으로 보입니다. 단, ComboBox가 값을 업데이트 한 후에는 아무 것도 이해할 수 없습니다.
"Selection"속성의 데이터 형식이 Int32에서 string으로 변경되면 예상대로 정확하게 작동합니다. 그러나 Int32처럼 값을 올바르게 설정하더라도 상자는 공백이됩니다.
이 문제를 해결하는 방법에 대한 도움을 주시면 감사하겠습니다.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ComboboxDatabindingTest
{
public partial class Form1 : Form
{
ComboBox _box;
TextBox _status;
ValuesDataSource _bsValues;
BindingSource _bsObject;
Binding _binding;
int _selection;
public Form1()
{
_selection = 0;
_bsValues = new ValuesDataSource();
_bsObject = new BindingSource();
_bsObject.DataSource = this;
_status = new TextBox();
_status.Left = 20;
_status.Top = 50;
_status.Width = 200;
_status.ReadOnly = true;
_box = new ComboBox();
_box.Name = "box";
_box.Left = 20;
_box.Top = 20;
_box.Width = 200;
_box.DropDownStyle = ComboBoxStyle.DropDownList;
_box.ValueMember = "CodeOrLabel";
_box.DisplayMember = "Label";
_box.DataSource = _bsValues;
_binding = _box.DataBindings.Add("SelectedValue", _bsObject, "Selection");
this.Controls.Add(_box);
this.Controls.Add(_status);
}
public int Selection
{
get { return _selection; }
set { _selection = value; _status.Text = value.ToString(); }
}
}
public class Value
{
private string _code = null;
private string _label = "";
public Value(string code, string label)
{
_code = code;
_label = label;
}
public string Code
{
get { return _code; }
}
public string Label
{
get { return _label; }
}
public string CodeOrLabel
{
get { return _code == null ? _label : _code; }
}
}
public class ValuesDataSource : BindingList<Value>
{
public ValuesDataSource()
{
base.Add(new Value("1", "California"));
base.Add(new Value("2", "Nevada"));
base.Add(new Value("3", "Arizona"));
base.Add(new Value("4", "Oregon"));
}
}
}
감사합니다. 유형 문제 여야한다는 것을 알고 있었지만 찾지 못했습니다. CodeOrLabel의 별칭을 CodeInt32로 만들고이를 ValueMember로 사용하여 해결했습니다. 다른 데이터 형식의 속성에 바인딩 할 때도 동일한 Value 개체를 사용할 수 있습니다. – Jeremy