DataReader对象引用未设置错误

本文关键字:错误 设置 对象引用 DataReader | 更新日期: 2023-09-27 18:16:45

我做了一个自动发送一些文件的应用程序。现在的问题是,我在另一个数据库(sdf-file)中有电子邮件地址。

我想搜索"filenaam"的值,它可以是类似"q1869"的值。该变量必须在数据库(automail.sdf)中搜索。当里面有"q1869"的时候。然后在第二个字段中获取该行的值,在我的例子中是"email"。

现在我尝试了很多东西。但是我现在碰到了一个问题。

当我运行这段代码时,我在string emailaddress = getemail.ExecuteScalar().ToString();

处得到一个"对象引用未设置为对象的实例"错误。
        System.Windows.Forms.Timer mytimer = new System.Windows.Forms.Timer();
    //Automail mail = new Automail();

    public Form1()
    {
        InitializeComponent();
        //timer aanmaken, interval instellen en aanzetten + gegevens in datatable laden
        mytimer.Tick +=mytimer_Tick;
        mytimer.Interval = 10000;
        Methods methods = new Methods();
        Populate();

    }

    public OdbcConnection con = new OdbcConnection("Driver={iSeries Access ODBC Driver};uid=AYISHB;system=NLPROD;dbq=MMASHB MMASHB;dftpkglib=QGPL;languageid=ENU;pkg=QGPL/DEFAULT(IBM),2,0,1,0,512;qrystglmt=-1;signon=1;trace=2");
    public iDB2Connection conn = new iDB2Connection("DataSource=NLPROD;UserID=AYISHB;Password=AYI;DataCompression=True;Default Collection=mmashb;");
    public SqlCeConnection dbcon = new SqlCeConnection(@"Data Source=E:'Users'Ali'Documents'automail.sdf");
    SmtpClient SmtpServer = new SmtpClient("smtp.dsv.com"); // smtp client maken
    int aantalmails = 0;

    public DataTable dt = new DataTable();
    ///////////////////////////methodes//////////////////////////
    //Vul dataGridView1 methode
    public void Populate()
    {
        dt.Clear();
        OdbcCommand cm = new OdbcCommand("SELECT * FROM SELECTIE ORDER BY OMSCH",con); //querycommand om gegevens te openen
        OdbcDataAdapter da = new OdbcDataAdapter();
        da.SelectCommand = cm; // data adapter command aanmaken

        da.Fill(dt); // datatable vullen met de data


    }

   public void sendMail()
    {
        while (true)
        {
            Populate();
            if (dt.Rows.Count >= 1)
            {
                for (int x = dt.Rows.Count - 1; x >= 0; --x)
                {

                    int i = x; //i is aantal rijen
                    int r = 1;
                    string query = dt.Rows[i][r].ToString();// zet de querynummer om in een string
                    string filenaam = query.Trim(); // haal de overtollige spaties uit de naam en filenaam is de querynmr

                    SqlCeCommand getemail = new SqlCeCommand("SELECT email" + " FROM Emails" + " WHERE (query LIKE @querynaam)" , dbcon);
                    getemail.Parameters.AddWithValue("@querynaam", filenaam);
                    string emailaddress = getemail.ExecuteScalar().ToString();

                    MessageBox.Show(emailaddress);

                        //try
                        //{

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



                    System.Diagnostics.Process.Start(@"M:'dtf'" + filenaam + ".dtf"); // start de dtf bestand met de zelfde querynaam op de M schijf

                    Thread.Sleep(15000); // wacht 15 seconden
                    try
                    {
                        MailMessage mail = new MailMessage();//

                        mail.From = new MailAddress("ali.yilmaz@nl.dsv.com");
                        mail.To.Add(emailaddress.ToString());
                        mail.Subject = "Report " + filenaam + " DSV REPORT";
                        mail.Body = "Dear Customer,'nthis message is an automated mail sent by an unattended server. 'nThe attachment included in this mail is: " + filenaam + "'nPlease do not reply to this email 'n 'nThis mail has been sent on " + string.Format("{0:HH:mm:ss:tt yyyy-MM-dd}", DateTime.Now);
                        System.Net.Mail.Attachment attachment;
                        attachment = new System.Net.Mail.Attachment(@"M:/" + filenaam + ".xls");
                        mail.Attachments.Add(attachment);
                        SmtpServer.Credentials = new System.Net.NetworkCredential("ali.yilmaz@nl.dsv.com", "Uran1234");
                        SmtpServer.Send(mail);
                        mail.Dispose();

                        Thread.Sleep(10000);
                        string sourcefile = @"M:'" + filenaam + ".xls";
                        string destinationfile = @"M:'verzondenreports'" + filenaam + ".xls";

                        if (System.IO.File.Exists(@"M:'verzondenreports'" + filenaam + ".xls"))
                        {
                            System.IO.File.Delete(@"M:'verzondenreports'" + filenaam + ".xls");
                            System.IO.File.Move(sourcefile, destinationfile);
                        }
                        else
                        {
                            System.IO.File.Move(sourcefile, destinationfile);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);

                    }
                    Thread.Sleep(2000);
                    try
                    {
                        iDB2DataAdapter data = new iDB2DataAdapter("SELECT FROM SELECTIE ORDER BY OMSCH", conn);
                        data.DeleteCommand = new iDB2Command("DELETE FROM SELECTIE WHERE" + filenaam, conn);
                        data.DeleteCommand.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    if (dt.Rows.Count > 0)
                    {
                        dt.Rows[i].Delete();
                    }
                    else
                    {
                        return;
                    }
                    dt.AcceptChanges();
                    filenaam = "";


                }
                dt.Clear();


            }
            else
            {
                dt.Clear();
                Populate();
            }
        }
    }
    ///////////////////////////methodes//////////////////////////
    //wanneer form word opgestart
    private void Form1_Shown(object sender, EventArgs e)
    {
        try
        {
            //open connecties
            con.Open();
            conn.Open();
            dbcon.Open();
            //vul de tabel met de gegevens
            Populate();

        }
        catch(iDB2Exception ex)
        {
            // als connectie niet lukt weergeef foutmelding
            MessageBox.Show(ex.Message);

        }

    }
    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
    }
    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        con.Close();
        conn.Close();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        label2.Text = ("Running...");
        mytimer.Enabled = true;

        Thread t = GetT();
        t.Start();

        //Populate();
        //if (dataGridView1.Rows.Count > 1)
        //{
        //    int count = dataGridView1.Rows.Count;
        //    for (int x = 0; x <= dataGridView1.Rows.Count; x++)
        //    {
        //        int i = 0;
        //        int r = 1;
        //        string number = dataGridView1.Rows[i].Cells[r].Value.ToString();
        //        string filenaam = number.Trim();
        //        textBox1.Text = filenaam;
        //        System.Diagnostics.Process.Start(@"M:'dtf'" + filenaam + ".dtf");
        //        i = i++;
        //        Thread.Sleep(100);
        //    }
        //    //OdbcCommand cm = new OdbcCommand("DELETE FROM SELECTIE WHERE *", con);
        //    //OdbcDataAdapter da = new OdbcDataAdapter();
        //    //da.DeleteCommand = cm;
        //    iDB2DataAdapter data = new iDB2DataAdapter("SELECT FROM SELECTIE ORDER BY OMSCH", conn);
        //    conn.Open();
        //    data.DeleteCommand = new iDB2Command("DELETE FROM SELECTIE", conn);
        //    data.DeleteCommand.ExecuteNonQuery();
        //}
        //else
        //{
        //    Populate();
        //}
        //conn.Close();
        //Populate();

    }
    private Thread GetT()
    {
        Thread t = new Thread(new ThreadStart(sendMail));
        return t;
    }
    void mytimer_Tick(object sender, EventArgs e)
    {
        //sendMail();

    }
    private void btnStop_Click(object sender, EventArgs e)
    {
        Thread t = GetT();
        t.Abort();
        label2.Text = ("Stopped...");
        mytimer.Enabled = false;
    }
    private void label2_Click(object sender, EventArgs e)
    {
    }
    private void Form1_Load(object sender, EventArgs e)
    {
    }

DataReader对象引用未设置错误

如果没有结果,getemail.ExecuteScalar()将返回null,在这种情况下,getemail.ExecuteScalar().ToString()将抛出空引用异常。

你需要检查,像这样:

var result = getemail.ExecuteScalar();
if (result != null)
{
    string emailaddress = result.ToString();
    // Etc

如果您执行var result = getemail.ExecuteScalar();,您将看到resultnull,因此您不能在其上调用ToString()。您必须检查返回值,看看它是否可用。

您的SQL查询可能是错误的,因此,ExecuteScalar返回null。你不能在null上使用ToString方法。验证您的查询将返回一个结果,我建议您在应用ToString之前从ExecuteScalar测试您的结果为null。

可以这样使用:

var emailaddress = getemail.ExecuteScalar();
if (emailaddress != null) {
    result = emailaddress.ToString();
}
当没有记录时,

getemail.ExecuteScalar()返回null。因此,需要在if块中检查条件

您可以按如下操作

emailaddress = Convert.ToString(getemail.ExecuteScalar());

你可以继续

if(!String.IsNullOrEmpty(emailaddress))
{
  // do something with email
}

SqlCeCommand getemail = new SqlCeCommand("SELECT email FROM Emails  WHERE query LIKE @querynaam" , dbcon);
getemail.Parameters.AddWithValue("@querynaam","%" + filenaam + "%");

试试下面这行代码来代替getemail.ExecuteScalar().ToString()

Convert.ToString(getemail.ExecuteScalar())

Convert.ToString()方法将为你处理null,如果值是非空值,它将返回字符串,如果它返回null,它将简单地返回一个空字符串。

谢谢