0

我在另一个类中访问了一个数据源。我使用此数据源在页面加载事件中填充我的组合框。我已经到了我的方法从 selectedindexchanged 事件访问数据库的地步。它给了我错误:对象引用未设置为对象的实例。我使用断点来查看失败的地方。令我惊讶的是,它正在收集第一行数据(不是我选择的数据),然后它越过断点并给我错误消息。为什么要这样做,因为它之前就有数据?我的组合框填充方法

try
        {
            List<PreviousVersionData> listID = PreviousVersionData.getDatabase();
            if (listID != null)
            {
                foreach (PreviousVersionData l in listID)
                {
                    cmboBoxPreviousVersion.Items.Add(l.FormatID.ToString() + " - " + l.FormatName);

                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

这就是问题所在,它给了我在 Item.FormatID = data.FormatID; 上设置的断点的错误。

if (cmboBoxPreviousVersion.SelectedItem != null)
        {
            PreviousVersionData data = new PreviousVersionData();

            PreviousVersionData pvdata = new PreviousVersionData();
            data = pvdata.getDataByID(cmboBoxPreviousVersion.SelectedItem.ToString());

            Item.FormatID = data.FormatID;
            Item.FormatName = data.FormatName;
            Item.FormatDescription = data.FormatDescription;
            Item.StockID = data.StockID;
            Item.PrintPlantCode = (bool)data.PrintPlantCode;
            Item.PrintWeight = (bool)data.PrintWeight;
            Item.PrintPrice = (bool)data.PrintPrice;

            rChkBoxPlantCode.Checked = Item.PrintPlantCode;
            rChkBoxPrintPrice.Checked = Item.PrintPrice;
            rChkBoxWeight.Checked = Item.PrintWeight;
            cmboBoxStock.Items.Add(Item.StockID);
            rTxtBoxDescription.Text = Item.FormatDescription;
        }

我是使用类进行数据库访问的新手,我总是使用向导进行教学。有没有更好的方法将该信息输入我的字段,或者我只是在某处遗漏了什么?谢谢您的帮助。如果您需要澄清,请告诉我!

4

1 回答 1

1

FormatID如果在这里,您将收到此错误null。该ToString()方法无法针对null引用执行。

cmboBoxPreviousVersion.Items.Add(l.FormatID.ToString() + " - " + l.FormatName);

无论如何,这可能不是您想要的,而是为了保护代码:

cmboBoxPreviousVersion.Items.Add(
    string.Format("{0} - {1}", l.FormatID, l.FormatName));

但是,您还需要研究为什么FormatIDnull在这里。

于 2013-11-04T16:32:11.550 回答