44
public class ComboboxItem { 
            public string Text { get; set; } 
            public string Value { get; set; }
            public override string ToString() { return Text; } 
        }

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int selectedIndex = comboBox1.SelectedIndex;
            int selecteVal = (int)comboBox1.SelectedValue; 
            ComboboxItem selectedCar = (ComboboxItem)comboBox1.SelectedItem;
            MessageBox.Show(String.Format("Index: [{0}] CarName={1}; Value={2}", selectedIndex, selectedCar.Text, selecteVal));
        }

私はそれらを次のように追加しています:

ComboboxItem item = new ComboboxItem();
                    item.Text = cd.Name;
                    item.Value = cd.ID;
                    this.comboBox1.Items.Add(item);

NullReferenceExeption が発生し続けますが、その理由がわかりません。テキストは問題なく表示されるようです。

4

7 に答える 7

48

これを試して:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    ComboBox cmb = (ComboBox)sender;
    int selectedIndex = cmb.SelectedIndex;
    int selectedValue = (int)cmb.SelectedValue;

    ComboboxItem selectedCar = (ComboboxItem)cmb.SelectedItem;
    MessageBox.Show(String.Format("Index: [{0}] CarName={1}; Value={2}", selectedIndex, selectedCar.Text, selecteVal));        
}
于 2011-08-01T16:00:32.347 に答える
15

nullNullReferenceExeptionの を使用しているため、取得しています。cmb.SelectedValueカスタムクラスのcomboBox値がわからないComboboxItemので、次のいずれかを行います。

ComboboxItem selectedCar = (ComboboxItem)comboBox2.SelectedItem;
int selecteVal = Convert.ToInt32(selectedCar.Value);

または、次のようなデータバインディングを使用することをお勧めします。

ComboboxItem item1 = new ComboboxItem();
item1.Text = "test";
item1.Value = "123";

ComboboxItem item2 = new ComboboxItem();
item2.Text = "test2";
item2.Value = "456";

List<ComboboxItem> items = new List<ComboboxItem> { item1, item2 };

this.comboBox1.DisplayMember = "Text";
this.comboBox1.ValueMember = "Value";
this.comboBox1.DataSource = items;
于 2011-08-01T16:24:44.517 に答える
6

同様のエラーが発生しました。私のクラスは

public class ServerInfo
{
    public string Text { get; set; }
    public string Value { get; set; }
    public string PortNo { get; set; }

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

しかし、私がしたことは、自分のクラスを ComboBox の SelectedItem プロパティにキャストしたことです。したがって、選択した項目のすべてのクラス プロパティを取得します。

// Code above
ServerInfo emailServer = (ServerInfo)cbServerName.SelectedItem;

mailClient.ServerName = emailServer.Value;
mailClient.ServerPort = emailServer.PortNo;

これが誰かに役立つことを願っています!乾杯!

于 2014-02-13T21:22:37.387 に答える
0

これを試して:

private void cmbLineColor_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataRowView drv = (DataRowView)cmbLineColor.SelectedItem;
        int selectedValue = (int)drv.Row.ItemArray[1];
    }
于 2015-05-19T11:12:59.537 に答える