[C#] ComboBox : 항목에 텍스트 및 값 추가 (바인딩 소스 없음)

C # WinApp에서 ComboBox의 항목에 텍스트와 값을 모두 추가하려면 어떻게해야합니까? 검색을 수행 한 결과 대개 “소스에 바인딩”을 사용하고 있습니다.하지만 제 경우에는 제 프로그램에 바인딩 소스가 준비되어 있지 않습니다. 어떻게하면 다음과 같은 작업을 수행 할 수 있습니까?

combo1.Item[1] = "DisplayText";
combo1.Item[1].Value = "useful Value"



답변

원하는 텍스트를 반환하려면 고유 한 클래스 유형을 만들고 ToString () 메서드를 재정의해야합니다. 사용할 수있는 간단한 클래스 예는 다음과 같습니다.

public class ComboboxItem
{
    public string Text { get; set; }
    public object Value { get; set; }

    public override string ToString()
    {
        return Text;
    }
}

다음은 사용법의 간단한 예입니다.

private void Test()
{
    ComboboxItem item = new ComboboxItem();
    item.Text = "Item text1";
    item.Value = 12;

    comboBox1.Items.Add(item);

    comboBox1.SelectedIndex = 0;

    MessageBox.Show((comboBox1.SelectedItem as ComboboxItem).Value.ToString());
}


답변

// Bind combobox to dictionary
Dictionary<string, string>test = new Dictionary<string, string>();
        test.Add("1", "dfdfdf");
        test.Add("2", "dfdfdf");
        test.Add("3", "dfdfdf");
        comboBox1.DataSource = new BindingSource(test, null);
        comboBox1.DisplayMember = "Value";
        comboBox1.ValueMember = "Key";

// Get combobox selection (in handler)
string value = ((KeyValuePair<string, string>)comboBox1.SelectedItem).Value;


답변

다음과 같이 익명 클래스를 사용할 수 있습니다.

comboBox.DisplayMember = "Text";
comboBox.ValueMember = "Value";

comboBox.Items.Add(new { Text = "report A", Value = "reportA" });
comboBox.Items.Add(new { Text = "report B", Value = "reportB" });
comboBox.Items.Add(new { Text = "report C", Value = "reportC" });
comboBox.Items.Add(new { Text = "report D", Value = "reportD" });
comboBox.Items.Add(new { Text = "report E", Value = "reportE" });

업데이트 : 위의 코드가 제대로 콤보 상자에 표시되지만, 당신은 사용할 수 없습니다 SelectedValue또는 SelectedText속성 ComboBox. 이를 사용하려면 콤보 상자를 다음과 같이 바인딩하십시오.

comboBox.DisplayMember = "Text";
comboBox.ValueMember = "Value";

var items = new[] {
    new { Text = "report A", Value = "reportA" },
    new { Text = "report B", Value = "reportB" },
    new { Text = "report C", Value = "reportC" },
    new { Text = "report D", Value = "reportD" },
    new { Text = "report E", Value = "reportE" }
};

comboBox.DataSource = items;


답변

dynamic런타임에 콤보 박스 항목을 해결 하려면 객체를 사용해야 합니다.

comboBox.DisplayMember = "Text";
comboBox.ValueMember = "Value";

comboBox.Items.Add(new { Text = "Text", Value = "Value" });

(comboBox.SelectedItem as dynamic).Value


답변

Dictionary텍스트와 값을 추가하기 위해 사용자 정의 클래스를 만드는 대신 Object를 사용할 수 있습니다 .Combobox .

Dictionary객체 에 키와 값을 추가하십시오 .

Dictionary<string, string> comboSource = new Dictionary<string, string>();
comboSource.Add("1", "Sunday");
comboSource.Add("2", "Monday");

소스 사전 오브젝트를 Combobox다음에 바인딩하십시오 .

comboBox1.DataSource = new BindingSource(comboSource, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";

키 및 값 검색 :

string key = ((KeyValuePair<string,string>)comboBox1.SelectedItem).Key;
string value = ((KeyValuePair<string,string>)comboBox1.SelectedItem).Value;

전체 소스 : Combobox Text nd Value


답변

이것은 방금 떠오른 방법 중 하나입니다.

combo1.Items.Add(new ListItem("Text", "Value"))

그리고 항목의 텍스트 또는 값을 변경하려면 다음과 같이 할 수 있습니다.

combo1.Items[0].Text = 'new Text';

combo1.Items[0].Value = 'new Value';

Windows Forms 에는 ListItem이라는 클래스가 없습니다 . ASP.NET 에만 존재 하므로 @Adam Markowitz가 대답 에서했던 것과 같이 사용하기 전에 자신의 클래스를 작성해야합니다 .

이 페이지를 확인하면 도움이 될 수 있습니다.


답변

이것이 원래 게시물에 주어진 상황에서 효과가 있는지 알지 못하지만 (이것이 2 년 후라는 사실을 염두에 두지 마십시오),이 예제는 저에게 효과적입니다.

Hashtable htImageTypes = new Hashtable();
htImageTypes.Add("JPEG", "*.jpg");
htImageTypes.Add("GIF", "*.gif");
htImageTypes.Add("BMP", "*.bmp");

foreach (DictionaryEntry ImageType in htImageTypes)
{
    cmbImageType.Items.Add(ImageType);
}
cmbImageType.DisplayMember = "key";
cmbImageType.ValueMember = "value";

값을 다시 읽으려면 SelectedItem 속성을 DictionaryEntry 개체로 캐스팅 한 다음 해당 Key 및 Value 속성을 평가해야합니다. 예를 들어 :

DictionaryEntry deImgType = (DictionaryEntry)cmbImageType.SelectedItem;
MessageBox.Show(deImgType.Key + ": " + deImgType.Value);