Hello I'm practicing on typing codes of inventory system of products for the pos software.
I'm working on something like here:
Click here to see my products of inventory sketch.
And after a click on the save button for the results of the database then it should show up like the "record added...." window. And I don't see the result even I don't see any error on my visual studio pro software.
And please let me know which part is wrong and how to fix that.
Here is my code of salesn.cs file
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace superpos3
{
public partial class salesn : Form
{
public salesn()
{
InitializeComponent();
}
int totalPrice = 0;
MySqlConnection con = new MySqlConnection("server= localhost; database =superpos; username= root; password=; ");
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void txtno_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
txtqty.Enabled = true;
txtqty.Focus();
}
}
private void txtqty_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
try
{
string txt = "select * from products where id='" + txtno.Text + "'";
MySqlCommand cmd = new MySqlCommand(txt, con);
con.Open();
MySqlDataReader r = cmd.ExecuteReader();
while (r.Read())
{
int price = int.Parse(txtqty.Text.ToString()) * int.Parse(r[4].ToString());
totalPrice = totalPrice + price;
//discount
// totalPrice = totalPrice - totalPrice* Payment.discount/100;
dataGridView1.Rows.Add(dataGridView1.RowCount, r[0], r[1], txtqty.Text.Trim(), r[4], price);
}
lbitems.Text = " " + (dataGridView1.RowCount - 1) + "";
lbtotal.Text = " " + totalPrice + " ";
con.Close();
}
catch (Exception ee)
{
MessageBox.Show(ee.Message, "Error From Database");
}
txtno.Focus();
txtno.Clear();
txtqty.Enabled = false;
txtqty.Clear();
}
}
private void txtqty_TextChanged(object sender, EventArgs e)
{
}
private void salesn_Load(object sender, EventArgs e)
{
lbldate.Text = DateTime.Today.ToString("dd/MM/yyyy");
lbltime.Text = DateTime.Now.ToShortTimeString();
con.Open();
string query = "select max(id) from salesmain ";
MySqlCommand cmd2 = new MySqlCommand(query, con);
MySqlDataReader dr;
dr = cmd2.ExecuteReader();
if (dr.Read())
{
string val = dr[0].ToString();
if (val == "")
{
lbinvoice.Text = "1";
}
else
{
int a;
a = int.Parse(dr[0].ToString());
a = a + 1;
lbinvoice.Text = a.ToString();
}
con.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = con;
cmd.CommandText = "Insert into salesproducts(saleid,productname,qty,price,grosstotal)values(#salesid,#productname,#qty,#price,#grosstotal)";
cmd.Parameters.AddWithValue("#saleid", lbinvoice.Text);
cmd.Parameters.AddWithValue("#productname", dataGridView1.Rows[i].Cells[2].Value);
cmd.Parameters.AddWithValue("#qty", dataGridView1.Rows[i].Cells[3].Value);
cmd.Parameters.AddWithValue("#price", dataGridView1.Rows[i].Cells[4].Value);
cmd.Parameters.AddWithValue("#grosstotal", dataGridView1.Rows[i].Cells[5].Value);
MySqlCommand cmd1 = new MySqlCommand();
cmd1.Connection = con;
cmd1.CommandText = "insert into salesmain(id,date,time,qty,grosstotal)values(#id,#date,#time,#qty,#grosstotal)";
cmd1.Parameters.AddWithValue("#id", lbinvoice.Text);
cmd1.Parameters.AddWithValue("#date", lbldate.Text);
cmd1.Parameters.AddWithValue("#time", lbltime.Text);
cmd1.Parameters.AddWithValue("#qty", lbitems.Text);
cmd1.Parameters.AddWithValue("#grosstotal", lbtotal.Text);
con.Open();
cmd.ExecuteNonQuery();
cmd1.ExecuteNonQuery();
MessageBox.Show("Record added ..........");
con.Close();
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
}
}
I guess you should check if the dataGridView1.Rows.Count is not zero because if it is, the for loop won't even run which means that neither your code nor the message box show method is gonna run.
the other MessageBox.Show() methods are inside catch blocks which obviously means that they won't run if the catch block doesn't catch any errors.
Related
I am using winform C#,
database name "School"
my "fees" table has 2 columns,
stu_id,fees
The issue I am facing is that it adds multiple (same) entries into the database instead of single.
I have code on other forms but I don't know why is this happening here, any help would be appreciated.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace SchoolManagementSystem
{
public partial class Fees : Form
{
public Fees()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=DRAGON\SQLEXPRESS;Initial Catalog=School;Integrated Security=True;");
con.Open();
try
{
string str = " INSERT INTO fees VALUES('" + textBox1.Text + "','" + textBox2.Text + "')";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
MessageBox.Show("Your Fees Submitted..");
this.Hide();
Home obj2 = new Home();
obj2.ShowDialog();
}
this.Close();
}
catch (SqlException excep)
{
MessageBox.Show(excep.Message);
}
con.Close();
}
private void textBox1_MouseLeave(object sender, EventArgs e)
{
textBox2.Text = "";
SqlConnection con = new SqlConnection(#"Data Source=DRAGON\SQLEXPRESS;Initial Catalog=School;Integrated Security=True;");
con.Open();
if (textBox1.Text != "")
{
try
{
string getCust = "select name,standard,medium from student where std_id=" + Convert.ToInt32(textBox1.Text) + " ;"; // saving new custmer info
SqlCommand cmd = new SqlCommand(getCust, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.Read())
{
label9.Text = dr.GetValue(0).ToString();
label6.Text = dr.GetValue(1).ToString();
label7.Text = dr.GetValue(2).ToString();
}
else
{
MessageBox.Show("Sorry '" + textBox1.Text + "' This Registration Id is Invalid, Please Insert Correct Id");
textBox1.Text = "";
textBox2.Text = "";
}
}
catch (SqlException excep)
{
MessageBox.Show(excep.Message);
}
con.Close();
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void Fees_Load(object sender, EventArgs e)
{
}
}
}
when I enter fees from front end, it adds same 2 rows into database instead of 1.
Because you're executing your INSERT statement twice:
cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
Why? Why do you even need the SqlDataReader? Just execute the INSERT once:
cmd.ExecuteNonQuery();
MessageBox.Show("Your Fees Submitted..");
If you want to confirm that a row was inserted, ExecuteNonQuery returns the number of rows affected:
var rows = cmd.ExecuteNonQuery();
if (rows != 1)
{
// handle error
}
else
{
MessageBox.Show("Your Fees Submitted..");
}
You are executing the command twice here:
cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
Why are you calling ExecuteReader when there's nothing to read? ExecuteReader is for when you execute a SELECT statement with multiple columns and/or multiple rows and you want to read the result set. For an INSERT statement, you only need to call ExecuteNonQuery... because it's not a query.
I wrote a code for my pleasure.
i have access data file "mdb" and i show him on gridview from gridview i select row and shown on text box.
i edit the textbox and try to press on Save button and show me error msg.
what i do wrong?
save button didnt save and show me error msg.
add pictures and my code:
Error msg
gridview+textbox
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Center image description hereDHW
{
public partial class Form2 : Form
{
private OleDbConnection connection = new OleDbConnection();
public Form2()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\Users\RBA\Desktop\123\users1.mdb;
Persist Security Info=False;";
}
private void button9_Click(object sender, EventArgs e)
{
this.Close();
Form1 f1 = new Form1();
f1.Show();
}
private void btn_save_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into GRL1 (NoBoard,Site,Group,Kind,Unit) values ('" + txt_noboard.Text + "','" + txt_site.Text + "','" + txt_group.Text + "','" + txt_kind.Text + "','" + txt_unit.Text + "',)";
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
private void Form2_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'users1DataSet.GRL1' table. You can move, or remove it, as needed.
this.gRL1TableAdapter.Fill(this.users1DataSet.GRL1);
}
private void btn_loadGR_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from GRL1";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
private void button3_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from GRS1";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
txt_noboard.Text = row.Cells[0].Value.ToString();
txt_site.Text = row.Cells[1].Value.ToString();
txt_group.Text = row.Cells[2].Value.ToString();
txt_kind.Text = row.Cells[3].Value.ToString();
txt_unit.Text = row.Cells[4].Value.ToString();
txt_com.Text = row.Cells[5].Value.ToString();
}
}
}
}
You have a typo in your sql text. There is a comma before the close brace. But there is also an error caused by the usage of a reserved keyword in MS-Access (Group). You need to put square brackets around that name.
Finally, do not use string concatenation to build sql commands but always use parameters.
This avoid sql injection hacks and remove problem with parsing your inputs (for example if there is a single quote in your input text the whole query will fail again with a syntax error)
private void btn_save_Click(object sender, EventArgs e)
{
try
{
using(OleDbConnection connection = new OleDbConnection(....con string...))
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
// Notice how Group field is between square brackets.
// If you can I suggest to change the name of this field
string cmdText = #"insert into GRL1 (NoBoard,Site,[Group],Kind,Unit)
values (#nob, #sit, #grp, #knd, #uni)";
command.CommandText = cmdText;
// Is NoBoard an integer? If yes you should pass an integer not a string
command.Parameters.Add("#nob", OleDbType.Integer).Value = Convert.ToInt32(txt_noboard.Text);
command.Parameters.Add("#sit", OleDbType.VarWChar).Value = txt_site.Text;
command.Parameters.Add("#grp", OleDbType.VarWChar).Value = txt_group.Text;
command.Parameters.Add("#knd", OleDbType.VarWChar).Value = txt_kind.Text;
command.Parameters.Add("#uni", OleDbType.VarWChar).Value = txt_unit.Text;
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
}
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
The parameters collection is filled with the values required by your query text. Notice that I don't know exactly the datatype of your columns in the database. The parameter OleDbType should exactly match the types expected to avoid Type Mismatch exceptions
Last tip. Connections should be created, opened and closed when needed. Do not keep a global connection object. You don't get much gain in performance because ADO.NET employs a technique called Connection Pooling
May I ask, how can I get error for this? It is so confusing. I get bug like this and I try to fix, but it does not work at all. I'm just a beginner.
namespace WindowsFormsApp1
{
public partial class Schedule : Form
{
public Schedule()
{
InitializeComponent();
}
MySqlConnection con = new MySqlConnection(#"Data Source=localhost;port=3306;Initial Catalog=Payroll;User Id=root;password=''");
MySqlDataReader dr;
int tc = 0;
private void Schedule_Load(object sender, EventArgs e)
{
datagrid();
fillsched();
}
public void datagrid()
{
con.Open();
MySqlDataAdapter sda = new MySqlDataAdapter("Select * from employee where Pstatus='Active'", con);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
con.Close();
}
public void fillsched()
{
con.Open();
MySqlDataReader dr;
MySqlCommand cmd = new MySqlCommand("select * from updateschedule ", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
int data = dr.GetInt32("empSched");
comboBox1.Items.Add(data);
}
con.Close();
}
public void getsched()
{
if (Int32.TryParse(comboBox1.SelectedItem.ToString(), out tc))
{
con.Open();
MySqlCommand cmd = new MySqlCommand("select * from updateschedule where empSched=#empSched ", con);
cmd.Parameters.Add("#empSched", MySqlDbType.Int32).Value = tc;
dr = cmd.ExecuteReader();
if (dr.Read())
{
textBox2.Text = dr["TimeIn"].ToString();
textBox3.Text = dr["TimeOut"].ToString();
label5.Text = tc.ToString();//to pass the data in the combobox1
}
con.Close();
}
}
public void view()
{
textBox1.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
getsched();
}
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex >= 0)
{
view();
}
}
private void button1_Click(object sender, EventArgs e)
{
insert();
insertempsched();
}
public void insert()
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO schedule (empSchedID,empID,empIN,empOut)VALUES(#empSchedID,#empID,#empIn,#EmpOut)", con);
cmd.Parameters.Add("#empSchedID", MySqlDbType.Int32).Value = label5.Text;
cmd.Parameters.Add("#empID", MySqlDbType.VarChar).Value = textBox1.Text;
cmd.Parameters.Add("#empIn", MySqlDbType.Date).Value = textBox2.Text;
cmd.Parameters.Add("#empOut", MySqlDbType.VarChar).Value = textBox3.Text;
execnonquery(cmd, "Data Inserted");
}
public void insertempsched()
{
con.Open();
MySqlCommand cmd = new MySqlCommand("Update employee set empSched=empSched where empID=#empID", con);
cmd.Parameters.Add("#empSchedID", MySqlDbType.Int32).Value = label5.Text;
cmd.Parameters.Add("#empID", MySqlDbType.VarChar).Value = textBox1.Text;
cmd.ExecuteNonQuery();
con.Close();
}
public void execnonquery(MySqlCommand sqc, string mymsg)
{
con.Open();
if (sqc.ExecuteNonQuery() == 1)
{
MessageBox.Show(mymsg);
}
else
{
MessageBox.Show("Query not Executed");
}
con.Close();
}
}
}
"Index was outside the bounds of the array" in c# always indicates that you are trying to get values based on column index number or row index number from datagrid or datatables or arrays and column or row does not exist at that position or index.
I think you are getting error at following line which exists in "view" method.
textBox1.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
Also to catch the errors it's a good practice to use try catch blocks in all the methods.
You can modify your method like this
public void view()
{
try
{
textBox1.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am new on c# and i am facing problem. i made two buttons, one for case another for credit card. when i click on button, my data is not inserting into ms access file.why is it not showing any error and how can i fix it ?
private void CashButton_Click(object sender, EventArgs e)
{
SaveOrder((int)PaymentTypes.Cash);
}
private void CreditCardButton_Click(object sender, EventArgs e)
{
SaveOrder((int)PaymentTypes.CreditCard);
}
private void SaveOrder(int paymentType)
{
try
{
string connstring = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand("INSERT INTO [Orders](OrderNummber,TransactionDate,ClientName,TotalAmount,PaymentType) VALUES(#OrderNummber,#TransactionDate,#ClientName,#TotalAmount,#PaymentType)",conn))
{
cmd.Parameters.AddWithValue("#OrderNummber",OrderNumberTextBox.Text);
cmd.Parameters.AddWithValue("#TransactionDate",TransactionDateDateTimePicker.Value.Date);
cmd.Parameters.AddWithValue("#ClientName",ClientNameTextBox.Text);
cmd.Parameters.AddWithValue("#TotalAmount",Convert.ToDecimal(TotalAmountTextBox.Text));
cmd.Parameters.AddWithValue("#PaymentType", paymentType);
cmd.ExecuteNonQuery();
}
foreach (DataGridViewRow row in CartDataGridView.Rows)
{
using (OleDbCommand cmd = new OleDbCommand("INSERT INTO [OrdersItems](OrderNumber,Quantity,UnitPrice,TotalPrice) VALUES(#OrderNumber,#Quantity,#UnitPrice,#TotalPrice)", conn))
{
cmd.Parameters.AddWithValue("#OrderNumber", OrderNumberTextBox.Text);
cmd.Parameters.AddWithValue("#Quantity", Convert.ToInt16(row.Cells["Quantity"].Value));
cmd.Parameters.AddWithValue("#UnitPrice",Convert.ToDecimal(row.Cells["UnitPrice"].Value));
cmd.Parameters.AddWithValue("#TotalPrice", Convert.ToDecimal(row.Cells["TotalPrice"].Value));
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("Order is processed successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
}
}
Do it like this.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind.mdb";
string fstName = textBox1.Text.Trim();
string lstName = textBox2.Text.Trim();
string adres = textBox3.Text.Trim();
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO MyExcelTable (FName, LName, Address) VALUES (#FName, #LName, #Address)")
{
Connection = conn
};
conn.Open();
if (conn.State == ConnectionState.Open)
{
// you should always use parameterized queries to avoid SQL Injection
cmd.Parameters.Add("#FName", OleDbType.VarChar).Value = fstName;
cmd.Parameters.Add("#LName", OleDbType.VarChar).Value = lstName;
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = adres;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show(#"Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source + "\n" + ex.Message);
conn.Close();
}
}
else
{
MessageBox.Show(#"Connection Failed");
}
}
}
}
This will definitely work. Just change the connection string and the variables to suit your needs.
Hello Friends i am trying to develop a shout box in asp.net but it ends with an error The connection was not closed. The connection's current state is open. Can you please help me out what is the problem in my code .
Shout.aspx.cs
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace finalWork
{
public partial class Shout : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateTextBox();
}
}
private void PopulateTextBox()
{
SqlConnection con = ConnectionManager.GetDatabaseConnection();
DataTable dt = new DataTable();
string name = string.Empty, message = string.Empty;
StringBuilder sb = new StringBuilder(string.Empty);
try
{
con.Open();
string sqlStatement = "SELECT * FROM Message";
SqlCommand cmd = new SqlCommand(sqlStatement, con);
SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
//get the data stored from the DataTable
name = dt.Rows[i]["Username"].ToString();// where Name is the FieldName from database
message = dt.Rows[i]["Message"].ToString();
sb.AppendFormat("Name:{0}Date Posted:{1}{2}", name + Environment.NewLine
, DateTime.Now.ToShortDateString() + Environment.NewLine
, message + Environment.NewLine);
}
// get the concated and formatted values from string builder and display the result in TextBoxPrintMessage
TextBoxPrintMessage.Text = sb.ToString();
}
con.Close();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
con.Close();
}
}
private void AddNewPost(string name, string message)
{
SqlConnection con = ConnectionManager.GetDatabaseConnection();
string sqlStatement = string.Empty;
sqlStatement = "INSERT INTO Message" +
"(Username,Message)" +
"VALUES (#Username,#Message)";
try
{
con.Open();
SqlCommand cmd = new SqlCommand(sqlStatement, con);
cmd.Parameters.AddWithValue("#Username", name);
cmd.Parameters.AddWithValue("#Message", message);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
con.Close();
}
}
protected void ButtonPost_Click(object sender, EventArgs e)
{
// Check for empty values fieds before inserting the record
if (TextBoxName.Text != string.Empty && TextBoxMessage.Text != string.Empty)
{
//insert new post to database
AddNewPost(TextBoxName.Text.Trim(), TextBoxMessage.Text.Trim());
//Populate the TextBox to reflect changes made
PopulateTextBox();
}
else
{
//display message if the field was not supplied
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Script",
"alert('Please supply the required fields!');", true);
}
}
}
}
I just manually add it and it works :)
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
Add comment to following code its already called in finally block of PopulateTextBox() function.
//con.Close();
Remove con.Close(); inside Try block as you have used it in finally block.
Try This way. It will help you.
SqlConnection connection = new SqlConnection(youCconnectionString);
connection.Close();
connection.Open();
SqlCommand command = new SqlCommand("YourQuery", connection);
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
connection.Close();
command.Dispose();