DataReader Object Reference not set error - c#

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

Related

Error: 42601 syntax error at or near ":" when trying to save data in windoes forms c# program

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?

Capture the id of one or more cells of a DataGridView for Mass SMS

I added a CheckBox to the DataGridView to be able to select several items and thus pass them to an Array to be able to send messages in bulk.
Problem 1: pressing on the CheckBox is not checked. It is worth mentioning that all I did was add it from the DataGridView editing properties.
Problem 2: to send messages in bulk use the following block in string:
string bloque = "";
bloque = bloque + "ID1\t112223333\tMessage\n";
But, I need to send those messages automatically. This means that, with the exception of the message or text, the ID and the PHONE must be loaded and / or assigned by selecting one or more CheckBoxes from the DataGridView. For this, create the following class:
class Example
{
public int id { get; set; }
public string cellphone{ get; set; }
public string text{ get; set; }
public Example() { }
public Example(int id, string cel, string text) {
this.id = id;
this.cellphone= cel;
this.text= text;
}
public string toString() {
return "ID"+id+"\t" + cellphone+ "\t" + text + "\n";
}
}
}
Now, this is currently the interface code:
public partial class Form1 : Form{
public Form1(){
InitializeComponent();
dtgId.AllowUserToAddRows = false;
}
private void Form1_Load(object sender, EventArgs e){
allId();
dtgId.ReadOnly = true;
}
public void allId(){//method to populate the DataGridView
try{
string chain = "chain";
using (SqlConnection con = new SqlConnection(cadena)){
con.Open();
string query = "SELECT id FROM clients GROUP BY id";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dtgId.DataSource = ds.Tables[0];
con.Close();
}
}
catch (SqlException ex){
MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button2_Click(object sender, EventArgs e){//Code to send SMS in bulk
string user= "user";
string pass= "pass";
string respuesta = "";
int id = Convert.ToInt32(txtId.Text);
string cellp= txtNumber.Text;
string text= txtText.Text;
List<Example> item = new List<Example>();
Example example= new Example(id, cellp, text);
item.Add(example);
string bloque = "";
//bloque = bloque + "ID1\t1144444444\tMi texto 1\n";
for (int i = 0; i > item.Count; i++){
bloque += item[i].toString();
}
Uri uri = new Uri("uri");
HttpWebRequest requestFile = (HttpWebRequest)WebRequest.Create(uri);
requestFile.Method = "POST";
requestFile.ContentType = "application/x-www-form-urlencoded";
StringBuilder postData = new StringBuilder();
postData.Append("api=" + System.Web.HttpUtility.UrlEncode("1") + "&");
postData.Append("usuario=" + System.Web.HttpUtility.UrlEncode(user) + "&");
postData.Append("clave=" + System.Web.HttpUtility.UrlEncode(pass) + "&");
postData.Append("separadorcampos=" + System.Web.HttpUtility.UrlEncode("tab") + "&");
postData.Append("bloque=" + System.Web.HttpUtility.UrlEncode(bloque) + "&");
byte[] byteArray = Encoding.GetEncoding("iso-8859-1").GetBytes(postData.ToString());
requestFile.ContentLength = byteArray.Length;
Stream requestStream = requestFile.GetRequestStream();
requestStream.Write(byteArray, 0, byteArray.Length);
requestStream.Close();
HttpWebResponse webResp = requestFile.GetResponse() as HttpWebResponse;
if (requestFile.HaveResponse){
if (webResp.StatusCode == HttpStatusCode.OK || webResp.StatusCode == HttpStatusCode.Accepted){
StreamReader respReader = new StreamReader(webResp.GetResponseStream(), Encoding.GetEncoding("iso-8859-1"));
respuesta = respReader.ReadToEnd();
MessageBox.Show(respuesta);
}
}
}
private void dtgId_CellContentClick(object sender, DataGridViewCellEventArgs e){
//With this method, pressing on a checkbox shows the id and the phone in a TextBox
var row = dtgId.Rows[e.RowIndex];
var id = Convert.ToInt32(row.Cells["id"].Value.ToString());
try{
string conn = "cadena";
using (SqlConnection con = new SqlConnection(conn)){
con.Open();
string sql = "SELECT id,cellphone FROM clients WHERE id=#id";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#id", id);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read()){
txtId.Text = reader["id"].ToString();
txtNumero.Text = reader["cellphone"].ToString();
}
}
}catch (SqlException exc){
MessageBox.Show("Error: " + exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
To summarize the idea: It does not send the messages, that is, they have not reached me. Any idea how I can fix it?
Think I'd have done it more like this; cut down on a lot of low level/redundant code by using HttpClient to send the request, by loading the cellphone into the grid as well as the ID so we don't have to trip to the database again:
public partial class Form1 : Form
{
HttpClient _httpClient = new HttpClient();
public Form1()
{
InitializeComponent();
dtgId.AllowUserToAddRows = false;
}
private void Form1_Load(object sender, EventArgs e)
{
AllId();
}
public void AllId()
{//method to populate the DataGridView
try
{
using (SqlDataAdapter da = new SqlDataAdapter("SELECT id, cellphone FROM clients GROUP BY id", "constr"))
{
DataTable dt = new DataTable();
da.Fill(dt);
dt.Columns.Add("Choose", typeof(bool)); //will become a checkbox column in the grid
dtgId.DataSource = dt;
}
}
catch (SqlException ex)
{
MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private async void SendSms(string id, string number, string message)
{
var values = new Dictionary<string, string>
{
{ "api", "1" },
{ "usario", "user" },
{ "clave", "pass" },
{ "separadorcampos", "tab" },
{ "bloque", $"{id}\t{number}\t{message}\n" }
};
var content = new FormUrlEncodedContent(values);
var response = await _httpClient.PostAsync("uri", content);
var responseString = await response.Content.ReadAsStringAsync();
//do whatever with response...
}
private void GoButton_Click(object sender, DataGridViewCellEventArgs e)
{
DataTable dt = dtgId.DataSource as DataTable;
foreach (DataRow ro in dt.Rows) //iterate the table
{
if (ro.Field<bool>("Choose")) //if ticked by user
SendSms(ro.Field<string>("ID"), ro.Field<string>("Cellphone"), "hello, this is my message"); //send the sms
}
}
}

survey page in asp c#

I have requirement to create a survey web form which should be loaded from database.
Each questions will have 10 rating items from 1-10 and the result should be saved to the database with question number.
I tried to achieve it with a web form with label control at the top and RadioButtonList for options, but only one question and answer is possible to load for display at a time. I'm new to web programming. If there is any working code sample or any idea how to achieve this, it would be helpful.
I've done the coding to put each question on page and on button click I am loading the next question, but I need all the questions on a single page.
public partial class _Default : System.Web.UI.Page
{
public static SqlConnection sqlconn;
protected string PostBackStr;
protected void Page_Load(object sender, EventArgs e)
{
sqlconn = new SqlConnection(ConfigurationManager.AppSettings["sqlconnstr"].ToString());
PostBackStr = Page.ClientScript.GetPostBackEventReference(this, "time");
if (IsPostBack)
{
string eventArg = Request["__EVENTARGUMENT"];
if (eventArg == "time")
{
string str = "select * from tbl_Question";
SqlDataAdapter da2 = new SqlDataAdapter(str, sqlconn);
DataSet ds2 = new DataSet();
da2.Fill(ds2, "Question");
int count = ds2.Tables[0].Rows.Count;
getNextQuestion(count);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Visible = false;
txtName.Visible =false;
Button1.Visible = false;
Panel1.Visible = true;
lblName.Text = "Name : " + txtName.Text;
int score = Convert.ToInt32(txtScore.Text);
lblScore.Text = "Score : " + Convert.ToString(score);
Session["counter"]="1";
Random rnd = new Random();
int i = rnd.Next(1, 10);//Here specify your starting slno of question table and ending no.
//lblQuestion.Text = i.ToString();
getQuestion(i);
}
protected void Button2_Click(object sender, EventArgs e)
{
string str = "select * from tbl_Question ";
SqlDataAdapter da2 = new SqlDataAdapter(str, sqlconn);
DataSet ds2 = new DataSet();
da2.Fill(ds2, "Question");
int count = ds2.Tables[0].Rows.Count;
getNextQuestion(count);
}
public void getQuestion(int no)
{
string str = "select * from tbl_Question where slNo=" + no + "";
SqlDataAdapter da2 = new SqlDataAdapter(str, sqlconn);
DataSet ds2 = new DataSet();
da2.Fill(ds2, "Question");
// int count = ds2.Tables[0].Rows.Count;
if (ds2.Tables[0].Rows.Count > 0)
{
DataRow dtr;
int i = 0;
while (i < ds2.Tables[0].Rows.Count)
{
dtr = ds2.Tables[0].Rows[i];
Session["Answer"] = Convert.ToString(Convert.ToInt32 (dtr["Correct"].ToString())-1);
lblQuestion.Text = "Q." + Session["counter"].ToString() + " " + dtr["Question"].ToString();
lblQuestion2.Text = "Q." + Session["counter"].ToString() + " " + dtr["arQuestion"].ToString();
LblQNNo.Text = Session["counter"].ToString();
RblOption.ClearSelection();
RblOption.Items.Clear();
RblOption.Items.Add(dtr["Option1"].ToString());
RblOption.Items.Add(dtr["Option2"].ToString());
RblOption.Items.Add(dtr["Option3"].ToString());
RblOption.Items.Add(dtr["Option4"].ToString());
RblOption.Items.Add(dtr["Option5"].ToString());
RblOption.Items.Add(dtr["Option6"].ToString());
RblOption.Items.Add(dtr["Option7"].ToString());
RblOption.Items.Add(dtr["Option8"].ToString());
RblOption.Items.Add(dtr["Option9"].ToString());
RblOption.Items.Add(dtr["Option10"].ToString());
i++;
}
}
}
public void getNextQuestion(int cnt)
{
if (Convert.ToInt32(Session["counter"].ToString()) < cnt)
{
Random rnd = new Random();
int i = rnd.Next(1, 10);
lblQuestion.Text = i.ToString();
getQuestion(i);
//qst_no = i;
Session["counter"] = Convert.ToString(Convert.ToInt32(Session["counter"].ToString()) + 1);
}
else
{
Panel2.Visible = false;
//code for displaying after completting the exam, if you want to show the result then you can code here.
}
}
protected void Button3_Click(object sender, EventArgs e)
{
insertAns();
}
private void insertAns()
{
SqlCommand cmd;
sqlconn = new SqlConnection(ConfigurationManager.AppSettings["sqlconnstr"].ToString());
cmd = new SqlCommand("insert into Tbl_Ans(UserID, Question_ID, Answer) values(#ans, #ans1, #ans2)", sqlconn);
cmd.Parameters.AddWithValue("#ans", txtName.Text);
cmd.Parameters.AddWithValue("#ans1", Session["counter"].ToString());
cmd.Parameters.AddWithValue("#ans2", RblOption.SelectedItem.Text);
sqlconn.Open();
int i = cmd.ExecuteNonQuery();
sqlconn.Close();
if (i != 0)
{
lbmsg.Text = "Your Answer Submitted Succesfully";
lbmsg.ForeColor = System.Drawing.Color.ForestGreen;
}
else
{
lbmsg.Text = "Some Problem Occured";
lbmsg.ForeColor = System.Drawing.Color.Red;
}
}
#region Connection Open
public void ConnectionOpen()
{
try
{
if (sqlconn.State == ConnectionState.Closed) { sqlconn.Open(); }
}
catch (SqlException ex)
{
lbmsg.Text = ex.Message;
}
catch (SystemException sex)
{
lbmsg.Text = sex.Message;
}
}
#endregion
#region Connection Close
public void ConnectionClose()
{
try
{
if (sqlconn.State != ConnectionState.Closed) { sqlconn.Close(); }
}
catch (SqlException ex)
{
lbmsg.Text = ex.Message;
}
catch (SystemException exs)
{
lbmsg.Text = exs.Message;
}
}
#endregion
}
first i want to say that you should use question table id instead of question number to save with the answer for future use.
I dont know more about dotnet so i have not attached any code here. But i can suggest you that
First fetch all the questions with their respective id into an object or array or fetch from them adaptor etc.
Then you can use a form to show them using foreach loop. for eg.
suppose "questions" is an array containing your all fetched questions from database. then apply
<form action="abc" method="post">
foreach(questions as question){
<tr>
<td>(print your question here)</td>
<td><input type="anything you want" name="(print here question.id)" />
</tr>
}
<input type="submit" value="submit" />
</form>
Now where you will fetch data on the form submission then you can easily access the answers with their name that is already question id. So now both have associated with each other.
welcome for any query if not clear.

Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool.

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
}

Connection error C#

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);
//....

Categories