I had this message
Input string was not in a correct format
when inserting values into the database. When I checked I have DDL but I did not select value from it so this message appeared, although I make this column in the database to allow NULL value.
protected void BT_submit_Click(object sender, ImageClickEventArgs e)
{
string File = "~/CvFiles/" + FU_CV.FileName;
if (FU_CV.FileBytes.Length > 4194304)
{
modalpopup.Show();
}
else
{
app.AddApplicant(txt_Mname.Text, Convert.ToInt32(DDL_Dept.SelectedValue));
}
}
private void loadDepts()
{
DDL_Dept.DataSource = d.GetAll();
DDL_Dept.Items.Clear();
DDL_Dept.AppendDataBoundItems = true;
DDL_Dept.Items.Insert(0, new ListItem("-All-", "NULL"));
DDL_Dept.DataValueField = "id";
DDL_Dept.DataTextField = "name";
DDL_Dept.DataBind();
}
public bool AddApplicant(string MiddleName, int Dept_ID)
{
SqlCommand cmd = new SqlCommand("SP_Insert_IntoApplicantforuser");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#MiddleName", MiddleName);
cmd.Parameters.AddWithValue("#Dept_ID", Dept_ID);
System.Data.SqlClient.SqlParameter paramter1 = cmd.Parameters.Add("#AppID", SqlDbType.Int);
paramter1.Direction = ParameterDirection.Output;
bool rowaffected;
rowaffected = DBHelper.Instance().Insert(cmd);
if (rowaffected == false)
{
AppID = (int)paramter1.Value;
}
return rowaffected;
}
You should check, if DDL_Dept.SelectedValue is a string representation of int. Use int.TryParse method:
if (FU_CV.FileBytes.Length > 4194304)
{
modalpopup.Show();
}
else
{
int dept;
if (int.TryParse(DDL_Dept.SelectedValue, out dept))
app.AddApplicant(txt_Mname.Text, dept);
else
app.AddApplicant(txt_Mname.Text, -1); //or whatever there should be for you
}
Related
I have inserted an image on the 1st form namely Add_Staff and want to get that image on the 2nd form namely Staff_Detail's data gridview. how I can pass reference of add_staff images to staff_detail form's data gridview. Here is the code.
Insertion Code: -
private void BTNSTAFF_Click(object sender, EventArgs e)
{
if (staffid.Text == "")
{
if (teachername.Text == "" || saddress.Text == "" || semail.Text == "" || contact.Text == "" || jobspeciality.Text == "")
{
MessageBox.Show("All Fields Required");
}
else
{
Image pimg = pictureBox1.Image;
ImageConverter converter = new ImageConverter();
var ImageConvert = converter.ConvertTo(pimg, typeof(byte[]));
conn.Open();
//Values Inserted into Course
SqlCommand cmd = new SqlCommand("insert into staff values (#a,#b,#c,#d,#e,#g)", conn);
cmd.Parameters.AddWithValue("#a", teachername.Text);
cmd.Parameters.AddWithValue("#b", saddress.Text);
cmd.Parameters.AddWithValue("#c", semail.Text);
cmd.Parameters.AddWithValue("#d", contact.Text);
cmd.Parameters.AddWithValue("#e", jobspeciality.Text);
cmd.Parameters.AddWithValue("#g", ImageConvert);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Inserted");
frm1.RefreshGrid();
conn.Close();
Staff_Clear();
this.Hide();
}
}}
Staff Detail Code for View Deatil: -
public partial class Staff_Detail : Form
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\mudas\source\repos\WindowsFormsApp1\WindowsFormsApp1\WindowsFormsApp1\Database1.mdf;Integrated Security=True");
public static string column_id = "";
public static string column_name = "";
public static string column_address = "";
public static string column_email = "";
public static string column_contact = "";
public static string column_job = "";
public Staff_Detail()
{
InitializeComponent();
View();
}
public void View()
{
try
{
dataGridView4.Rows.Clear();
// if (conn.State != ConnectionState.Open)
conn.Open();
SqlCommand cmd = new SqlCommand("Select * From staff", conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
String column_getid = dr["id"].ToString();
String column_getname = dr["name"].ToString();
String column_getaddress = dr["address"].ToString();
String column_getemail = dr["email"].ToString();
String column_getcontact = dr["contact"].ToString();
String column_getjob = dr["job"].ToString();
dataGridView4.Rows.Add(column_getid, column_getname, column_getaddress, column_getemail, column_getcontact, column_getjob, "Edit/Delet");
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void dataGridView4_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
int rowIndex = dataGridView4.CurrentCell.RowIndex;
String Column_id = dataGridView4.Rows[rowIndex].Cells[0].Value.ToString();
String Column_name = dataGridView4.Rows[rowIndex].Cells[1].Value.ToString();
String Column_address = dataGridView4.Rows[rowIndex].Cells[2].Value.ToString();
String Column_email = dataGridView4.Rows[rowIndex].Cells[3].Value.ToString();
String Column_contact = dataGridView4.Rows[rowIndex].Cells[4].Value.ToString();
String Column_job = dataGridView4.Rows[rowIndex].Cells[5].Value.ToString();
column_id = Column_id;
column_name = Column_name;
column_address = Column_address;
column_email = Column_email;
column_contact = Column_contact;
column_job = Column_job;
Add_Staff ad = new Add_Staff(this);
ad.Show();
ad.BringToFront();
}
}
I'm checking if a seal number exists in the database table, however when I use either the stored procedure or behind it doesn't work. The stored procedure produce the error message but if it doesn't exist it tells that I didn't supply a value, when the value is there. And from the code behind it is giving this error: Collection was modified; enumeration operation may not execute.
Code Behind
protected void showData()
{
#region Seal
SqlCommand R = new SqlCommand("PP_SealRecord", objConnection);
R.CommandType = CommandType.StoredProcedure;
R.Parameters.AddWithValue("#loadSheetNum", dispatchSheetNo);
objConnection.Open();
SqlDataReader Reader = R.ExecuteReader();
int maximumTextBoxCount = 7;
if (Reader.Read())
{
ControlCache = new List<Control>();
phSealNum.Controls.Clear();
for (int i = 0; i < maximumTextBoxCount; i++)
{
TextBox txt = new TextBox();
string index = string.Format("seal{0}", i + 1);
if (Reader[index] != DBNull.Value)
{
txt.Text = (string)Reader[index];
}
else
{
continue;
}
phSealNum.Controls.Add(txt);
phSealNum.Controls.Add(new LiteralControl(" "));
ControlCache.Add(txt);
txt.Width = 100;
//txt.Enabled = false;
}
}
Reader.Close();
objConnection.Close();
#endregion
}
protected void Update_Click(object sender, EventArgs e)
{
#region Seal Data
string str = null;
int countseal = 0;
foreach (TextBox textBox in phSealNum.Controls.OfType<TextBox>())
{
string constr = ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ConnectionString;
using (SqlCommand comm = new SqlCommand("PP_CountSeal"))
{
comm.Connection = con;
con.Open();
comm.CommandType = CommandType.StoredProcedure;
str = textBox.Text.TrimEnd();
comm.CommandType = CommandType.StoredProcedure;
string seal1 = string.Format("#seal{0}", countseal);
comm.Parameters.AddWithValue(seal1, str);
int count = (int)cmd.ExecuteScalar();
string name = HttpContext.Current.User.Identity.Name;
if (count > 0)
{
SqlCommand command = new SqlCommand("PP_SealRecord", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#loadSheetNum", dispatchSheetNo);
SqlDataReader data = command.ExecuteReader();
if (data.Read())
{
string previousseal1 = Convert.ToString(data["seal1"]);
string previousseal2 = Convert.ToString(data["seal2"]);
string previousseal3 = Convert.ToString(data["seal3"]);
string previousseal4 = Convert.ToString(data["seal4"]);
string previousseal5 = Convert.ToString(data["seal5"]);
string previousseal6 = Convert.ToString(data["seal6"]);
string previousseal7 = Convert.ToString(data["seal7"]);
EditSeal(dispatchSheetNo, previousseal1, previousseal2, previousseal3, previousseal4, previousseal5, previousseal6, previousseal7, name);
}
}
else
{
// INSERT STATEMENT
CreateSeal(loadsheet, CreatedBy);
}
#endregion
}
//Creates history when seal is updated
protected void InsertSealHistory()
{
SqlConnection con = new SqlConnection(connection); //SQL Connection
con.Open();
#region Get Seal Record
SqlCommand cmd = new SqlCommand("PP_SealDataRecord", con);
cmd.CommandType = CommandType.StoredProcedure; //SQL Command Type is Stored Procedure
cmd.Parameters.AddWithValue("#loadsheetnum", dispatchSheetNo);
SqlDataReader dr = cmd.ExecuteReader();
string sealNumber = "";
string CreatedBy = "";
DateTime? DateCreated = null;
while (dr.Read()) {
sealNumber = dr["sealNumber"].ToString();
CreatedBy = dr["CreatedBy"].ToString();
DateCreated = Convert.ToDateTime(dr["DateCreated"].ToString());
}
dr.Close();
con.Close();
#endregion
#region Insert Seal History
con.Open();
SqlCommand I = new SqlCommand("PP_CreateSealDataHistory", con);
I.CommandType = CommandType.StoredProcedure;
I.Parameters.AddWithValue("#LoadSheetNum", dispatchSheetNo);
I.Parameters.AddWithValue("#SealNumber", sealNumber);
I.Parameters.AddWithValue("#CreatedBy", CreatedBy);
I.Parameters.AddWithValue("#DateCreated",DateCreated);
I.ExecuteNonQuery();
con.Close();
#endregion
}
protected void EditSeal(string num, string a, string b, string c, string d, string e, string f, string g, string user)
{
SqlConnection con = new SqlConnection(connection); //SQL Connection
con.Open();
int maxPossibleTextBoxCount = 7;
int selectedTextBoxCount = phSealNum.Controls.OfType<TextBox>().Count();
int emptyTextBoxCount = maxPossibleTextBoxCount - selectedTextBoxCount;
SqlCommand U = new SqlCommand("PP_updateSeal", con);
U.CommandType = CommandType.StoredProcedure;
U.Parameters.AddWithValue("#loadsheetNum", num);
foreach (TextBox textBox in phSealNum.Controls.OfType<TextBox>())
{
if (!Regex.IsMatch(textBox.Text.Replace(" ", ""), #"(^([0-9]*|\d*\d{1}?\d*)$)"))
{
lblError.Text = "Please enter only numeric values for seal number";
return;
}
else if (textBox.Text == "")
{
lblError.Text = "Please enter seal number";
return;
}
else
{
countSeal += 1;
Session["CountSeal"] = countSeal;
if (countSeal == 1)
{
string seal = string.Format("#previous_seal{0}", countSeal);
U.Parameters.AddWithValue(seal, a);
}
else if (countSeal == 2)
{
string seal = string.Format("#previous_seal{0}", countSeal);
U.Parameters.AddWithValue(seal, b);
}
else if (countSeal == 3)
{
string seal = string.Format("#previous_seal{0}", countSeal);
U.Parameters.AddWithValue(seal, c);
}
else if (countSeal == 4)
{
string seal = string.Format("#previous_seal{0}", countSeal);
U.Parameters.AddWithValue(seal, d);
}
else if (countSeal == 5)
{
string seal = string.Format("#previous_seal{0}", countSeal);
U.Parameters.AddWithValue(seal, e);
}
else if (countSeal == 6)
{
string seal = string.Format("#previous_seal{0}", countSeal);
U.Parameters.AddWithValue(seal, f);
}
else
{
string seal = string.Format("#previous_seal{0}", countSeal);
U.Parameters.AddWithValue(seal, g);
}
string seal1 = string.Format("#seal{0}", countSeal);
U.Parameters.AddWithValue(seal1, textBox.Text);
}
}
// Here we add the parameters for the non-selected textboxes.
if (emptyTextBoxCount > 0)
{
for (int i = 0; i < emptyTextBoxCount; i++)
{
countSeal += 1;
Session["CountSeal"] = countSeal;
string seal = string.Format("#previous_seal{0}", countSeal);
string seal1 = string.Format("#seal{0}", countSeal);
U.Parameters.AddWithValue(seal, System.DBNull.Value);
U.Parameters.AddWithValue(seal1, System.DBNull.Value);
}
}
U.Parameters.AddWithValue("#lastUser", user);
//U.Parameters.Add("#outmessage", SqlDbType.Char, 500);
//U.Parameters["#outmessage"].Direction = ParameterDirection.Output;
U.ExecuteNonQuery();
//lblError.Text = (string)U.Parameters["#outmessage"].Value;
con.Close();
showData();
}
protected void CreateSeal(string num, string user)
{
SqlConnection con = new SqlConnection(connection); //SQL Connection
con.Open();
SqlCommand U = new SqlCommand("PP_CreateSealNumber", con);
U.CommandType = CommandType.StoredProcedure;
int counter = 1;
int maxPossibleTextBoxCount = 7;
int selectedTextBoxCount = phSealNum.Controls.OfType<TextBox>().Count();
int emptyTextBoxCount = maxPossibleTextBoxCount - selectedTextBoxCount;
foreach (TextBox textBox in phSealNum.Controls.OfType<TextBox>())
{
if (!Regex.IsMatch(textBox.Text, #"(^([0-9]*|\d*\d{1}?\d*)$)"))
{
lblError.Text = "Please enter only numeric values for seal number";
return;
}
else
{
string seal = string.Format("#seal{0}", counter++);
//command.Parameters.AddWithValue(seal, textBox.Text);
U.Parameters.AddWithValue(seal, textBox.Text);
}
}
// Here we add the parameters for the non-selected textboxes.
if (emptyTextBoxCount > 0)
{
for (int i = 0; i < emptyTextBoxCount; i++)
{
string seal = string.Format("#seal{0}", counter++);
//command.Parameters.AddWithValue(seal, textBox.Text);
U.Parameters.AddWithValue(seal, DBNull.Value);
//command.Parameters.AddWithValue($"#seal{counter++}", DBNull.Value);
}
}
U.Parameters.AddWithValue("#loadsheetNum", num);
U.Parameters.AddWithValue("#lastUser", user);
U.ExecuteNonQuery();
con.Close();
showData();
}
protected void TotalSeal_SelectedIndexChanged(object sender, EventArgs e)
{
populate();
}
//Populates the amount of textbox based on the value selected from the drop down
public void populate()
{
//ControlCache = new List<Control>();
//phSealNum.Controls.Clear();
int targetCount = Convert.ToInt32(TotalSeal.SelectedItem.Value);
int currentItems = phSealNum.Controls.OfType<TextBox>().Count();
int totalitems = targetCount - currentItems;
if (totalitems <= 7)
{
for (int i = 0; i < totalitems; i++)
{
TextBox tx = new TextBox();
tx.MaxLength = 10;
tx.Width = 100;
phSealNum.Controls.Add(tx);
phSealNum.Controls.Add(new LiteralControl(" "));
ControlCache.Add(tx);
}
}
else
{
lblError.Text = targetCount + " exceeds number of seals";
}
}
Is your collection phSealNum.Controls.OfType() is getting modified when your iterating in loop? Please check that let me know.
I have been trying to figure out how to save image into database with both null and image values. For my code it saves the image but if the image is missing it does not save a null value.
public string STDNAME { get; set; }
public string Image { get; set; }
DateTime Date1 = DateTime.Now;
This the code that I used to save the data
public string imagepath { get; set; }
public bool Insert(StudentC c)
{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstring);
try
{
byte[] imageBT = null;
FileStream fstream = new FileStream(this.Image, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fstream);
imageBT = br.ReadBytes((int)fstream.Length);
string sql = "INSERT INTO STUDENT (STDNAME,imagepath,Image,Date) VALUES (#STDNAME,#imagepath,#Image,#Date)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#STDNAME", c.STDNAME);
cmd.Parameters.AddWithValue("#imagepath", c.imagepath);
cmd.Parameters.AddWithValue("#Image", imageBT);
cmd.Parameters.AddWithValue("#Date", Date1);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
catch (Exception ex)
{
Console.WriteLine("\nMessage ---\n{0}", ex.Message);
}
finally
{
conn.Close();
}
return isSuccess;
}
This code is for browsing the image
//browse image
private void button6_Click(object sender, EventArgs e)
{
OpenFileDialog f = new OpenFileDialog();
f.Filter = "All Files|*.*|JPEGs|*.jpg|Bitmaps|*.bmp|GIFs|*.gif";
f.FilterIndex = 2;
if (f.ShowDialog() == DialogResult.OK)
{
pictureBox2.Image = Image.FromFile(f.FileName);
pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox2.BorderStyle = BorderStyle.Fixed3D;
textBox7.Text = f.SafeFileName.ToString();
string picPath = f.FileName.ToString();
textBox7.Text = picPath;
pictureBox2.ImageLocation = picPath;
}
}
This is the code to supplies the values to store
private void button5_Click(object sender, EventArgs e)
{
c.STDNAME = textBox2.Text;
c.Image = textBox7.Text;
c.imagepath = textBox7.Text;
bool success = c.Insert(c);
if (success == true)
{
MessageBox.Show("Data has been saved");
//Clear();
}
else
{
// label4.Text = "Data Has not been saved";
MessageBox.Show("Data has not been saved");
}
}
For adding adding null to the image column, make sure you specify the type (e.g. VarBinary) as the example below. In addition, make sure the image column accepts null.
cmd.Parameters.Add("#Image", SqlDbType.VarBinary).Value = DBNull.Value;
Moreover, the following approach may lead to the exception further below:
cmd.Parameters.AddWithValue("#Image", DBNull.Value);
--- Exception ---
System.Data.SqlClient.SqlException (0x80131904): Implicit conversion from data type nvarchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.
**Very Simple Solution
C# Text
query = "insert into Customer (CustomerCode,LdegerCode,CustomerPicture) values ('0001','9999',NULL)"
Sql query Text
insert into Customer (CustomerCode,LdegerCode,CustomerPicture) values ('0001','9999',NULL)
if You use DBNull.Value its save Empty String in Column
I am getting this error
Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
I read this question and it states that the exception is caused because of not closing the connection. However, i close all the connection in my code
This is my code, it is simple
public partial class index : System.Web.UI.Page
{
private static string defaultReason = "reason not selected";
protected override object SaveViewState()
{
//save view state right after the dynamic controlss added
var viewState = new object[1];
viewState[0] = base.SaveViewState();
return viewState;
}
protected override void LoadViewState(object savedState)
{
//load data frm saved viewstate
if (savedState is object[] && ((object[])savedState).Length == 1)
{
var viewState = (object[])savedState;
fillReasons();
base.LoadViewState(viewState[0]);
}
else
{
base.LoadViewState(savedState);
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string callIDValue = Request.QueryString["CallID"];
string callerIDValue = Request.QueryString["CallerID"];
if (!String.IsNullOrEmpty(callerIDValue))
{
callerID.Value = callerIDValue;
if (!String.IsNullOrEmpty(callIDValue))
{
string query = "INSERT INTO Reason (callerID, callID, reason, timestamp) VALUES (#callerID, #callID, #reason, #timestamp)";
SqlConnection con = getConnection();
SqlCommand command = new SqlCommand(query, con);
command.Parameters.AddWithValue("#callerID", callerIDValue);
command.Parameters.AddWithValue("#callID", callIDValue);
command.Parameters.AddWithValue("#reason", defaultReason);
command.Parameters.AddWithValue("#timestamp", DateTime.Now.ToString());
try
{
con.Open();
command.ExecuteNonQuery();
command.Dispose();
con.Close();
}
catch (Exception ee)
{
command.Dispose();
con.Close();
message.InnerHtml = ee.Message;
}
}
else
{
message.InnerHtml = "Call ID is empty";
}
}
else
{
callerID.Value = "Undefined";
message.InnerHtml = "Caller ID is empty";
}
fillReasons();
}
else
{
}
}
private void fillReasons()
{
string query = "SELECT * FROM wrapuplist WHERE isEnabled = #isEnabled";
SqlConnection con = new SqlConnection(getConnectionString());
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("isEnabled", true);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable results = new DataTable();
da.Fill(results);
int numberOfReasons = 0; // a integer variable to know if the number of the reasons becomes able to be divided by four
HtmlGenericControl div = null;
foreach (DataRow row in results.Rows)
{
numberOfReasons++;
if ((numberOfReasons % 4) == 1)
{
div = new HtmlGenericControl("div");
div.Attributes.Add("class", "oneLine");
}
RadioButton radioButton = new RadioButton();
radioButton.ID = "reason_" + row["reasonName"].ToString();
radioButton.GroupName = "reason";
radioButton.Text = row["reasonName"].ToString();
div.Controls.Add(radioButton);
if (numberOfReasons % 4 == 0)
{
myValueDiv.Controls.Add(div);
//numberOfReasons = 0;
}
else if (numberOfReasons == results.Rows.Count)
{
myValueDiv.Controls.Add(div);
//numberOfReasons = 0;
}
}
cmd.Dispose();
da.Dispose();
con.Close();
}
private SqlConnection getConnection()
{
return new SqlConnection(ConfigurationManager.ConnectionStrings["vmpcon"].ConnectionString);
}
private string getConnectionString()
{
return ConfigurationManager.ConnectionStrings["wrapupconnection"].ConnectionString.ToString();
}
protected void buttonSaveClose_Click(object sender, EventArgs e)
{
var divcontrols = myValueDiv.Controls.OfType<HtmlGenericControl>();
bool isFound = false;
RadioButton checkedRadioButton = null;
foreach (HtmlGenericControl loHTML in divcontrols)
{
var checkedRadioButtons = loHTML.Controls.OfType<RadioButton>().Where(radButton => radButton.Checked).ToList();
foreach (RadioButton lobtn in checkedRadioButtons)
{
if (lobtn.Checked)
{
isFound = true;
checkedRadioButton = lobtn;
}
}
}
if (isFound)
{
sReasonError.InnerText = "";
string reason = "";
reason = checkedRadioButton.Text;
string callIDValue = Request.QueryString["CallID"];
string callerIDValue = Request.QueryString["CallerID"];
if (String.IsNullOrEmpty(callIDValue))
{
message.InnerText = "Call ID is empty";
}
else if (String.IsNullOrEmpty(callerIDValue))
{
message.InnerText = "Caller ID is empty";
}
else
{
message.InnerText = "";
string query2 = "SELECT * FROM Reason WHERE callID = #callID AND reason != #reason";
SqlConnection con = getConnection();
SqlCommand command2 = new SqlCommand(query2, con);
command2.Parameters.AddWithValue("#callID", callIDValue);
command2.Parameters.AddWithValue("#reason", defaultReason);
con.Open();
if (command2.ExecuteScalar() != null)
{
message.InnerText = "Already saved";
command2.Dispose();
con.Close();
}
else
{
command2.Dispose();
con.Close();
string notes = taNotes.InnerText;
string query = "UPDATE Reason SET reason = #reason, notes = #notes, timestamp = #timestamp WHERE callID = #callID";
SqlCommand command = new SqlCommand(query, con);
command.Parameters.AddWithValue("#callID", callIDValue);
command.Parameters.AddWithValue("#reason", reason);
command.Parameters.AddWithValue("#notes", notes);
command.Parameters.AddWithValue("#timestamp", DateTime.Now.ToString());
try
{
con.Open();
command.ExecuteNonQuery();
command.Dispose();
con.Close();
message.InnerText = "Done Successfully";
//ClientScript.RegisterStartupScript(typeof(Page), "closePage", "<script type='text/JavaScript'>window.close();</script>");
ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.open('close.html', '_self', null);", true);
}
catch (Exception ee)
{
command.Dispose();
con.Close();
message.InnerText = "Error, " + ee.Message;
}
}
}
}
else
{
sReasonError.InnerText = "Required";
message.InnerText = "Select a reason";
//fillReasons();
}
}
}
as you see, all the connection are being closed, what wrong did I do please?
Closing connections and disposing should be in a finally block while using a try catch.
or use a using block like the one below
using(SqlConnection con = getConnection())
{
con.Open();
//Do your operation here. The connection will be closed and disposed automatically when the using scope is exited
}
I am am trying to pass a parameter into my textbox which communicates to my database and runs a stored procedure on a button click.
I have the button working if I hard code a parameter value but I need to to accept parameters in a textbox.
Any ideas how I can fix this code to accomplish this?
This is one of my classes
public FixPayrollMonth PayrollMonth()
{
return StoreProcPayrollMonth("fix_Payroll_PayingMonth");
}
private FixPayrollMonth StoreProcPayrollMonth(string storeprocedurename)
{
FixPayrollMonth result = new FixPayrollMonth() {IsSuccess = false };
SqlCommand cmd = new SqlCommand(storeprocedurename, Connection);
cmd.Parameters.Add(new SqlParameter("#Month_Change", 123456 ));
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Connection.Open();
using (var data = cmd.ExecuteReader())
{
while (data.Read())
{
result.MonthChanged = Convert.ToInt32(data["MonthChanged"]);
result.IsSuccess = Convert.ToBoolean(data["IsSuccess"]);
}
}
return result;
}
This is my button click...I need to link it to my textbox called txtPay
protected void btnFixMnth_Click(object sender, EventArgs e)
{
var result = repo.PayrollMonth();
if (result.IsSuccess)
{
lblMessageBoxMnthChg.Text = "Succesful Month has been changed to: " + result.MonthChanged;
}
else
{
lblMessageBoxMnthChg.Text = "Failed to change month";
}
}
Your call to repo.PayrollMonth would required a parameter to pass in the value of the textbox. So in your button click event you would do:
var result = repo.PayrollMonth(txtPay.Text);
And you repo would need to be modified to look like the following:
public FixPayrollMonth(string pay)
{
StoreProcPayrollMonth("fix_Payroll_PayingMonth", pay);
}
private FixPayrollMonth StoreProcPayrollMonth(string storeprocedurename, string pay)
{
FixPayrollMonth result = new FixPayrollMonth() {IsSuccess = false };
SqlCommand cmd = new SqlCommand(storeprocedurename, Connection);
cmd.Parameters.Add(new SqlParameter("#Month_Change", pay ));
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Connection.Open();
using (var data = cmd.ExecuteReader())
{
while (data.Read())
{
result.MonthChanged = Convert.ToInt32(data["MonthChanged"]);
result.IsSuccess = Convert.ToBoolean(data["IsSuccess"]);
}
}
return result;
}