Local database not refreshing after updating data from C# - c#

I'm working with a local database, and it works well, the whole app. The problem is that I'm facing with some annoying things. If I update, or add new data to my local database, I have to close the whole app and start it again so I can see the new data I have entered. Why is it not refreshing and how can I solve it?
Here is how I add data:
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
label5.Text = "1";
}
else
{
label5.Text = "0";
}
if (radioButton2.Checked)
{
label5.Text = "2";
}
if (textBox1.Text.Length == 0)
{
textBox1.Text = "Fara";
}
if (textBox2.Text.Length == 0)
{
textBox2.Text = "0";
}
if (textBox3.Text.Length == 0)
{
textBox3.Text = "0";
}
if (numeTextBox.TextLength != 0 && prenumeTextBox.TextLength != 0)
{
var connString = (#"Data Source=" + Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + #"\Angajati.sdf");
//var connString = #"Data Source=C:\Users\Andrei\Documents\Visual Studio 2010\Projects\Stellwag\Stellwag\Angajati.sdf";
using (var conn = new SqlCeConnection(connString))
{
try
{
//deschide conectiunea in db
conn.Open();
//creaza comanda in SQL Server CE
SqlCeCommand cmd = new SqlCeCommand();
//conecteaza cmd la conn
cmd.Connection = conn;
//adauga parametru pt campul poza cu value image
SqlCeParameter picture = new SqlCeParameter("#Poza", SqlDbType.Image);
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] a = ms.GetBuffer();
ms.Close();
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Poza", a);
cmd.CommandText = "INSERT INTO info(Nume, Prenume, Data, Proiect, Schimburi, Poza, Acord, Baza) VALUES('" + numeTextBox.Text.Trim() + "', '" + prenumeTextBox.Text.Trim() + "', '" + dateTimePicker1.Value.ToShortDateString() + "', '" + textBox1.Text.Trim() + "', " + label5.Text + " , #Poza, " + textBox2.Text + ", " + textBox3.Text + ");";
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Salvat cu succes!");
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
numeTextBox.Clear();
prenumeTextBox.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
else
{
MessageBox.Show("Trebuie sa completezi campurile inainte de a salva!");
}
}
Here is how I update it:
private void button1_Click_1(object sender, EventArgs e)
{
//var connString = (#"Data Source= |DataDirectory|\Angajati.sdf");
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Angajati.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
SqlCeCommand cmd = new SqlCeCommand();
//conecteaza cmd la conn
cmd.Connection = conn;
//adauga parametru pt campul poza cu value image
SqlCeParameter picture = new SqlCeParameter("#Poza", SqlDbType.Image);
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] a = ms.GetBuffer();
ms.Close();
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Poza", a);
var query = "UPDATE info SET Nume='" + textBox5.Text + "' , Prenume='" + textBox4.Text + "' , Data='" + dateTimePicker1.Value.ToShortDateString() + "', Proiect='" + textBox1.Text + "', Schimburi='" + label10.Text + "', Poza=#Poza, Acord='" + textBox2.Text + "', Baza='" + textBox3.Text + "' WHERE Nume='" + textBox5.Text + "' AND Prenume='" + textBox4.Text + "'";
cmd.CommandText = query;
cmd.ExecuteNonQuery();
MessageBox.Show("Salvat cu succes!");
this.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
Here is how I search data:
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length != 0)
{
var numePrenume = textBox1.Text.Trim().Split(' ');
if (numePrenume.Count() > 1)
{
var nume = numePrenume[0];
var prenume = numePrenume[1];
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Angajati.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
var query = "SELECT COUNT(*) FROM info WHERE Nume='" + nume + "' AND Prenume='" + prenume + "'";
var command = new SqlCeCommand(query, conn);
var dataAdapter = new SqlCeDataAdapter(command);
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
//checks if there's the searched record is in the db.
int infoCount = (int)command.ExecuteScalar();
if (infoCount > 0)
{
Info form = new Info(nume, prenume);
form.Show();
}
else
{
MessageBox.Show("Nu exista un angajat cu acest nume");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
else
{
MessageBox.Show("Nu ai introdus prenumele");
}
}
else
{
MessageBox.Show("Nu ai introdus nici un nume!");
}
}

I have solved this problem by changing the path to the db, it was something wrong at it, and by creating a refresh function for my gridView called after the insert. Bellow is the code for the solution:
Getting the path like this now:
string startPath = Application.StartupPath;
var filepath = startPath + "\\" + "Grupe.sdf";
var connString = (#"Data Source=" + filepath +"");
The refresh function:
public void refresh()
{
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Grupe.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
var query = "SELECT * FROM copii";
var command = new SqlCeCommand(query, conn);
var dataAdapter = new SqlCeDataAdapter(command);
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
dataGridView1.DataSource = dataTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}

Related

Updating row in Gridview not saving to my database

I am trying to update the row in my GridView to my SQL table. But when I change some information and click on update it then does nothing, doesn't save it to the database?
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["PROJECTS"].ConnectionString);
DataTable dt = new DataTable();
con1.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand($"SELECT id, " +
$"Date, " +
$"Number, " +
$"CustomerName, " +
$"AccpacPcNo, " +
$"CRMCaseNo, " +
$"ProjectDetails, " +
$"TechnicalResourceAssigned," +
$"ProjectPhase, " +
$"WorkHours, " +
$"PlannedCompletionDate, " +
$"Comments FROM tbl_projects WHERE ID={Request["id"]}", con1);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
txtProjectDate.Text = (myReader["Date"].ToString());
txtProjectNumber.Text = (myReader["Number"].ToString());
txtProjectCustomerName.Text = (myReader["CustomerName"].ToString());
txtProjectAccpacNumber.Text = (myReader["AccpacPcNo"].ToString());
txtProjectCRMCaseNumber.Text = (myReader["CRMCaseNo"].ToString());
txtProjectDetails.Text = (myReader["ProjectDetails"].ToString());
txtProjectTechnicalResourceAssigned.Text = (myReader["TechnicalResourceAssigned"].ToString());
txtProjectPhase.SelectedItem.Text = (myReader["ProjectPhase"].ToString());
txtProjectWorkHours.Text = (myReader["WorkHours"].ToString());
txtProjectPlannedCompletionDate.Text = (myReader["PlannedCompletionDate"].ToString());
txtProjectComments.Text = (myReader["Comments"].ToString());
}
con1.Close();
}
protected void BtnUpdate_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["PROJECTS"].ConnectionString);
SqlCommand cmd = new SqlCommand($"UPDATE tbl_projects SET [Date] = #Date, " +
$"[Number] = #Number, " +
$"[CustomerName] = #CustomerName, " +
$"[AccpacPcNo] = #AccpacPcNo, " +
$"[CRMCaseNo] = #CRMCaseNo, " +
$"[ProjectDetails] = #ProjectDetails, " +
$"[TechnicalResourceAssigned] = #TechnicalResourceAssigned, " +
$"[ProjectPhase] = #ProjectPhase, " +
$"[WorkHours] = #WorkHours, " +
$"[PlannedCompletionDate] = #PlannedCompletionDate, " +
$"[Comments] = #Comments FROM tbl_Projects WHERE ID = {Request["id"]}", con);
con.Open();
cmd.Parameters.AddWithValue("#Date", txtProjectDate.Text);
cmd.Parameters.AddWithValue("#Number", txtProjectNumber.Text);
cmd.Parameters.AddWithValue("#CustomerName", txtProjectCustomerName.Text);
cmd.Parameters.AddWithValue("#AccpacPcNo", txtProjectAccpacNumber.Text);
cmd.Parameters.AddWithValue("#CRMCaseNo", txtProjectCRMCaseNumber.Text);
cmd.Parameters.AddWithValue("#ProjectDetails", txtProjectDetails.Text);
cmd.Parameters.AddWithValue("#TechnicalResourceAssigned", txtProjectTechnicalResourceAssigned.Text);
cmd.Parameters.AddWithValue("#ProjectPhase", txtProjectPhase.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#WorkHours", txtProjectWorkHours.Text);
cmd.Parameters.AddWithValue("#PlannedCompletionDate", txtProjectPlannedCompletionDate.Text);
cmd.Parameters.AddWithValue("#Comments", txtProjectComments.Text);
cmd.ExecuteNonQuery();
con.Close();
}
I am not sure what I am doing wrong? It displays the correct information when I click on the row to update but just doesn't want to update. I get no error messages or anything?
check this create gloabal variable that store Request ID then use ID in other Events or function.
private static string _REQID = "";
protected void Page_Load(object sender, EventArgs e)
{
_REQID = Request["id"];
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["PROJECTS"].ConnectionString);
DataTable dt = new DataTable();
con1.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand($"SELECT id, " +
$"Date, " +
$"Number, " +
$"CustomerName, " +
$"AccpacPcNo, " +
$"CRMCaseNo, " +
$"ProjectDetails, " +
$"TechnicalResourceAssigned," +
$"ProjectPhase, " +
$"WorkHours, " +
$"PlannedCompletionDate, " +
$"Comments FROM tbl_projects WHERE ID=#ReqID", con1);
myCommand.Parameters.AddWithValue("#ReqID", _REQID );
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
txtProjectDate.Text = (myReader["Date"].ToString());
txtProjectNumber.Text = (myReader["Number"].ToString());
txtProjectCustomerName.Text = (myReader["CustomerName"].ToString());
txtProjectAccpacNumber.Text = (myReader["AccpacPcNo"].ToString());
txtProjectCRMCaseNumber.Text = (myReader["CRMCaseNo"].ToString());
txtProjectDetails.Text = (myReader["ProjectDetails"].ToString());
txtProjectTechnicalResourceAssigned.Text = (myReader["TechnicalResourceAssigned"].ToString());
txtProjectPhase.SelectedItem.Text = (myReader["ProjectPhase"].ToString());
txtProjectWorkHours.Text = (myReader["WorkHours"].ToString());
txtProjectPlannedCompletionDate.Text = (myReader["PlannedCompletionDate"].ToString());
txtProjectComments.Text = (myReader["Comments"].ToString());
}
con1.Close();
}
protected void BtnUpdate_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["PROJECTS"].ConnectionString);
SqlCommand cmd = new SqlCommand($"UPDATE tbl_projects SET [Date] = #Date, " +
$"[Number] = #Number, " +
$"[CustomerName] = #CustomerName, " +
$"[AccpacPcNo] = #AccpacPcNo, " +
$"[CRMCaseNo] = #CRMCaseNo, " +
$"[ProjectDetails] = #ProjectDetails, " +
$"[TechnicalResourceAssigned] = #TechnicalResourceAssigned, " +
$"[ProjectPhase] = #ProjectPhase, " +
$"[WorkHours] = #WorkHours, " +
$"[PlannedCompletionDate] = #PlannedCompletionDate, " +
$"[Comments] = #Comments FROM tbl_Projects WHERE ID = #ReqID", con);
con.Open();
cmd.Parameters.AddWithValue("#Date", txtProjectDate.Text);
cmd.Parameters.AddWithValue("#Number", txtProjectNumber.Text);
cmd.Parameters.AddWithValue("#CustomerName", txtProjectCustomerName.Text);
cmd.Parameters.AddWithValue("#AccpacPcNo", txtProjectAccpacNumber.Text);
cmd.Parameters.AddWithValue("#CRMCaseNo", txtProjectCRMCaseNumber.Text);
cmd.Parameters.AddWithValue("#ProjectDetails", txtProjectDetails.Text);
cmd.Parameters.AddWithValue("#TechnicalResourceAssigned", txtProjectTechnicalResourceAssigned.Text);
cmd.Parameters.AddWithValue("#ProjectPhase", txtProjectPhase.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#WorkHours", txtProjectWorkHours.Text);
cmd.Parameters.AddWithValue("#PlannedCompletionDate", txtProjectPlannedCompletionDate.Text);
cmd.Parameters.AddWithValue("#Comments", txtProjectComments.Text);
cmd.Parameters.AddWithValue("#ReqID", _REQID);
cmd.ExecuteNonQuery();
con.Close();
}

Parameter is not valid Exception in windowsForm

i am using multi panels for making multi section project and using access database and inserting some thing in it like below:
private void addmoneyPanel_firstLoad()
{
try
{
employee_list.Items.Clear();
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select Ename,Elastname from employee";
OleDbDataReader reader = command.ExecuteReader();
while(reader.Read())
{
employee_list.Items.Add(reader[0].ToString() + " \n" +reader[1].ToString());
}
connection.Close();
/*addMoneyPanelMes.Text = "با موفقیت ذخیره شد.";
addMoneyPanelMes.ForeColor = Color.Green;*/
}
catch (Exception err)
{
addMoneyPanelMes.Text = "خظا در ارتباط با پایگاه داده.";
addMoneyPanelMes.ForeColor = Color.Red;
addMoneyPanelMes.Visible = true;
}
}
private void pictureBox1_Click_1(object sender, EventArgs e)
{
try
{
string TempPrice, TempCheckNum, TempCriditNum;
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
if(radioButton1.Checked == true)
{
TempPrice = money_price.Text;
TempCheckNum = "0";
TempCriditNum = "0";
}else if(radioButton2.Checked == true)
{
TempPrice = money_price.Text;
TempCheckNum = "0";
TempCriditNum = criditNumber.Text;
}
else
{
TempPrice = money_price.Text;
TempCheckNum = checkNumber.Text;
TempCriditNum = "0";
}
///////////////////////////////split the combo box names
string mainToSplit,id = "";
string[] splited;
mainToSplit = employee_list.SelectedItem.ToString();
splited = mainToSplit.Split('\n');
splited[0] = "" + splited[0].Remove((splited[0].Length-1),1);
command.CommandText = "select id from employee where Ename='" +splited[0]+ "' AND Elastname='" +splited[1]+"'";
OleDbDataReader reader = command.ExecuteReader();
if (reader.Read())
id = reader[0].ToString();
connection.Close();
connection.Open();
OleDbCommand command2 = new OleDbCommand();
command2.Connection = connection;
command2.CommandText = "INSERT INTO realMoney (price,cardnum,checknum,theDate,employeeid,descrip) values(" + Int32.Parse(TempPrice) + "," + Int32.Parse(TempCriditNum) + "," + Int32.Parse(TempCheckNum) + ",#" + dateTimePickerX1.GetSelectedDateInPersianDateTime().ToShortDateString() + "#," + Int32.Parse(id) + ",'" + money_descrip.Text + "')";
command2.ExecuteNonQuery();
connection.Close();
addMoneyPanelMes.Text = "با موفقیت ذخیره شد.";
addMoneyPanelMes.ForeColor = Color.Green;
addMoneyPanelMes.Visible = true;
}
catch(OleDbException h)
{
addMoneyPanelMes.Text = "خظا در ارتباط با پایگاه داده.";
addMoneyPanelMes.ForeColor = Color.Red;
addMoneyPanelMes.Visible = true;
}
}
this 2 function will be run successfully but after that i will get the "Parameter is not valid" Exception in this part:
private void timer1_Tick(object sender, EventArgs e)
{
if(pass == 0 || pass == 1)
{
prossespass();
}
DateTime datetime = DateTime.Now;
try
{
time.Text = string.Format("{0:hh:mm:ss}", DateTime.Now); // error here
timesun.Text = datetime.ToString("tt");
}
catch(Exception d)
{ }
}
this is a timer for a clock in my project. so after returning to the main panel that clock is existing in it (make the main panel visible and hide current panel) clock text box cant set and my project crashed.
i dont know what the problem is.
but if i erase this part from the second function that i mentioned:
addMoneyPanelMes.Text = "با موفقیت ذخیره شد.";
addMoneyPanelMes.ForeColor = Color.Green;
addMoneyPanelMes.Visible = true;
or removing insert section in second function above:
connection.Open();
OleDbCommand command2 = new OleDbCommand();
command2.Connection = connection;
command2.CommandText = "INSERT INTO realMoney (price,cardnum,checknum,theDate,employeeid,descrip) values(" + Int32.Parse(TempPrice) + "," + Int32.Parse(TempCriditNum) + "," + Int32.Parse(TempCheckNum) + ",#" + dateTimePickerX1.GetSelectedDateInPersianDateTime().ToShortDateString() + "#," + Int32.Parse(id) + ",'" + money_descrip.Text + "')";
command2.ExecuteNonQuery();
connection.Close();
i have other function in other panels that work with database but work great together this is it. thanks for your help.
just turn the timer off:
timer1.Enabled = false;
when enter to each panel and turn it on when come back to main panel:
timer1.Enabled = true;

Connection was not closed. The connection's current state is open

How to fix this problem? I don't know why this error occur when I already add Clode().
The error will go here:
public void existType()
{
try
{
con.Open();
string existquery = "SELECT*FROM tblRoomType WHERE Type = '" + txtRoomType.Text + "'";
da = new OleDbDataAdapter(existquery, con);
da.Fill(ds, "tblRoomType");
int counter = 0;
string tabletype = "tblRoomType";
if (counter < ds.Tables[tabletype].Rows.Count)
{
string type = ds.Tables[tabletype].Rows[counter]["Type"].ToString();
if (type == txtRoomType.Text)
{
editRoomType(); //There will be no error if I remove this and include the MessageBox below.
MessageBox.Show("Successfully Edited", "SUCCESS", MessageBoxButtons.OK, MessageBoxIcon.Information);
//MessageBox.Show("This " + txtRoomType.Text + " is already exist.", "EXIST", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else //Remove this will remove the error
{
addRoomType();
MessageBox.Show("Successfully Added", "SUCCESS", MessageBoxButtons.OK, MessageBoxIcon.Information);
}//to here
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This are the code of editRoomType() and addRoomType():
public void addRoomType()
{
con.Open();
string addtypequery = "INSERT INTO tblRoomType VALUES ('" + this.typeid + "','" + txtRoomType.Text + "','" + txtRoomRate.Text + "','" + txtExtraCharge.Text + "','" + txtCancelFee.Text + "','" + txtMaxOcc.Text + "')";
cmd = new OleDbCommand(addtypequery, con);
cmd.ExecuteNonQuery();
con.Close();
loadRoomType();
txtRoomType.ReadOnly = false;
txtRoomType.Enabled = false;
txtRoomRate.Enabled = false;
txtMaxOcc.Enabled = false;
txtExtraCharge.Enabled = false;
txtCancelFee.Enabled = false;
btnAddRoomType.Enabled = false;
txtRoomType.Clear();
txtRoomRate.Clear();
txtMaxOcc.Clear();
txtExtraCharge.Clear();
txtCancelFee.Clear();
}
public void editRoomType()
{
con.Open();
string edittypequery = "UPDATE tblRoomType SET Rate = '" + txtRoomRate.Text + "', ExtraCharge = '" + txtExtraCharge.Text + "', CancelFee = '" + txtCancelFee.Text + "', MaxOcc = '" + txtMaxOcc.Text + "' WHERE TypeID = '" + txtRoomType.Text + "'";
cmd = new OleDbCommand(edittypequery, con);
cmd.ExecuteNonQuery();
con.Close();
}
The existType() will be go here:
private void btnAddRoomType_Click(object sender, EventArgs e)
{
if (txtRoomType.Text != "" || txtRoomRate.Text != "" || txtExtraCharge.Text != "" || txtCancelFee.Text != "" || txtMaxOcc.Text != "")
{
existType();
}
else
{
MessageBox.Show("Please fill in the space provided","OOPPSS!!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
The error is because you call con.Open in existType, then you either call addRoomType or editRoomType, both of which call con.Open again before you call con.Close in existType. Calling con.Open on an already open connection will throw the error you are seeing.
You can either remove the calls to con.Open/con.Close inside of the addRoomType or editRoomType and only call them in existType, or use local connections for each method, like so:
public void existType()
{
try
{
using (var conn = new SqlConnection())
{
conn.Open();
string existquery = "SELECT*FROM tblRoomType WHERE Type = '" + txtRoomType.Text + "'";
da = new OleDbDataAdapter(existquery, conn);
da.Fill(ds, "tblRoomType");
}
//rest of code
}
}
public void editRoomType()
{
using (var conn = new SqlConnection())
{
conn.Open();
string edittypequery = "UPDATE tblRoomType SET Rate = '" + txtRoomRate.Text + "', ExtraCharge = '" + txtExtraCharge.Text + "', CancelFee = '" + txtCancelFee.Text + "', MaxOcc = '" + txtMaxOcc.Text + "' WHERE TypeID = '" + txtRoomType.Text + "'";
cmd = new OleDbCommand(edittypequery, conn);
cmd.ExecuteNonQuery();
}
}
Note that you don't have to call Close since the using statement will do that for you.
Try like this -
try
{
con.Open();
.......
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Open();
}
}

Ozeki is not returning other records

I'm doing an Ozeki Messenger Project using C#. I want to retrieve more than one record from the table. Its returning me the first record only...
Here's my code. Any Idea what am doing wrong guys?
protected void Page_Load(object sender, EventArgs e)
{
try
{
String x;
String y;
String z;
String SenderNumber, receiverNumber, message;
SenderNumber = Request.QueryString.Get("sender");
receiverNumber = Request.QueryString.Get("receiver");
message = Request.QueryString.Get("msg");
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
SqlDataReader reader;
connection.ConnectionString = Constring;
command.Connection = connection;
command.CommandText = "SELECT P_Name, P_Parking FROM tblPharmacy Where Code = '" + message + "'" ;
connection.Open();
reader = command.ExecuteReader();
String data = "";
while (reader.Read())
{
x = reader["P_Name"].ToString();
y = reader["P_Parking"].ToString();
data += x + " " + y + " - ";
Response.Redirect("http://localhost:9333/ozeki?login=admin&password=xxxxxx&action=sendMessage&messagetype=SMS:TEXT&recepient=" + SenderNumber + " &messageData= " + data);
}
reader.Close();
connection.Close();
}
catch (Exception)
{
}
}
protected void Page_Load(object sender, EventArgs e)
{
try
{
String x;
String y;
String z;
String SenderNumber, receiverNumber, message;
SenderNumber = Request.QueryString.Get("sender");
receiverNumber = Request.QueryString.Get("receiver");
message = Request.QueryString.Get("msg");
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
SqlDataReader reader;
connection.ConnectionString = Constring;
command.Connection = connection;
command.CommandText = "SELECT P_Name, P_Parking FROM tblPharmacy Where Code = '" + message + "'" ;
connection.Open();
reader = command.ExecuteReader();
String data = "";
while (reader.Read())
{
x = reader["P_Name"].ToString();
y = reader["P_Parking"].ToString();
data += x + " " + y + " - ";
}
Response.Redirect("http://localhost:9333/ozeki?login=admin&password=xxxxxx&action=sendMessage&messagetype=SMS:TEXT&recepient=" + SenderNumber + " &messageData= " + data);
reader.Close();
connection.Close();
}
catch (Exception)
{
}
}
I got The Answer Myself.. LOL. The Response.Redirect should be outside the While Loop. It Works Just fine :D

Everything freezes when closing or disposing a reader

I'm having an issue with either the reader being open when I try to use the same connection to add data to the database OR closing or disposing the reader and having the program freeze.
If you don't understand what i'm trying to explain, please ask questions. I'm a bit confused by the whole thing so I might be making 0 sense.
Code:
private void btnRegister_Click(object sender, EventArgs e)
{
int numerror = 0;
if (RUsernameTextBox.Text == "")
{
numerror++;
}
if (RPasswordTextBox.Text == "")
{
numerror++;
}
if (REmailTextBox.Text == "")
{
numerror++;
}
if (numerror > 0)
{
ErrorLabel.Text = "*" + numerror + " required field" + (numerror != 1 ? "s are" : " is") + " blank.";
}
else
{
var constring = "datasource=localhost;port=3306;username=Admin;password=**********;";
using (var con = new MySqlConnection(constring))
{
con.Open();
var cmd0 = new MySqlCommand("select username from userinfo.users where username=#username");
cmd0.CommandType = CommandType.Text;
cmd0.Connection = con;
cmd0.Parameters.AddWithValue("#username", RUsernameTextBox.Text);
using (var reader = cmd0.ExecuteReader())
{
if (reader.HasRows)
{
CMessageBox("Error", "Username is already in use.");
reader.Close();
}
else
{
reader.Close();
var HashedPassword = EncodePassword(RPasswordTextBox.Text);
var cmd = new MySqlCommand("INSERT INTO userinfo.users (username,password,email,premium,picture) VALUES (#username, #hashedpassword, #email , #premium , #picture);");
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Username", RUsernameTextBox.Text);
cmd.Parameters.AddWithValue("#hashedpassword", HashedPassword);
cmd.Parameters.AddWithValue("#email", REmailTextBox.Text);
cmd.Parameters.AddWithValue("#premium", "0");
cmd.Parameters.AddWithValue("#picture", "ftp://***.***.*.**/Profile Pictures/" + RUsernameTextBox.Text + "/" + Path.GetFileNameWithoutExtension(RProfilePicture.ImageLocation) + ".png");
try
{
cmd.ExecuteNonQuery();
MakeLoginVisible();
var TempFolder = Path.GetTempPath();
RProfilePicture.Image.Save("C:\\temp\\" + Path.GetFileNameWithoutExtension(RProfilePicture.ImageLocation) + ".png", System.Drawing.Imaging.ImageFormat.Png);
var ftpclient = new ftp("ftp://***.***.*.**/", "Admin", "**********");
ftpclient.createDirectory("Profile Pictures/" + RUsernameTextBox.Text);
ftpclient.upload("Profile Pictures/" + RUsernameTextBox.Text + "/" + Path.GetFileNameWithoutExtension(RProfilePicture.ImageLocation) + ".png", "C:\\temp\\" + Path.GetFileNameWithoutExtension(RProfilePicture.ImageLocation) + ".png");
MakeLoginVisible();
CMessageBox("Success!", "AirSpace Account '" + RUsernameTextBox.Text + "' Created.");
ftpclient = null;
con.Close();
}
catch (Exception ex)
{
CMessageBox("Error", ex.Message.ToString());
}
}
}
}
}
}
using (var con = new MySqlConnection(constring))
using(var cmd0 = new MySqlCommand("Select count(*) from userinfo.users where username=#username", con))
{
con.Open();
cmd0.Parameters.AddWithValue("#username", RUsernameTextBox.Text);
if((int)cmd0.ExecuteScalar() > 0)
{
CMessageBox("Error", "Username is already in use.");
return;
}
}
using (var con = new MySqlConnection(constring))
using(var cmd= new MySqlCommand("INSERT INTO userinfo.users (username,password,email,premium,picture) VALUES (#username, #hashedpassword, #email , #premium , #picture)", con))
{
con.Open();
var HashedPassword = EncodePassword(RPasswordTextBox.Text);
cmd.Parameters.AddWithValue("#Username", RUsernameTextBox.Text);
cmd.Parameters.AddWithValue("#hashedpassword", HashedPassword);
cmd.Parameters.AddWithValue("#email", REmailTextBox.Text);
cmd.Parameters.AddWithValue("#premium", "0");
cmd.Parameters.AddWithValue("#picture", "ftp://***.***.*.**/Profile Pictures/" + RUsernameTextBox.Text + "/" + Path.GetFileNameWithoutExtension(RProfilePicture.ImageLocation) + ".png");
try
{
cmd.ExecuteNonQuery();
MakeLoginVisible();
var TempFolder = Path.GetTempPath();
RProfilePicture.Image.Save("C:\\temp\\" + Path.GetFileNameWithoutExtension(RProfilePicture.ImageLocation) + ".png", System.Drawing.Imaging.ImageFormat.Png);
var ftpclient = new ftp("ftp://***.***.*.**/", "Admin", "**********");
ftpclient.createDirectory("Profile Pictures/" + RUsernameTextBox.Text);
ftpclient.upload("Profile Pictures/" + RUsernameTextBox.Text + "/" + Path.GetFileNameWithoutExtension(RProfilePicture.ImageLocation) + ".png", "C:\\temp\\" + Path.GetFileNameWithoutExtension(RProfilePicture.ImageLocation) + ".png");
MakeLoginVisible();
CMessageBox("Success!", "AirSpace Account '" + RUsernameTextBox.Text + "' Created.");
ftpclient = null;
}
catch (Exception ex)
{
CMessageBox("Error", ex.Message.ToString());
}
}
You don't really need a reader in this case. You can just get the count in your query and use ExecuteScalar()
var cmd0 = new MySqlCommand("select count(*) from userinfo.users where username=#username");
cmd0.CommandType = CommandType.Text;
cmd0.Connection = con;
cmd0.Parameters.AddWithValue("#username", RUsernameTextBox.Text);
if (((int)cmd0.ExecuteScalar()) > 0)
CMessageBox("Error", "Username is already in use.");
else
... the rest of the code

Categories