private OleDbConnection conexao;
private Timer time = new Timer();
public void Conexao() //Conexão
{
string strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|DB.accdb";
conexao = new OleDbConnection(strcon);
}
void tabela()
{
Conexao();
conexao.Open();
label1.Text = DateTime.Now.ToString();
string bn = "select D2 from Planilha where D2='" + label1.Text + "'";
textBox1.Text = label1.Text;
OleDbCommand Queryyy = new OleDbCommand(bn, conexao);
OleDbDataReader drr;
drr = Queryyy.ExecuteReader();
if (drr.Read() == true)
{
try
{
MessageBox.Show("Hi");
}
catch (OleDbException ex)
{
MessageBox.Show("" + ex);
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
tabela();
}
Timer Interval = 1000
(click for larger view)
I'm all afternoon trying to fix it but could not so I come here for help
I think asawyer's comment had it right I bet the problem is from the fact you are not handling your objects correctly, get rid of your class objects and work with using statements
public OleDbConnection Conexao() //Conexão
{
string strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|DB.accdb";
return new OleDbConnection(strcon);
}
void tabela()
{
try
{
timer1.Enabled = false;
using(var conexao = Conexao())
{
conexao.Open();
label1.Text = DateTime.Now.ToString();
string bn = "select D2 from Planilha where D2='" + label1.Text + "'";
textBox1.Text = label1.Text;
using(OleDbCommand Queryyy = new OleDbCommand(bn, conexao))
using(OleDbDataReader drr = Queryyy.ExecuteReader())
{
if (drr.Read() == true)
{
try
{
MessageBox.Show("Hi");
}
catch (OleDbException ex)
{
MessageBox.Show("" + ex);
}
}
}
}
}
finally
{
timer.Enabled = true;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
tabela();
}
Also from the fact that you are only reading the first column of the first row, you should use ExecuteScalar instead of ExecuteReader.
using(OleDbCommand Queryyy = new OleDbCommand(bn, conexao))
{
try
{
var result = Queryyy.ExecuteScalar();
if (result != null)
{
MessageBox.Show("Hi");
}
}
catch (OleDbException ex)
{
MessageBox.Show("" + ex);
}
}
}
You also should be using parametrized queries.
label1.Text = DateTime.Now.ToString();
string bn = "select D2 from Planilha where D2=#param1";
textBox1.Text = label1.Text;
using(OleDbCommand Queryyy = new OleDbCommand(bn, conexao))
{
Queryyy.Parameters.AddWithValue("#param1", label1.Text);
//....
Related
Form1
namespace erpmam
{
public partial class Form1 : Form
{
MySqlDB mySqlDB;
SqlDataAdapter adpt;
DataTable dt;
SqlConnection con;
public void showdata()
{
adpt = new SqlDataAdapter("select deptmt_id, deptmt_name, deptmt_seq, reg_ymdtms, mod_ymdtms from sys_department;",con);
dt = new DataTable();
adpt.Fill(dt);
dgv1.DataSource = dt;
}
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
mySqlDB = new MySqlDB("server=······");
}
private SqlDataAdapter MySqlDataAdapter(string v, MySqlConnection con)
{
throw new NotImplementedException();
}
public void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void BTN_INSERT_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.ShowDialog();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
string sql = "";
sql += " select";
sql += " deptmt_id, deptmt_name, deptmt_seq, reg_ymdtms, mod_ymdtms";
sql += " from sys_department";
sql += " where deptmt_id like '%" + textBox1.Text.Trim() + "%'";
DataTable dt = mySqlDB.ExecuteReader(sql, mySqlDB.DBConnection());
dgv1.SuspendLayout();
dgv1.Rows.Clear();
for (int idx = 0; idx < dt.Rows.Count; idx++)
{
DataRow r = dt.Rows[idx];
dgv1.Rows.Add(1);
dgv1[0, idx].Value = r["deptmt_id"].ToString().Trim();
dgv1[1, idx].Value = r["deptmt_name"].ToString().Trim();
dgv1[2, idx].Value = r["deptmt_seq"].ToString().Trim();
dgv1[3, idx].Value = r["reg_ymdtms"].ToString().Trim();
dgv1[4, idx].Value = r["mod_ymdtms"].ToString().Trim();
}
dgv1.ResumeLayout();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
string sql = "";
sql += " select";
sql += " deptmt_id, deptmt_name, deptmt_seq, reg_ymdtms, mod_ymdtms";
sql += " from sys_department";
sql += " where deptmt_name like '%" + textBox2.Text.Trim() + "%'";
DataTable dt = mySqlDB.ExecuteReader(sql, mySqlDB.DBConnection());
dgv1.SuspendLayout();
dgv1.Rows.Clear();
for (int idx = 0; idx < dt.Rows.Count; idx++)
{
DataRow r = dt.Rows[idx];
dgv1.Rows.Add(1);
dgv1[0, idx].Value = r["deptmt_id"].ToString().Trim();
dgv1[1, idx].Value = r["deptmt_name"].ToString().Trim();
dgv1[2, idx].Value = r["deptmt_seq"].ToString().Trim();
dgv1[3, idx].Value = r["reg_ymdtms"].ToString().Trim();
dgv1[4, idx].Value = r["mod_ymdtms"].ToString().Trim();
}
dgv1.ResumeLayout();
}
private void dgv1_CellClick(object sender, DataGridViewCellEventArgs e)
{
Form3 Form3 = new Form3();
Form3.ShowDialog();
}
}
}
Form2
namespace erpmam
{
public partial class Form2 : Form
{
MySqlConnection connection = new MySqlConnection("datasource =······");
MySqlCommand command;
public Form2()
{
InitializeComponent();
}
public void executeMyQuery(string query)
{
try
{
openConnection();
command = new MySqlCommand(query, connection);
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("Query Executed");
}
else
{
MessageBox.Show("Query Not Executed");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
closeConnection();
}
}
public void openConnection()
{
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
}
public void closeConnection()
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
string insertQuery = "INSERT INTO sys_department(DEPTMT_ID, DEPTMT_NAME, DEPTMT_SEQ, REG_YMDTMS) VALUES(" + textBox1.Text + ',' + textBox2.Text + ','+ textBox3.Text + ','+ "NOW()" +")";
connection.Open();
MySqlCommand command = new MySqlCommand(insertQuery, connection);
try
{
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("adding normally");
}
else
{
MessageBox.Show("error");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Form3
namespace erpmam
{
public partial class Form3 : Form
{
MySqlConnection connection = new MySqlConnection("datasource = localhost; port = 3306; Initial Catalog = 'erp'; username = root; password=610822");
MySqlCommand command;
public Form3()
{
InitializeComponent();
}
public void executeMyQuery(string query)
{
try
{
openConnection();
command = new MySqlCommand(query, connection);
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("Query Executed");
}
else
{
MessageBox.Show("Query Not Executed");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
closeConnection();
}
} public void openConnection()
{
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
}
public void closeConnection()
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
private void btn_update_Click(object sender, EventArgs e)
{
string updateQuery = " UPDATE sys_department";
updateQuery += " SET DEPTMT_NAME = '" + textBox2.Text + "', DEPTMT_SEQ = '" + textBox3.Text + "', mod_ymdtms = NOW()";
updateQuery += " where DEPTMT_ID = '" + textBox1.Text + "'";
connection.Open();
MySqlCommand command = new MySqlCommand(updateQuery, connection);
try
{
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("changed normally");
}
else
{
MessageBox.Show("error");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
this.Close();
}
private void btn_delete_Click(object sender, EventArgs e)
{
string deleteQuery = " DELETE from sys_department";
deleteQuery += " where DEPTMT_ID = '" + textBox1.Text + "' or DEPTMT_NAME = '" + textBox2.Text + "' or DEPTMT_SEQ = '" + textBox3.Text + "'" ;
connection.Open();
MySqlCommand command = new MySqlCommand(deleteQuery, connection);
try
{
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("adding normally");
}
else
{
MessageBox.Show("error");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
this.Close();
}
private void btn_cancel_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Simply you can create a Global variable of Datatable to use it as source of Data and you can use it anywhere in your Forms
This is the GLobal Class
//make sure to import this System.Data
using System.Data;
class Global
{
private static DataTable source;
public static DataTable Source
{
get
{
// Reads are usually simple
return source;
}
set
{
// You can add logic here for race conditions,
// or other measurements
source = value;
}
}
}
In your first form
string connectString = "datasource=xxxx;port=3306;username=xxxx;password=;database=xxxxx;";
MySqlConnection conn;
MySqlCommand comm;
MySqlDataReader read;
MySqlDataAdapter adapter;
Global mySource;
void getData() {
string query = "Select * from tableName";
conn = new MySqlConnection(connectString);
conn.Open();
comm = new MySqlCommand(query, conn);
adapter = new MySqlDataAdapter(query, conn);
DataSet ds = new DataSet();
adapter.Fill(ds);
//setting up
Global.Source = ds.Tables[0];
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
In you second Form
public Form2()
{
InitializeComponent();
dataGridView1.DataSource = Global.Source;
}
Simply you can create static method in the class of form3 and accept one argument from DataGridView type and call this method from form1 and pass dg1 after filling it with rows then you can access it now from this static method...
private void dgv1_CellClick(object sender, DataGridViewCellEventArgs e) {
Form3 Form3 = new Form3();
Form3.staticMethodToPassDGVBetweenTwoForms(dgv1);
Form3.ShowDialog();
}
namespace erpmam {
public partial class Form3 : Form {
public Form3() {
initializeComponent();
}
public static void staticMethodToPassDGVBetweenTwoForms(DataGridView dgv1){
//do anything with dg1 now
}
}
I'm making a small program that allows me to insert data into a data table which is connected with PostgreSQL. All functions are working fine on postgresql: select, insert, update and delete.
Here is the code:
private void FrmTeachers_Load(object sender, EventArgs e)
{
conn = new NpgsqlConnection(connstring);
Select();
//dgvTabela.Columns["docente_id"].HeaderText = "Teachers ID";
}
private void Select()
{
try
{
conn.Open();
sql = #"select * from docen_selecionar()";
cmd = new NpgsqlCommand(sql, conn);
dt = new DataTable();
dt.Load(cmd.ExecuteReader());
conn.Close();
dgvTabela.DataSource = null;
dgvTabela.DataSource = dt;
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show("Error: " + ex.Message);
}
}
private void DgvTabela_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
txtName.Text = dgvTabela.Rows[e.RowIndex].Cells["_docente_id"].Value.ToString();
txtID.Text = dgvTabela.Rows[e.RowIndex].Cells["_nome_docente"].Value.ToString();
txtVAT.Text = dgvTabela.Rows[e.RowIndex].Cells["_nif_number"].Value.ToString();
txtDepart.Text = dgvTabela.Rows[e.RowIndex].Cells["_departamento"].Value.ToString();
txtDegree.Text = dgvTabela.Rows[e.RowIndex].Cells["_grau_academico"].Value.ToString();
}
}
private void btnRegister_Click(object sender, EventArgs e)
{
rowIndex = -1;
txtName.Enabled = txtDegree.Enabled = txtDepart.Enabled = txtID.Enabled = txtVAT.Enabled = true;
txtName.Text = txtDegree.Text = txtDepart.Text = txtID.Text = txtVAT.Text = null;
txtName.Select();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (rowIndex < 0)
{
MessageBox.Show("Please choose a Teacher to update");
return;
}
txtName.Enabled = txtDegree.Enabled = txtDepart.Enabled = txtID.Enabled = txtVAT.Enabled = true;
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (rowIndex < 0)
{
MessageBox.Show("Please choose a Teacher ID to delete");
return;
}
try
{
conn.Open();
sql = #"select * from docen_apagar(:_docente_id)";
cmd = new NpgsqlCommand(sql, conn);
cmd.Parameters.AddWithValue("_docente_id", int.Parse(dgvTabela.Rows[rowIndex].Cells["docente_id"].Value.ToString()));
if ((int)cmd.ExecuteScalar() == 1)
{
MessageBox.Show("Teacher deleted successfully");
rowIndex = -1;
Select();
}
conn.Close();
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show("Delete fail. Please try again. Error:" + ex.Message);
}
}
//save - esqueci-me de alterar o name
private void iconButton1_Click(object sender, EventArgs e)
{
int result = 0;
if (rowIndex < 0) //insert
{
try
{
conn.Open();
sql = #"select * from docen_registar(:_docente_id,:_nome_docente,:_departmento,:_grau_academico,:_nif_number)";
cmd = new NpgsqlCommand(sql, conn);
cmd.Parameters.AddWithValue("_nome_docente", txtName.Text);
cmd.Parameters.AddWithValue("_docente_id", txtID.Text);
cmd.Parameters.AddWithValue("_departamento", txtDepart.Text);
cmd.Parameters.AddWithValue("_grau_academico", txtDegree.Text);
cmd.Parameters.AddWithValue("_nif_number", txtVAT.Text);
result = (int)cmd.ExecuteScalar();
conn.Close();
if (result == 1)
{
MessageBox.Show("Inserted new Teacher successfully");
Select();
}
else
{
MessageBox.Show("Inserted fail");
}
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show("Inserted fail, please try again. Error: " + ex.Message);
}
}
else //update
{
try
{
conn.Open();
sql = #"select * from docen_update(:_docente_id,:_nome_docente,:_departmento,:_grau_academico,:_nif_number)";
cmd = new NpgsqlCommand(sql, conn);
cmd.Parameters.AddWithValue("_docente_id", int.Parse(dgvTabela.Rows[rowIndex].Cells["docente_id"].Value.ToString()));
cmd.Parameters.AddWithValue("_nome_docente", txtName.Text);
cmd.Parameters.AddWithValue("_docente_id", txtID.Text);
cmd.Parameters.AddWithValue("_departamento", txtDepart.Text);
cmd.Parameters.AddWithValue("_grau_academico", txtDegree.Text);
cmd.Parameters.AddWithValue("_nif_number", txtVAT.Text);
result = (int)cmd.ExecuteScalar();
conn.Close();
if (result == 1)
{
MessageBox.Show("Successfully updated");
Select();
}
else
{
MessageBox.Show("Updated fail, please try again.");
}
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show("Updated fail, please try again. Error: " + ex.Message);
}
}
result = 0;
txtName.Text = txtDegree.Text = txtDepart.Text = txtID.Text = txtVAT.Text = null;
txtName.Enabled = txtDegree.Enabled = txtDepart.Enabled = txtID.Enabled = txtVAT.Enabled = false;
}
}
}
I'm trying to create 4 buttons: insert, update, delete and save and when I click save it gives the following error:
"Error: 42601 syntax error at or near ":""
I Really don't know what it is.
Can someone help me?
I am getting this error
Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
I read this question and it states that the exception is caused because of not closing the connection. However, i close all the connection in my code
This is my code, it is simple
public partial class index : System.Web.UI.Page
{
private static string defaultReason = "reason not selected";
protected override object SaveViewState()
{
//save view state right after the dynamic controlss added
var viewState = new object[1];
viewState[0] = base.SaveViewState();
return viewState;
}
protected override void LoadViewState(object savedState)
{
//load data frm saved viewstate
if (savedState is object[] && ((object[])savedState).Length == 1)
{
var viewState = (object[])savedState;
fillReasons();
base.LoadViewState(viewState[0]);
}
else
{
base.LoadViewState(savedState);
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string callIDValue = Request.QueryString["CallID"];
string callerIDValue = Request.QueryString["CallerID"];
if (!String.IsNullOrEmpty(callerIDValue))
{
callerID.Value = callerIDValue;
if (!String.IsNullOrEmpty(callIDValue))
{
string query = "INSERT INTO Reason (callerID, callID, reason, timestamp) VALUES (#callerID, #callID, #reason, #timestamp)";
SqlConnection con = getConnection();
SqlCommand command = new SqlCommand(query, con);
command.Parameters.AddWithValue("#callerID", callerIDValue);
command.Parameters.AddWithValue("#callID", callIDValue);
command.Parameters.AddWithValue("#reason", defaultReason);
command.Parameters.AddWithValue("#timestamp", DateTime.Now.ToString());
try
{
con.Open();
command.ExecuteNonQuery();
command.Dispose();
con.Close();
}
catch (Exception ee)
{
command.Dispose();
con.Close();
message.InnerHtml = ee.Message;
}
}
else
{
message.InnerHtml = "Call ID is empty";
}
}
else
{
callerID.Value = "Undefined";
message.InnerHtml = "Caller ID is empty";
}
fillReasons();
}
else
{
}
}
private void fillReasons()
{
string query = "SELECT * FROM wrapuplist WHERE isEnabled = #isEnabled";
SqlConnection con = new SqlConnection(getConnectionString());
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("isEnabled", true);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable results = new DataTable();
da.Fill(results);
int numberOfReasons = 0; // a integer variable to know if the number of the reasons becomes able to be divided by four
HtmlGenericControl div = null;
foreach (DataRow row in results.Rows)
{
numberOfReasons++;
if ((numberOfReasons % 4) == 1)
{
div = new HtmlGenericControl("div");
div.Attributes.Add("class", "oneLine");
}
RadioButton radioButton = new RadioButton();
radioButton.ID = "reason_" + row["reasonName"].ToString();
radioButton.GroupName = "reason";
radioButton.Text = row["reasonName"].ToString();
div.Controls.Add(radioButton);
if (numberOfReasons % 4 == 0)
{
myValueDiv.Controls.Add(div);
//numberOfReasons = 0;
}
else if (numberOfReasons == results.Rows.Count)
{
myValueDiv.Controls.Add(div);
//numberOfReasons = 0;
}
}
cmd.Dispose();
da.Dispose();
con.Close();
}
private SqlConnection getConnection()
{
return new SqlConnection(ConfigurationManager.ConnectionStrings["vmpcon"].ConnectionString);
}
private string getConnectionString()
{
return ConfigurationManager.ConnectionStrings["wrapupconnection"].ConnectionString.ToString();
}
protected void buttonSaveClose_Click(object sender, EventArgs e)
{
var divcontrols = myValueDiv.Controls.OfType<HtmlGenericControl>();
bool isFound = false;
RadioButton checkedRadioButton = null;
foreach (HtmlGenericControl loHTML in divcontrols)
{
var checkedRadioButtons = loHTML.Controls.OfType<RadioButton>().Where(radButton => radButton.Checked).ToList();
foreach (RadioButton lobtn in checkedRadioButtons)
{
if (lobtn.Checked)
{
isFound = true;
checkedRadioButton = lobtn;
}
}
}
if (isFound)
{
sReasonError.InnerText = "";
string reason = "";
reason = checkedRadioButton.Text;
string callIDValue = Request.QueryString["CallID"];
string callerIDValue = Request.QueryString["CallerID"];
if (String.IsNullOrEmpty(callIDValue))
{
message.InnerText = "Call ID is empty";
}
else if (String.IsNullOrEmpty(callerIDValue))
{
message.InnerText = "Caller ID is empty";
}
else
{
message.InnerText = "";
string query2 = "SELECT * FROM Reason WHERE callID = #callID AND reason != #reason";
SqlConnection con = getConnection();
SqlCommand command2 = new SqlCommand(query2, con);
command2.Parameters.AddWithValue("#callID", callIDValue);
command2.Parameters.AddWithValue("#reason", defaultReason);
con.Open();
if (command2.ExecuteScalar() != null)
{
message.InnerText = "Already saved";
command2.Dispose();
con.Close();
}
else
{
command2.Dispose();
con.Close();
string notes = taNotes.InnerText;
string query = "UPDATE Reason SET reason = #reason, notes = #notes, timestamp = #timestamp WHERE callID = #callID";
SqlCommand command = new SqlCommand(query, con);
command.Parameters.AddWithValue("#callID", callIDValue);
command.Parameters.AddWithValue("#reason", reason);
command.Parameters.AddWithValue("#notes", notes);
command.Parameters.AddWithValue("#timestamp", DateTime.Now.ToString());
try
{
con.Open();
command.ExecuteNonQuery();
command.Dispose();
con.Close();
message.InnerText = "Done Successfully";
//ClientScript.RegisterStartupScript(typeof(Page), "closePage", "<script type='text/JavaScript'>window.close();</script>");
ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.open('close.html', '_self', null);", true);
}
catch (Exception ee)
{
command.Dispose();
con.Close();
message.InnerText = "Error, " + ee.Message;
}
}
}
}
else
{
sReasonError.InnerText = "Required";
message.InnerText = "Select a reason";
//fillReasons();
}
}
}
as you see, all the connection are being closed, what wrong did I do please?
Closing connections and disposing should be in a finally block while using a try catch.
or use a using block like the one below
using(SqlConnection con = getConnection())
{
con.Open();
//Do your operation here. The connection will be closed and disposed automatically when the using scope is exited
}
I have made an application that automatically mails some files.
The problem now is, that I have the emailaddresses in another database, (sdf-file).
I want to search for the value of "filenaam" which can be something like "q1869".
That variable has to be searched in the database (automail.sdf). And when ther is something with the "q1869" in it. Then get the value of that row, in the second field, which is in my case "email".
Now I tried a lot of things.
But I stumbled upon a problem right now.
When I run this code, I get an "Object reference not set to an instance of an object." error at 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)
{
}
getemail.ExecuteScalar() will return null if there are no results, in which case getemail.ExecuteScalar().ToString() will throw a null reference exception.
You will need to check, something like this:
var result = getemail.ExecuteScalar();
if (result != null)
{
string emailaddress = result.ToString();
// Etc
If you do var result = getemail.ExecuteScalar(); you will see that result is null, hence you cannot call ToString() on it. You will have to check the return value to see if it is usable or not.
Your SQL query is probably wrong and thus, the ExecuteScalar returns null. You cannot use ToString method on null. Verify that your query will return a result and I suggest you test your result from ExecuteScalar for null before applying ToString.
You can use like this:
var emailaddress = getemail.ExecuteScalar();
if (emailaddress != null) {
result = emailaddress.ToString();
}
getemail.ExecuteScalar() returns null when there are no records. hence, you need to check condition in if block.
You can do as below
emailaddress = Convert.ToString(getemail.ExecuteScalar());
you can proceed with
if(!String.IsNullOrEmpty(emailaddress))
{
// do something with email
}
And Change below lines
SqlCeCommand getemail = new SqlCeCommand("SELECT email FROM Emails WHERE query LIKE #querynaam" , dbcon);
getemail.Parameters.AddWithValue("#querynaam","%" + filenaam + "%");
Try the below line of code instead of getemail.ExecuteScalar().ToString()
Convert.ToString(getemail.ExecuteScalar())
The Convert.ToString() method will handle null for you, if the value is a non-null value it will return the string and of it returns null it will simple return an empty string.
Thanks
I want to delete from the treeview the nodes,and of course the roleid and userid.and on the other hand i also want to delete from listboxes rows,but i can delete them,but after restart application they are here again.it doesnt save
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using FirebirdSql.Data.FirebirdClient;
using System.Collections;
using System.Reflection;
namespace SiteYoenetim
{
public partial class ManageRoles : Form
{
private FbCommand cmd = null;
public ManageRoles()
{
InitializeComponent();
FillUsersInRollsTree();
}
private void homeToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
}
private void AddNewRole_Click(object sender, EventArgs e)
{
string newName = string.Empty;
newName = NewRoleName.Text;
NewRoleName.Text = string.Empty; // clear the control
DataSet1.ROLESRow newRolesRow;
newRolesRow = DataSet1.ROLES.NewROLESRow();
newRolesRow.ROLENAME = newName;
this.DataSet1.ROLES.Rows.Add(newRolesRow);
try
{
this.rolesTableAdapter.Update(this.DataSet1.ROLES);
}
catch (Exception ex)
{
this.DataSet1.ROLES.Rows.Remove(newRolesRow);
MessageBox.Show("Unable to add role " + newName + ex.Message,
"Unable to add role!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
RolesListBox.SelectedIndex = -1;
}
private void DeleteRole_Click(object sender, EventArgs e)
{
string newName = string.Empty;
newName = NewRoleName.Text;
NewRoleName.Text = string.Empty; // clear the control
DataSet1.ROLESRow newRolesRow;
newRolesRow = DataSet1.ROLES.NewROLESRow();
newRolesRow.ROLENAME = newName;
this.DataSet1.ROLES.Rows.RemoveAt(RolesListBox.SelectedIndex);
this.rolesTableAdapter.Update(this.DataSet1.ROLES);
}
private void AddNewAppUser_Click(object sender, EventArgs e)
{
DataSet1.USERSRow newUsersRow;
newUsersRow = DataSet1.USERS.NewUSERSRow();
newUsersRow.NAME = NewUserName.Text;
NewUserName.Text = string.Empty;
this.DataSet1.USERS.Rows.Add(newUsersRow);
this.usersTableAdapter.Update(this.DataSet1.USERS);
AppUsersListBox.SelectedIndex = -1;
}
HERE IT DELETES FROM APPUSER but it is again here after restart application
private void DeleteAppUser_Click(object sender, EventArgs e)
{
DataSet1.USERSRow delUsersRow;
delUsersRow = DataSet1.USERS.NewUSERSRow();
delUsersRow.NAME = NewUserName.Text;
NewUserName.Text = string.Empty;
this.DataSet1.USERS.Rows.RemoveAt(AppUsersListBox.SelectedIndex);
this.usersTableAdapter.Update(this.DataSet1.USERS);
}
private void AddUsersToRole_Click(object sender, EventArgs e)
{
ConnectionStringSettingsCollection connectionStrings =
ConfigurationManager.ConnectionStrings;
string connString = connectionStrings["xxx.Properties.Settings.xxx"].ToString();
FbConnection conn = new FbConnection(connString);
conn.Open();
FbParameter param;
foreach (DataRowView userRow in AppUsersListBox.SelectedItems)
{
foreach (DataRowView roleRow in RolesListBox.SelectedItems)
{
int userID = Convert.ToInt32(userRow["UserID"]);
int roleID = Convert.ToInt32(roleRow["RoleID"]);
try
{
cmd = new FbCommand("INSERT INTO usersToRoles (FKUserID, FKRoleID) values
(#USERID, #RoleID)", conn);
param = cmd.Parameters.Add("#USERID", FbDbType.Integer);
param.Value = userID;
param.Direction = ParameterDirection.Input;
param = cmd.Parameters.Add("#RoleID", FbDbType.Integer);
param.Value = roleID;
param.Direction = ParameterDirection.Input;
int rowsInserted = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
conn.Close();
FillUsersInRollsTree();
}
private void DisplayError(int userID, int roleID, string message)
{
MessageBox.Show("Unable to add user (" + userID + ") to role (" + roleID + ")" + message,
"Unable to add user to role",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
private void FillUsersInRollsTree()
{
ConnectionStringSettingsCollection connectionStrings =
ConfigurationManager.ConnectionStrings;
string connString = connectionStrings["xxx.Properties.Settings.xxx"].ToString();
FbConnection conn = new FbConnection(connString);
conn.Open();
string queryString = "select u.Name, r.RoleName from userstoRoles utr " +
" join users u on u.userID = utr.FKUserID " +
" join Roles r on r.roleID = utr.FKRoleID ";
if (rbName.Checked)
{
queryString += "order by Name";
}
else
{
queryString += "order by RoleName";
}
UsersInRoles.BeginUpdate();
UsersInRoles.Nodes.Clear();
TreeNode parentNode = null;
TreeNode subNode = null;
DataSet ds = new DataSet();
FbDataAdapter dataAdapter = new FbDataAdapter(queryString, conn);
dataAdapter.Fill(ds, "usersInRoles");
DataTable dt = ds.Tables[0];
string currentName = string.Empty;
foreach (DataRow row in dt.Rows)
{
if (rbName.Checked)
{
subNode = new TreeNode(row["roleName"].ToString());
if (currentName != row["Name"].ToString())
{
parentNode = new TreeNode(row["Name"].ToString());
currentName = row["Name"].ToString();
UsersInRoles.Nodes.Add(parentNode);
}
}
else
{
subNode = new TreeNode(row["Name"].ToString());
if (currentName != row["RoleName"].ToString())
{
parentNode = new TreeNode(row["RoleName"].ToString());
currentName = row["RoleName"].ToString();
UsersInRoles.Nodes.Add(parentNode);
}
}
if (parentNode != null)
{
parentNode.Nodes.Add(subNode);
}
}
UsersInRoles.EndUpdate();
}
private void RadioButtonClick(object sender, EventArgs e)
{
FillUsersInRollsTree();
}
private void ManageRoles_Load(object sender, EventArgs e)
{
this.uSERSTOROLESTableAdapter.Fill(this.dataSet11.USERSTOROLES);
this.uSERSTOROLESTableAdapter.Fill(this.DataSet1.USERSTOROLES);
this.usersTableAdapter.Fill(this.DataSet1.USERS);
this.rolesTableAdapter.Fill(this.DataSet1.ROLES);
}
private void Save_Click(object sender, EventArgs e)
{
this.Validate();
this.usersBindingSource.EndEdit();
this.usersTableAdapter.Update(this.DataSet1);
}
HERE IT SHOULD DELETE FROM TREEVIEW, but it doesnt
private void RemoveUsersFromRole_Click(object sender, EventArgs e)
{
ConnectionStringSettingsCollection connectionStrings =
ConfigurationManager.ConnectionStrings;
string connString = connectionStrings["xxx.Properties.Settings.xxx"].ToString();
FbConnection conn = new FbConnection(connString);
conn.Open();
FbParameter param;
foreach (DataRowView userRow in AppUsersListBox.SelectedItems)
{
foreach (DataRowView roleRow in RolesListBox.SelectedItems)
{
{
int userID = Convert.ToInt32(userRow["UserID"]);
int roleID = Convert.ToInt32(roleRow["RoleID"]);
try
{
cmd = new FbCommand("DELETE FROM usersToRoles (FKUserID, FKRoleID) values (USERID, RoleID)", conn);
param = cmd.Parameters.Add("USERID", FbDbType.Integer);
param.Value = userID;
param.Direction = ParameterDirection.Input;
param = cmd.Parameters.Add("RoleID", FbDbType.Integer);
param.Value = roleID;
param.Direction = ParameterDirection.Input;
int rowsInserted = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
conn.Close();
FillUsersInRollsTree();
}
}
}
}
If your data is stored in a database, then deleting the data from the treeview and listboxes alone is not sufficient. You will have to delete the information in the database as well.
EDIT:
Your DELETE SQL command is wrong. Try to change it to:
DELETE FROM usersToRoles WHERE FKUserID = #USERID AND FKRoleID = #RoleID
(I was a mix between INSERT statement and DELETE statement.)