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

时间:2012-11-20 08:36:57

标签: 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'的定义,并且没有扩展方法'VendorID'接受类型'Objects.Product'的第一个参数可以找到(你错过了吗?使用指令或程序集引用?)

2 个答案:

答案 0 :(得分:1)

如果要访问子类的属性,则需要将其强制转换为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;  
}

答案 1 :(得分:0)

您可以执行以下操作:

if (productNo == this.product1.ProductNumber)  //ProductNumber comes from Product class
{
        tbDescription.Text = product1.ProductDescription; 
        tbOnHand.Text = product1.NumberOnHand.ToString(); 
        tbUnitOfMeasure.Text = product1.UnitOfMeasure;    
        if(priduct1 is ManufacturedProduct)
               tbVendorID.Text = ((ManufacturedProduct)product1).VendorID.ToString(); 
}