일부 파일을 자동으로 메일 링하는 응용 프로그램을 만들었습니다. 문제는 이제 다른 데이터베이스 (sdf-file)에 emailaddresses가 있다는 것입니다.DataReader 개체 참조가 설정되지 않았습니다. 오류
"filenaam"의 값을 "q1869"와 같은 값으로 검색하려고합니다. 해당 변수를 데이터베이스 (automail.sdf)에서 검색해야합니다. 그리고 그 때 "q1869"가있는 뭔가가 있습니다. 그런 다음 두 번째 필드에서 해당 행의 값을 구하십시오. 제 경우는 "전자 메일"입니다.
이제 많은 것을 시도했습니다. 하지만 지금 문제가 발생했습니다.
이 코드를 실행하면 "개체 참조가 개체의 인스턴스로 설정되지 않았습니다."라는 메시지가 나타납니다. getemail.ExecuteScalar().ToString()
널 레퍼런스 예외가 발생하는 경우에 결과가 존재하지 않는 경우 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("[email protected]");
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("[email protected]", "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)
{
}
나는 이것을 시도,하지만, 난 여전히 똑같은 오류가 발생합니다. 나는 그 들판이 비어 있지 않았 음을 확신한다. 내가 할 수있는 일이 또 있니? –
디버거에서이 코드를 실행하여 정확히 어떤 유형이 반환되는지 확인할 수 있습니까? 디버거에서 값을 검사하려고하면 어떻게됩니까?만약 당신이 말하는 것이 사실이라면, 타입의 ToString() 메소드의 구현 내에서 예외가 발생해야합니다. 그러나 그것이 단지 '문자열'인 경우 가능하지 않습니다 ... –
아무런 타입도 반환되지 않으므로 "null"이 반환됩니다. 나는 이것이 어떻게 작동하는지 알지 못한다. 어쩌면 당신이 내 SQL 문장에 오류가 있는지 확인할 수 있다면 어떨까? –