简体   繁体   English

对象引用未设置为C#winform devexpress中的对象错误实例?

[英]Object reference not set to an instance of an object error in C# winform devexpress?

I have Gridview in my Form, If i click button on the Gridview I get Column value of Focused Row and Try to use that Value in next Form. 我的窗体中有Gridview,如果单击Gridview上的按钮,我将获得Focused Row的Column值,并尝试在下一个Form中使用该值。 But in that new form error shown like this 但是以这种新形式出现的错误如下

 public partial class New_Invoice : DevExpress.XtraEditors.XtraForm
{

    string getOper = "A";

    public New_Invoice()
    {
        InitializeComponent();
    }

    public New_Invoice(string oper, int invoiceno)
    {
        // TODO: Complete member initialization

        textEdit5.Text = invoiceno.ToString(); // error shown in this line
        textEdit5.Visible = false;
        getOper = oper;
    }  

What was wrong in my code ? 我的代码出了什么问题?

In your custom constructor you aren't calling InitializeComponent() . 在您的自定义构造函数中,您不会调用InitializeComponent() This is critical: this is what creates the controls. 这很关键:这就是创建控件的原因。 A simple fix might be to chain the constructor (see the : this() ): 一个简单的解决方法可能是链接构造函数(请参阅: this() ):

public New_Invoice(string oper, int invoiceno) : this()
{
    textEdit5.Text = invoiceno.ToString(); // error shown in this line
    textEdit5.Visible = false;
    getOper = oper;
} 

However, personally I would advise against adding custom constructors to forms / controls, and instead use properties / methods on the newly created instance, so the caller does something like: 但是,就我个人而言,我建议不要将自定义构造函数添加到窗体/控件中,而应在新创建的实例上使用属性/方法,因此调用者应执行以下操作:

using(var form = new NewInvoice())
{
    form.Operation = ...;     // (or maybe form.SetInvoiceNumber(...) if the
    form.InvoiceNumber = ...; // logic is non-trivial)
    // show the form, etc
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM