从另一个类调用方法会抛出System.NullReferenceException

时间:2018-04-07 08:06:37

标签: c# asp.net

我有这个代码,意味着向用户发送生成错误的电子邮件通知,因此我在主页面中创建了一个标签,用户希望在访问该页面时收到通知,然后标签文本将更改为通知状态。所以我创建了标签并创建了一个方法,将标签文本值更改为我需要显示的错误消息。当我在同一个类中调用该方法时,它工作正常,但是当我从另一个类调用它时,它会抛出" System.NullReferenceException:对象引用未设置为对象的实例。"错误。

这是通知类:

using OICEVENTS.home;
using System;
using System.Net.Mail;

namespace OICEVENTS.inc.func
{
    public class Notify
    {
        public void EmailNotify()
        {
            string _fromMail = "111@111.com";
            string _toMail = "111@111.com";
            string _subjectMail = "Test mail notification";
            string _bodyMail = "test message";
            string _smtpHost = "111.com";
            string _smtpPwd = "111";
            string _smtpUsr = "111";
            int _smtpPort = 25;
            bool _smtpSSL = true;
            bool _smtpHTML = true;

            SmtpClient smtpClient = new SmtpClient(_smtpHost, _smtpPort);

            smtpClient.Credentials = new System.Net.NetworkCredential(_smtpUsr, _smtpPwd);
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtpClient.EnableSsl = _smtpSSL;

            MailMessage mailMessage = new MailMessage(_fromMail, _toMail);
            mailMessage.Subject = _subjectMail;
            mailMessage.Body = _bodyMail;
            mailMessage.IsBodyHtml = _smtpHTML;

            evpg _evpg = new evpg();
            try
            {
                smtpClient.Send(mailMessage);
                _evpg.lblMsg("Message Successfuly Sent ..."); //I always get the error here
            }
            catch (Exception ex)
            {
                _evpg.lblMsg(ex.ToString()); //and here
            }
        }
    }
}

这里是我从另一个类调用该方法并为其分配一些文本的地方:

using OICEVENTS.inc.func;
using System;

namespace OICEVENTS.home
{
    public partial class evpg : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ////initiate data access class
            DbAccess DbAccess = new DbAccess();

            //Fill repeater
            evRepList.DataSource = DbAccess.GetLatestEventsList();
            evRepList.DataBind();

            Notify _sendNotification = new Notify();
            _sendNotification.EmailNotify();
        }

        public void lblMsg(string _msg)
        {
            if(!String.IsNullOrWhiteSpace(_msg))
            {
                evFrmMsg.Text = _msg ;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我认为您收到了NullReferenceException,因为evFrmMsg未实例化,请尝试将您的方法更改为:

public void lblMsg(string _msg)
{
    Label evFrmMsg = new Label();
    if(!String.IsNullOrWhiteSpace(_msg))
    {
        evFrmMsg.Text = _msg ;
    }
    ControlContainingLabel.Controls.Add(evFrmMsg);
}

ControlContainingLabel是包含您的标签的控件。