ComboBox.SelectedValue 抛出空引用异常 [英] ComboBox.SelectedValue throws null reference exception

查看:21
本文介绍了ComboBox.SelectedValue 抛出空引用异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我整理了以下代码来演示我遇到的问题.

I've put together the following code to demonstrate a problem I'm having.

这是一个只有一个组合框的表单,它使用加载方法中从 LINQ 生成的数组进行填充.

It's a form with just a combobox, which is populated using an array generated from LINQ in the load method.

它设置了 DisplayMember 和 ValueMember.显示成员按预期工作 - 它显示数字列表.但是,正如所评论的,SelectedValue 为空.

It's got DisplayMember and ValueMember set. Display member works as expected - it displays a list of numbers. However, as commented, SelectedValue is null.

private void Form1_Load(object sender, EventArgs e)
{
    comboBox1.DisplayMember = "Number";
    comboBox1.ValueMember = "Square";

    var it = from n in new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
             select new NumberAndSquare(n);
    comboBox1.Items.AddRange(it.ToArray());
}

private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
{
    ComboBox combo = sender as ComboBox;
    MessageBox.Show(combo.SelectedItem.ToString());  //works as expected
    MessageBox.Show(combo.SelectedValue.ToString()); //throws null reference exception
}

class NumberAndSquare
{
    public NumberAndSquare(int number)
    {
        Number = number;
    }

    public int Number
    { get; set; }
    public int Square
    {
        get
        {
            return Number*Number;
        }
    }

    public override String ToString()
    {
        return string.Format("{0}: {1}", Number, Square);
    }
}

我做错了什么?

推荐答案

SelectedValue 在这种情况下无疑是 null 因为没有任何东西被绑定 到它.AFAIK DataMember/ValueMember 属性仅在您将 DataSource 绑定到组合框(您不是)时使用.例如,如果您将代码更改为:

SelectedValue is no doubt null in this scenario because there is nothing being bound to it. AFAIK the DataMember/ValueMember properties are used only when you bind a DataSource to your combobox (which you aren't). For example, if you changed your code to:

var it = from n in new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
         select new NumberAndSquare(n);
comboBox1.DataSource = it.ToList();
comboBox1.DisplayMember = "Number";
comboBox1.ValueMember = "Square";

应该可以

这篇关于ComboBox.SelectedValue 抛出空引用异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆