c# - 如何使用派生类的值填充文本框? C#

标签 c#

在我的表单中,我有以下...

if (productNo == this.product1.ProductNumber)  //ProductNumber comes from Product class
                {
                    //if so, set the other values of the text boxes to that of the 
                    //product in memory
                    tbDescription.Text = product1.ProductDescription; //Works - from Product class
                    tbOnHand.Text = product1.NumberOnHand.ToString(); //Works - from Product class
                    tbUnitOfMeasure.Text = product1.UnitOfMeasure;    //Works - from Product class

                    tbVendorID.Text = product1.VendorID; // Doesn't work - from derived ManufacturedProduct class 
                }

其中 VendorID 来自 ManufacturedProduct 类,它是来自 Product 的派生类。最后一行代码不起作用。我希望能够用 product1.VendorID 中的值填充 tbVendorID(顺便说一句,它是一个 int)

我收到以下错误...Objects.Product' 不包含 'VendorID' 的定义,并且找不到接受类型为 'Objects.Product' 的第一个参数的扩展方法 'VendorID'(您是否缺少使用指令或程序集引用?)

最佳答案

如果您想访问子类的属性,您需要将其转换为 ManufacturedProduct:

ManufacturedProduct mfgProduct = (ManufacturedProduct) product1;
if (productNo == mfgProduct.ProductNumber)  
{
    tbDescription.Text = mfgProduct.ProductDescription;  
    tbOnHand.Text = mfgProduct.NumberOnHand.ToString();  
    tbUnitOfMeasure.Text = mfgProduct.UnitOfMeasure;    
    tbVendorID.Text = mfgProduct.VendorID;  
}

关于c# - 如何使用派生类的值填充文本框? C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13469293/

相关文章:

C# 如何获得其他批处理文件的输出?

c# - SOAPUI 未显示来自 WSDL 的操作

c# - 如何避免包含文件的完整路径

c# - 如何判断用户何时在您的控制范围之外单击?

c# - ActiveX 控件 '6bf52a52-394a-11d3-b153-00c04f79faa6' 无法实例化,因为当前线程不在单线程单元中

c# - 如何在 Entity Framework 中查询名字和姓氏?

c# - 如何从多线程访问 GUI (GTK)?

c# - 与 SMSS 相比,从 ADO.NET 执行具有相同查询计划的相同查询需要大约 10 倍的时间

c# - EF映射一对一可选

c# - 为什么 ConcurrentDictionary.GetOrAdd(key, valueFactory) 允许 valueFactory 被调用两次?