Execute command inside datareader c# - c#

I have a button click function which runs a stored procedure.
The stored procedure returns data. After execution depend upon the datareader output another command needs to be executed.
using (SqlDataReader oReader = command.ExecuteReader())
{
while (oReader.Read())
{
if (oReader["comments1"].ToString() == "0")
{
MessageBox.Show("CHECK THE COMMENTS AND THE GIVEN VALUE");
;
}
else
{
command.ExecuteNonQuery();
MessageBox.Show("Inserted data");
ClearTextBoxes(this);
button2.Enabled = false;
}
}
}
There is already an open DataReader associated with this Command which
must be closed first
I know that im trying to use same connection for reading and also for writing the data in the table.
Whether there is any other approach to solve the given problem.
Entire Function:
private void button2_Click(object sender, EventArgs e)
{
var connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var command = new SqlCommand(#"[lis1].[_Submit_test]", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Date", SqlDbType.Date).Value = textBox1.Text;
command.Parameters.Add("#Username", SqlDbType.VarChar).Value = textBox11.Text;
command.Parameters.Add("#workflow", SqlDbType.VarChar).Value = comboBox2.Text;
command.Parameters.Add("#program", SqlDbType.VarChar).Value = comboBox1.Text;
command.Parameters.Add("#Full_Denial", SqlDbType.Int).Value = textBox2.Text;
command.Parameters.Add("#Partial_Denial", SqlDbType.Int).Value = textBox3.Text;
command.Parameters.Add("#No_Findings", SqlDbType.Int).Value = textBox4.Text;
command.Parameters.Add("#Rejections", SqlDbType.Int).Value = textBox5.Text;
command.Parameters.Add("#Unfulfilled", SqlDbType.Int).Value = textBox6.Text;
command.Parameters.Add("#TargetPerDay", SqlDbType.Int).Value = textBox7.Text;
command.Parameters.Add("#Audits_Assigned", SqlDbType.Int).Value = textBox10.Text;
command.Parameters.Add("#Total_Audits_Reviewed", SqlDbType.Int).Value = textBox12.Text;
command.Parameters.Add("#Audits_Carry_Forward", SqlDbType.Int).Value = textBox8.Text;
command.Parameters.Add("#Pending_Audits", SqlDbType.Int).Value = textBox9.Text;
command.Parameters.Add("#Comments", SqlDbType.VarChar).Value = comboBox3.Text;
SqlParameter returnParameter = command.Parameters.Add("RetVal", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
using (SqlDataReader oReader = command.ExecuteReader())
{
while (oReader.Read())
{
if (oReader["comments1"].ToString() == "0")
{
MessageBox.Show("CHECK THE COMMENTS AND THE GIVEN VALUE");
}
else
{
command.ExecuteNonQuery();
MessageBox.Show("Inserted data");
ClearTextBoxes(this);
button2.Enabled = false;
}
}
}
}
}
}

I tried to execute same command using command.ExecuteReader() and using command.ExecuteNonQuery() after i removed the command.ExecuteNonQuery(). Everything works as i expected.
using (SqlDataReader oReader = command.ExecuteReader())
{
while (oReader.Read())
{
if (oReader["comments1"].ToString() == "0")
{
MessageBox.Show("CHECK THE COMMENTS AND THE GIVEN VALUE");
;
}
else
{
MessageBox.Show("Inserted");
ClearTextBoxes(this);
button2.Enabled = false;
}
}

Related

How to perform custom CRUD operations on an asp Gridview using C#

This is not a question but a solution since I spent a lot of time figuring it out.
Use the onInsert, OnUpdating, OnDeleting events **I used a Datasource for the Populating the grid so that my fields are editable.
2.Row inserting
{
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "spINSERTtblPARfinancialPropotions";
cmd.Parameters.Add("#financialPropotionsPercentageType", SqlDbType.NVarChar).Value = e.NewValues["financialPropotionsPercentageType"].ToString();
cmd.Parameters.Add("#financialPropotionsPercentage", SqlDbType.NVarChar).Value = Convert.ToDecimal(e.NewValues["financialPropotionsPercentage"]);
cmd.Connection = con;
try
{
con.Open();
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
e.Cancel = true;
grid1.CancelEdit();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}```
3.Row Updating
{
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "spUPDATEtblPARfinancialPropotions";
/// cmd.Parameters.Add("#TestConfigId", SqlDbType.Int).Value = Convert.ToInt32(e.NewValues["TestConfigId"]);
//cmd.Parameters.Add("#ServiceId", SqlDbType.Int).Value = Convert.ToInt32(_serviceId);
//cmd.Parameters.Add("#ParentTest", SqlDbType.NVarChar).Value = ddlService.SelectedItem.Text.Trim();
// cmd.Parameters.Add("#MainTest", SqlDbType.NVarChar).Value = e.NewValues["MainTest"].ToString();
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = e.OldValues["ID"];
cmd.Parameters.Add("#financialPropotionsPercentageType", SqlDbType.NVarChar).Value = e.NewValues["financialPropotionsPercentageType"].ToString();
cmd.Parameters.Add("#financialPropotionsPercentage", SqlDbType.NVarChar).Value = Convert.ToDecimal(e.NewValues["financialPropotionsPercentage"]);
cmd.Connection = con;
try
{
con.Open();
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
e.Cancel = true;
grid1.CancelEdit();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}```

play math with sql commands

i'm working on restaurants programming with c#
working on the daily quantity of the material
i do count of the total that they make on the day then count how many they used and how many remaining on that day
my code is
public void ExecuteQuery(string query)
{
foreach (Control txt in this.Controls)
{
if (txt.GetType() == typeof(TextBox))
if (string.IsNullOrEmpty(txt.Text))
txt.Text = "0";
}
SqlCommand com = new SqlCommand(query, connection);
com.Parameters.Add("#shish_add", SqlDbType.Int).Value = shish_add.Text;
com.Parameters.Add("#bani_add", SqlDbType.Int).Value = bani_add.Text;
com.Parameters.Add("#zingr_add", SqlDbType.Int).Value = zingr_add.Text;
com.Parameters.Add("#tabona_add", SqlDbType.Int).Value = tabona_add.Text;
com.Parameters.Add("#fahita_chkn_add", SqlDbType.Int).Value = fahita_chkn_add.Text;
com.Parameters.Add("#borger_add", SqlDbType.Int).Value = borger_add.Text;
com.Parameters.Add("#kabab_add", SqlDbType.Int).Value = kabab_add.Text;
com.Parameters.Add("#shgef_add", SqlDbType.Int).Value = shgef_add.Text;
com.Parameters.Add("#faheta_met_add", SqlDbType.Int).Value = faheta_met_add.Text;
com.Parameters.Add("#kabda_add", SqlDbType.Int).Value = kabda_add.Text;
com.Parameters.Add("#shawo_met_add", SqlDbType.Int).Value = shawo_met_add.Text;
com.Parameters.Add("#shawo_chkn_add", SqlDbType.Int).Value = shawo_chkn_add.Text;
com.Parameters.Add("#chkn_mash_add", SqlDbType.Int).Value = chkn_mash_add.Text;
com.Parameters.Add("#chkn_red_add", SqlDbType.Int).Value = chkn_red_add.Text;
com.Parameters.Add("#patata_add", SqlDbType.Int).Value = patata_add.Text;
com.Parameters.Add("#shish_take", SqlDbType.Int).Value = shish_take.Text;
com.Parameters.Add("#bani_take", SqlDbType.Int).Value = bani_take.Text;
com.Parameters.Add("#zingr_take", SqlDbType.Int).Value = zingr_take.Text;
com.Parameters.Add("#tabona_take", SqlDbType.Int).Value = tabona_take.Text;
com.Parameters.Add("#fahita_chkn_take", SqlDbType.Int).Value = fahita_chkn_take.Text;
com.Parameters.Add("#borger_take", SqlDbType.Int).Value = borger_take.Text;
com.Parameters.Add("#kabab_take", SqlDbType.Int).Value = kabab_take.Text;
com.Parameters.Add("#shgef_take", SqlDbType.Int).Value = shgef_take.Text;
com.Parameters.Add("#faheta_met_take", SqlDbType.Int).Value = faheta_met_take.Text;
com.Parameters.Add("#kabda_take", SqlDbType.Int).Value = kabda_take.Text;
com.Parameters.Add("#shawo_met_take", SqlDbType.Int).Value = shawo_met_take.Text;
com.Parameters.Add("#shawo_chkn_take", SqlDbType.Int).Value = shawo_chkn_take.Text;
com.Parameters.Add("#chkn_mash_take", SqlDbType.Int).Value = chkn_mash_take.Text;
com.Parameters.Add("#chkn_red_take", SqlDbType.Int).Value = chkn_red_take.Text;
com.Parameters.Add("#patata_take", SqlDbType.Int).Value = patata_take.Text;
com.Parameters.Add("#shish_rom", SqlDbType.Int).Value = shish_rom.Text;
com.Parameters.Add("#bani_rom", SqlDbType.Int).Value = bani_rom.Text;
com.Parameters.Add("#zingr_rom", SqlDbType.Int).Value = zingr_rom.Text;
com.Parameters.Add("#tabona_rom", SqlDbType.Int).Value = tabona_rom.Text;
com.Parameters.Add("#fahita_chkn_rom", SqlDbType.Int).Value = fahita_chkn_rom.Text;
com.Parameters.Add("#borger_rom", SqlDbType.Int).Value = borger_rom.Text;
com.Parameters.Add("#kabab_rom", SqlDbType.Int).Value = kabab_rom.Text;
com.Parameters.Add("#shgef_rom", SqlDbType.Int).Value = shgef_rom.Text;
com.Parameters.Add("#faheta_met_rom", SqlDbType.Int).Value = faheta_met_rom.Text;
com.Parameters.Add("#kabda_rom", SqlDbType.Int).Value = kabda_rom.Text;
com.Parameters.Add("#shawo_met_rom", SqlDbType.Int).Value = shawo_met_rom.Text;
com.Parameters.Add("#shawo_chkn_rom", SqlDbType.Int).Value = shawo_chkn_rom.Text;
com.Parameters.Add("#chkn_mash_rom", SqlDbType.Int).Value = chkn_mash_rom.Text;
com.Parameters.Add("#chkn_red_rom", SqlDbType.Int).Value = chkn_red_rom.Text;
com.Parameters.Add("#patata_rom", SqlDbType.Int).Value = patata_rom.Text;
com.Parameters.Add("#dates", SqlDbType.DateTime).Value = dates.Value.Date;
if (connection.State == ConnectionState.Closed)
connection.Open();
com.ExecuteNonQuery();
connection.Close();
foreach (Control txt in this.Controls)
{
if (txt.GetType() == typeof(TextBox))
if (txt.Text == "0")
txt.Text = "";
}
MessageBox.Show("تمت عملية الاضافة بنجاح", "ملاحظة", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
}
public void doqury(string strn)
{
string sqlQuery = strn;
ExecuteQuery(sqlQuery);
}
private void button1_Click(object sender, EventArgs e)
{
// check for first time entry
SqlCommand cmd = new SqlCommand("select * from megana_cooking ", connection);
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
//mean there values on database
//now need to check is this a new day or not
SqlCommand cmd1 = new SqlCommand("select * from megana_cooking where dates = #dates", connection);
connection.Open();
SqlDataReader reader1 = cmd.ExecuteReader();
if (reader1.HasRows)
{
//no this is the take valus statment
reader.Close();
doqury("UPDATE megana_cooking SET shish_rom =shish_add - #shish_take ,bani_rom =bani_add - #bani_take ,zingr_rom =zingr_add - #zingr_take ,tabona_rom =tabona_add - #tabona_take ,fahita_chkn_rom =fahita_chkn_add - #fahita_chkn_take ,borger_rom =borger_add - #borger_take ,kabab_rom =kabab_add - #kabab_take ,shgef_rom =shgef_add - #shgef_take ,faheta_met_rom =faheta_met_add - #faheta_met_take ,kabda_rom =kabda_add - #kabda_take ,shawo_met_rom =shawo_met_add - #shawo_met_take ,shawo_chkn_rom =shawo_chkn_add - #shawo_chkn_take ,chkn_mash_rom =chkn_mash_add - #chkn_mash_take ,chkn_red_rom =chkn_red_add - #chkn_red_take ,patata_rom =patata_add - #patata_take ,patata_take =#patata_take,chkn_red_take =#chkn_red_take,chkn_mash_take =#chkn_mash_take,shawo_chkn_take =#shawo_chkn_take,shawo_met_take =#shawo_met_take,kabda_take =#kabda_take,faheta_met_take =#faheta_met_take,shgef_take =#shgef_take,kabab_take =#kabab_take,borger_take =#borger_take,fahita_chkn_take =#fahita_chkn_take,tabona_take =#tabona_take,zingr_take =#zingr_take,bani_take =#bani_take,shish_take =#shish_take ,dates =#dates where dates = #dates ");
}
else
{
// yes new day new values and add value to the remain values from last entry
DialogResult result = MessageBox.Show("سيتم ادخال بيانات ليوم جديد " + Environment.NewLine + " سيقوم بأدخال البيانات دون احتساب عملية السحب", "تأكيد", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1,
MessageBoxOptions.RightAlign);
doqury("INSERT INTO megana_cooking ( shish_add ,bani_add ,zingr_add ,tabona_add ,fahita_chkn_add ,borger_add ,kabab_add ,shgef_add ,faheta_met_add ,kabda_add ,shawo_met_add ,shawo_chkn_add ,chkn_mash_add ,chkn_red_add ,patata_add ,dates ) VALUES ( #shish_add ,#bani_add ,#zingr_add ,#tabona_add ,#fahita_chkn_add ,#borger_add ,#kabab_add ,#shgef_add ,#faheta_met_add ,#kabda_add ,#shawo_met_add ,#shawo_chkn_add ,#chkn_mash_add ,#chkn_red_add ,#patata_add ,#dates )");
//insert new quentity done now need to update the remain value
//new quentity + last remain
here need to find the last date that it have value then update and add the new quantity to it
}
}
else
{
//this is first entry
reader.Close();
DialogResult result = MessageBox.Show("سيتم ادخال البيانات الى المنظومة لاول مره " + Environment.NewLine + " سيقوم بأدخال البيانات دون احتساب عملية السحب", "تأكيد", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1,
MessageBoxOptions.RightAlign);
doqury("INSERT INTO megana_cooking ( shish_add ,bani_add ,zingr_add ,tabona_add ,fahita_chkn_add ,borger_add ,kabab_add ,shgef_add ,faheta_met_add ,kabda_add ,shawo_met_add ,shawo_chkn_add ,chkn_mash_add ,chkn_red_add ,patata_add ,shish_rom ,bani_rom ,zingr_rom ,tabona_rom ,fahita_chkn_rom ,borger_rom ,kabab_rom ,shgef_rom ,faheta_met_rom ,kabda_rom ,shawo_met_rom ,shawo_chkn_rom ,chkn_mash_rom ,chkn_red_rom ,patata_rom ,dates ) VALUES ( #shish_add ,#bani_add ,#zingr_add ,#tabona_add ,#fahita_chkn_add ,#borger_add ,#kabab_add ,#shgef_add ,#faheta_met_add ,#kabda_add ,#shawo_met_add ,#shawo_chkn_add ,#chkn_mash_add ,#chkn_red_add ,#patata_add ,#shish_add ,#bani_add ,#zingr_add ,#tabona_add ,#fahita_chkn_add ,#borger_add ,#kabab_add ,#shgef_add ,#faheta_met_add ,#kabda_add ,#shawo_met_add ,#shawo_chkn_add ,#chkn_mash_add ,#chkn_red_add ,#patata_add ,#dates )");
}
connection.Close();
}
the question is
i need to find the last date that it have value then update and add the new quantity to it i did mention it in my code
i know i can because when i tried this code on new query on sql management studio it work
SELECT
*
FROM
megana_cooking
ORDER BY
dates
update megana_cooking set shish_rom = shish_rom + '5'
can i make the sql command shorter than this by using sql programmability or server side because i have more than 15 type of the material food
i have weak knowledge about sql
thank you in advance

How to prevent 2 connection open in database?

I try something good code about prevent duplication of entries but I got error about connection. How can I fix this? Here's my code.
if(label1.Text == "" || label2.Text == "" || label3.Text == "") {
MessageBox.Show("Please Select Data");
} else {
String query = "Select * from Attendance where empIn=#empIn";
MySqlCommand cmd1 = new MySqlCommand(query, con);
cmd1.Parameters.AddWithValue("empIn", label2.Text);
MySqlDataReader dr = cmd1.ExecuteReader();
if (dr.HasRows) {
MessageBox.Show("This Person has already IN");
} else {
insert();
}
}
}
public void insert()
{
int i;
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO Attendance (Name,Date,empIn)VALUES(#Name,#Date,#empIn)", con);
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = label3.Text;
cmd.Parameters.Add("#Date", MySqlDbType.Date).Value = Convert.ToDateTime(label1.Text);
cmd.Parameters.Add("#empIn", MySqlDbType.VarChar).Value = label3.Text;
i = cmd.ExecuteNonQuery();
if (i > 0) {
MessageBox.Show("Data Inserted");
label2.Text = "";
label3.Text = "";
label4.Text = "";
} else {
MessageBox.Show("Not Deleted");
}
con.Close();
you can simply use the "using" state which will create and close the connection automatically
public object getQueryScaller(string sqlQuery)
{
object value = null;
using (SqlConnection conn = new SqlConnection(_connectionString))
{
using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))
{
conn.Open();
value = cmd.ExecuteScalar();
}
}
return value;
}
This will Automatically control the connection problem you will have no need to take care of it. just passing the parameter into the function as SQL statement and it will work.

Error/exception handling (try-catch) C#

How to achieve the requirements below:
The Retrieve button click event:
if user doesn't enter CustID in txtCustID need to inform them to enter Customer Id via lblMessage;
if entered CustId doesn't exist in database inform user that it doesn't exist via lblMessage.
The Update button click event - need to ensure that Customer ID already exists in the database.
The Delete button click event: same requirements as for Retrieve button.
I must use error/exception handling (try-catch) to achieve these (project requirement). I spent hours trying, but no success. I would be very grateful for some help! My code is below:
namespace ACME
{
public partial class Customer : System.Web.UI.Page
{
SqlConnection conn;
SqlDataAdapter adapter = new SqlDataAdapter();
DataTable table = new DataTable();
SqlCommand command = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
}
private void Page_PreInit(object sender, EventArgs e)
{
HttpCookie setTheme = Request.Cookies.Get("UserSelectedTheme");
if (setTheme != null)
{
Page.Theme = setTheme.Value;
}
}
protected void Clear()
{
txtCustID.Text = "";
txtFirstname.Text = "";
txtSurname.Text = "";
rbtGender.SelectedValue = "";
txtAge.Text = "";
txtAddress1.Text = "";
txtAddress2.Text = "";
txtCity.Text = "";
txtPhone.Text = "";
txtMobile.Text = "";
txtEmail.Text = "";
txtEmail2.Text = "";
}
protected void btnNew_Click(object sender, EventArgs e)
{
SqlDataAdapter adapter1 = new SqlDataAdapter();
DataTable table1 = new DataTable();
SqlCommand command1 = new SqlCommand();
Clear();
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
command1.Connection = conn;
command1.CommandType = CommandType.StoredProcedure;
command1.CommandText = "LargestCustID";
command1.Connection.Open();
int id = (int)command1.ExecuteScalar() + 1;
txtCustID.Text = id.ToString();
command1.Dispose();
conn.Close();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "AddCustomer";
command.Connection.Open();
command.Parameters.AddWithValue("#CustID",
int.Parse(txtCustID.Text));
command.Parameters.AddWithValue("#Firstname", txtFirstname.Text);
command.Parameters.AddWithValue("#Surname", txtSurname.Text);
command.Parameters.AddWithValue("#Gender", rbtGender.SelectedValue);
command.Parameters.AddWithValue("#Age", int.Parse(txtAge.Text));
command.Parameters.AddWithValue("#Address1", txtAddress1.Text);
command.Parameters.AddWithValue("#Address2", txtAddress2.Text);
command.Parameters.AddWithValue("#City", txtCity.Text);
command.Parameters.AddWithValue("#Phone", txtPhone.Text);
command.Parameters.AddWithValue("#Mobile", txtMobile.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
adapter.InsertCommand = command;
adapter.InsertCommand.ExecuteNonQuery();
lblMessage.Text = "The new record has been added to the database!";
command.Connection.Close();
Clear();
}
protected void btnRetrieve_Click(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "GetCustID";
command.Connection.Open();
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = int.Parse(txtCustID.Text);
command.Parameters.Add(param);
adapter.SelectCommand = command;
adapter.Fill(table);
int id = table.Rows.Count;
if (id == 0)
{
lblMessage.Text = "Customer ID does not exists!";
}
else
{
lblMessage.Text = "";
txtFirstname.Text = table.Rows[0].Field<string>("Firstname");
txtFirstname.DataBind();
txtSurname.Text = table.Rows[0].Field<string>("Surname");
txtSurname.DataBind();
txtAge.Text = table.Rows[0].Field<int>("Age").ToString();
txtAge.DataBind();
txtAddress1.Text = table.Rows[0].Field<string>("Address1");
txtAddress1.DataBind();
txtAddress2.Text = table.Rows[0].Field<string>("Address2");
txtAddress2.DataBind();
txtCity.Text = table.Rows[0].Field<string>("City");
txtCity.DataBind();
txtPhone.Text = table.Rows[0].Field<string>("Phone");
txtPhone.DataBind();
txtMobile.Text = table.Rows[0].Field<string>("Mobile");
txtMobile.DataBind();
txtEmail.Text = table.Rows[0].Field<string>("Email");
txtEmail.DataBind();
}
command.Connection.Close();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "UpdateCustomer";
command.Connection.Open();
command.Parameters.AddWithValue("#CustID",
int.Parse(txtCustID.Text));
command.Parameters.AddWithValue("#Firstname", txtFirstname.Text);
command.Parameters.AddWithValue("#Surname", txtSurname.Text);
command.Parameters.AddWithValue("#Gender", rbtGender.SelectedValue);
command.Parameters.AddWithValue("#Age", int.Parse(txtAge.Text));
command.Parameters.AddWithValue("#Address1", txtAddress1.Text);
command.Parameters.AddWithValue("#Address2", txtAddress2.Text);
command.Parameters.AddWithValue("#City", txtCity.Text);
command.Parameters.AddWithValue("#Phone", txtPhone.Text);
command.Parameters.AddWithValue("#Mobile", txtMobile.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
lblMessage.Text = "The record has been updated!";
command.Connection.Close();
Clear();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "DeleteCustomer";
command.Connection.Open();
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = int.Parse(txtCustID.Text);
command.Parameters.Add(param);
adapter.DeleteCommand = command;
adapter.DeleteCommand.ExecuteNonQuery();
int id = (int)param.Value;
command.Connection.Close();
}
catch (Exception ex)
{
lblMessage.Text += "Please enter Customer ID!";
}
try
{
lblMessage.Text = "";
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = int.Parse(txtCustID.Text);
command.Parameters.Add(param);
adapter.DeleteCommand = command;
adapter.DeleteCommand.ExecuteNonQuery();
int id = table.Rows.Count;
id = (int)param.Value;
lblMessage.Text += "Customer record has been deleted";
command.Connection.Close();
}
catch (Exception ex)
{
lblMessage.Text = "Customer ID doesnot exists!";
}
Clear();
}
public string CustID { get; set; }
}
}
It sounds like you are trying to control flow of your application by use of exceptions. There are many reasons against this approach:
1) Code is difficult to understand and to debug.
2) Throwing exceptions in .Net is expensive.
3) If exception control flow of application how do you differentiate them from a real exceptions (thrown when something doesn't work as expected)?
If, on the other hand, you want to throw an exception when any of the scenarios you listed in the question happens then you can use standard .Net Exception class:
if (string.IsNullOrWhiteSpace(txtCustID.Text))
{
throw new Exception("Id not provided.");
}
Or you can create a custom exception to provide some more specific information:
public class IdNotProvidedException : Exception
{
public string MyCommandName { get; set; }
public IdNotProvidedException(string msg)
: base(msg)
{
}
public IdNotProvidedException(string msg, string myCommandName)
: base(msg)
{
this.MyCommandName = myCommandName;
}
}
And then you initialize and throw your custom exception.
Lastly, there are already places in your code, though not mentioned in your question, that are worth wrapping in a try...catch block. Basically, any place where you connect with the server may result in something unexpected (for instance, the server may not be available).

"Variable names must be unique within a query batch or stored procedure." error c# asp.net

this is my code,when the textbox content changes the datas required have to retrieved from the databse and displayed in the labels specified.
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Match match = Regex.Match(TextBox1.Text, #"^\d{4}[A-Z]{5}\d{3}$");
if (match.Success)
{
try
{
DropDownList1.Focus();
string dpt = (string)Session["deptmnt"];
idd = TextBox1.Text;
Label33.Text = idd;
string val = idd;
string con = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
SqlConnection con1 = new SqlConnection(con);
con1.Open();
// string val1 = dpt;
try
{
String str = "SELECT * from student where sid=#val";
SqlCommand cmd = new SqlCommand(str, con1);
cmd.CommandType = CommandType.Text;
SqlParameter sql;
cmd.Parameters.Clear();
sql = cmd.Parameters.Add("#val", SqlDbType.VarChar, 20);
sql.Value = val;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows == false)
{
Label35.Visible = true;
TextBox1.Text = "";
}
else
{
{
Panel3.Visible = true;
DropDownList1.Focus();
while (reader.Read()) // if can read row from database
{
Panel3.Visible = true;
Label3.Text = reader["sname"].ToString();
Label5.Text = reader["dept"].ToString();
Label25.Text = reader["yr"].ToString();
}
cmd.Parameters.Clear();
{
string val1 = idd;
string str2 = "SELECT bid from studentissuebook where sid=#val1 AND status='" + "lost" + "'";
SqlCommand cmd2 = new SqlCommand(str2, con1);
cmd2.CommandType = CommandType.Text;
cmd2.Parameters.Clear();
SqlParameter sql2;
sql2 = cmd2.Parameters.Add("#val1", SqlDbType.VarChar, 20);
sql2.Value = val1;
SqlDataReader reader1 = cmd2.ExecuteReader();
if (reader1.HasRows == false)
{
TextBox1.Text = "";
Label39.Visible = true;
Panel3.Visible = false;
}
else
{
DropDownList1.Focus();
while (reader1.Read()) // if can read row from database
{
DropDownList1.Items.Add(reader1[0].ToString());
}
DropDownList1.Focus();
}
}
}
}
con1.Close();
}
catch(Exception ex)
{
TextBox1.Text=ex.ToString();
}
}
catch (Exception ex)
{
TextBox1.Text = ex.ToString();
}
} else
{
formatlabel.Visible = true;
}
}
but,when i run the code,i get an error "The variable name '#sid' has already been declared. Variable names must be unique within a query batch or stored procedure.",I googled, generally this error occurs when there is a for loop or any loops,but i do not have any loops in my code.so im unable to find the cause
Try using two separate connection and command objects, like this:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Match match = Regex.Match(TextBox1.Text, #"^\d{4}[A-Z]{5}\d{3}$");
if (match.Success)
{
DropDownList1.Focus();
string dpt = (string) Session["deptmnt"];
idd = TextBox1.Text;
Label33.Text = idd;
string val = idd;
string con = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
using (SqlConnection con1 = new SqlConnection(con))
{
String str = "SELECT * from student where sid=#val";
con1.Open();
using (SqlCommand cmd = new SqlCommand(str, con1))
{
cmd.CommandType = CommandType.Text;
SqlParameter sql;
cmd.Parameters.Clear();
sql = cmd.Parameters.Add("#val", SqlDbType.VarChar, 20);
sql.Value = val;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows == false)
{
Label35.Visible = true;
TextBox1.Text = "";
}
else
{
Panel3.Visible = true;
DropDownList1.Focus();
while (reader.Read()) // if can read row from database
{
Panel3.Visible = true;
Label3.Text = reader["sname"].ToString();
Label5.Text = reader["dept"].ToString();
Label25.Text = reader["yr"].ToString();
}
cmd.Parameters.Clear();
}
}
}
using (SqlConnection con2 = new SqlConnection(con))
{
string val1 = idd;
string str2 = "SELECT bid from studentissuebook where sid=#val1 AND status='" + "lost" + "'";
con2.Open();
using (SqlCommand cmd2 = new SqlCommand(str2, con2))
{
cmd2.CommandType = CommandType.Text;
cmd2.Parameters.Clear();
SqlParameter sql2;
sql2 = cmd2.Parameters.Add("#val1", SqlDbType.VarChar, 20);
sql2.Value = val1;
SqlDataReader reader1 = cmd2.ExecuteReader();
if (reader1.HasRows == false)
{
TextBox1.Text = "";
Label39.Visible = true;
Panel3.Visible = false;
}
else
{
DropDownList1.Focus();
while (reader1.Read()) // if can read row from database
{
DropDownList1.Items.Add(reader1[0].ToString());
}
DropDownList1.Focus();
}
}
}
}
else
{
formatlabel.Visible = true;
}
}
Note: I have removed your try-catch blocks to make the code simpler to interpret, once it is working, then please re-apply your try-catch logic where you feel appropriate. Also, I added using blocks for the SqlConnection and SqlCommand objects, this will clean up the connection even if an exception happens.

Categories