calling 2 methods from onclick c# - c#
Ive been trying to pass 2 SQL queries by clicking the button once and so this is what ive been trying to do as shown below but its not working....please help... thanks in advance
so this the code in front
<asp:Button ID="btnWedRecInsert" runat="server" Text="Insert" OnClick="btnWedRecInsert_Click1; btnWedRecInsert_Click2;" />
The code behind is below
protected void btnWedRecInsert_Click1(object sender, EventArgs e)
{
string Function = ddlFunction.Text;
string FunctionDate = txtFunctionDate.Text;
string FunctionTime = ddlFunctionTime.Text;
string groomName = txtGroomName.Text;
string groomFatherName = txtGroomFatherName.Text;
string groomAge = txtGroomAge.Text;
string groomPhone = txtGroomPhone.Text;
string groomAddress = txtGroomAddress.Text;
string brideName = txtBrideName.Text;
string brideFatherName = txtBrideFatherName.Text;
string brideAge = txtBrideAge.Text;
string bridePhone = txtBridePhone.Text;
string brideAddress = txtBrideAddress.Text;
string registerName = txtRegisterName.Text;
string registerPhone = txtRegisterPhone.Text;
string registerAddress = txtRegisterAddress.Text;
string referenceName = txtReferenceName.Text;
string referencePhone = txtReferencePhone.Text;
string referenceAddress = txtReferenceAddress.Text;
string connString = ConfigurationManager.ConnectionStrings["MandapamDatabase"].ConnectionString;
OleDbConnection connection = new OleDbConnection(connString);
string insertQuery = "INSERT INTO wedding(RegisteredDate, Function, FunctionDate, FunctionTime, groomName, groomFatherName, groomAge, groomPhone, groomAddress, brideName, brideFatherName, brideAge, bridePhone, brideAddress, registerName, registerPhone, registerAddress, referenceName, referencePhone, referenceAddress) VALUES( #Date, #Function, #FunctionDate, #FunctionTime, #groomName, #groomFatherName, #groomAge, #groomPhone, #groomAddress, #brideName, #brideFatherName, #brideAge, #bridePhone, #brideAddress, #registerName, #registerPhone, #registerAddress, #referenceName, #referencePhone, #referenceAddress) ";
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = insertQuery;
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#Date", DateTime.Now.Date);
command.Parameters.AddWithValue("#Function", Function);
command.Parameters.AddWithValue("#FunctionDate", FunctionDate);
command.Parameters.AddWithValue("#FunctionTime", FunctionTime);
command.Parameters.AddWithValue("#groomName", groomName);
command.Parameters.AddWithValue("#groomFatherName", groomFatherName);
command.Parameters.AddWithValue("#groomAge", groomAge);
command.Parameters.AddWithValue("#groomPhone", groomPhone);
command.Parameters.AddWithValue("#groomAddress", groomAddress);
command.Parameters.AddWithValue("#brideName", brideName);
command.Parameters.AddWithValue("#brideFatherName", brideFatherName);
command.Parameters.AddWithValue("#brideAge", brideAge);
command.Parameters.AddWithValue("#bridePhone", bridePhone);
command.Parameters.AddWithValue("#brideAddress", brideAddress);
command.Parameters.AddWithValue("#registerName", registerName);
command.Parameters.AddWithValue("#registerPhone", registerPhone);
command.Parameters.AddWithValue("#registerAddress", registerAddress);
command.Parameters.AddWithValue("#referenceName", referenceName);
command.Parameters.AddWithValue("#referencePhone", referencePhone);
command.Parameters.AddWithValue("#referenceAddress", referenceAddress);
try
{
connection.Open();
command.ExecuteNonQuery();
lblMessage.Text = "Record inserted successfully";
}
catch (Exception ex)
{
lblMessage.Text = "Unable to insert record";
}
finally
{
connection.Close();
}
}
protected void btnWedRecInsert_Click2(object sender, EventArgs e)
{
string Function = ddlReception.Text;
string FunctionDate = txtReceptionDate.Text;
string FunctionTime = ddlReceptionTime.Text;
string groomName = txtGroomName.Text;
string groomFatherName = txtGroomFatherName.Text;
string groomAge = txtGroomAge.Text;
string groomPhone = txtGroomPhone.Text;
string groomAddress = txtGroomAddress.Text;
string brideName = txtBrideName.Text;
string brideFatherName = txtBrideFatherName.Text;
string brideAge = txtBrideAge.Text;
string bridePhone = txtBridePhone.Text;
string brideAddress = txtBrideAddress.Text;
string registerName = txtRegisterName.Text;
string registerPhone = txtRegisterPhone.Text;
string registerAddress = txtRegisterAddress.Text;
string referenceName = txtReferenceName.Text;
string referencePhone = txtReferencePhone.Text;
string referenceAddress = txtReferenceAddress.Text;
string connString = ConfigurationManager.ConnectionStrings["MandapamDatabase"].ConnectionString;
OleDbConnection connection = new OleDbConnection(connString);
string insertQuery = "INSERT INTO wedding(RegisteredDate, Function, ReceptionTime, FunctionDate, FunctionTime, groomName, groomFatherName, groomAge, groomPhone, groomAddress, brideName, brideFatherName, brideAge, bridePhone, brideAddress, registerName, registerPhone, registerAddress, referenceName, referencePhone, referenceAddress) VALUES( #Date, #Function, #FunctionDate, #FunctionTime, #groomName, #groomFatherName, #groomAge, #groomPhone, #groomAddress, #brideName, #brideFatherName, #brideAge, #bridePhone, #brideAddress, #registerName, #registerPhone, #registerAddress, #referenceName, #referencePhone, #referenceAddress) ";
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = insertQuery;
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#Date", DateTime.Now.Date);
command.Parameters.AddWithValue("#Function", Function);
command.Parameters.AddWithValue("#FunctionDate", FunctionDate);
command.Parameters.AddWithValue("#FunctionTime", FunctionTime);
command.Parameters.AddWithValue("#groomName", groomName);
command.Parameters.AddWithValue("#groomFatherName", groomFatherName);
command.Parameters.AddWithValue("#groomAge", groomAge);
command.Parameters.AddWithValue("#groomPhone", groomPhone);
command.Parameters.AddWithValue("#groomAddress", groomAddress);
command.Parameters.AddWithValue("#brideName", brideName);
command.Parameters.AddWithValue("#brideFatherName", brideFatherName);
command.Parameters.AddWithValue("#brideAge", brideAge);
command.Parameters.AddWithValue("#bridePhone", bridePhone);
command.Parameters.AddWithValue("#brideAddress", brideAddress);
command.Parameters.AddWithValue("#registerName", registerName);
command.Parameters.AddWithValue("#registerPhone", registerPhone);
command.Parameters.AddWithValue("#registerAddress", registerAddress);
command.Parameters.AddWithValue("#referenceName", referenceName);
command.Parameters.AddWithValue("#referencePhone", referencePhone);
command.Parameters.AddWithValue("#referenceAddress", referenceAddress);
try
{
connection.Open();
command.ExecuteNonQuery();
lblMessage.Text = "Record inserted successfully";
}
catch (Exception ex)
{
lblMessage.Text = "Unable to insert record";
}
finally
{
connection.Close();
}
}
You should change your markup to:
<asp:Button ID="btnWedRecInsert" runat="server" Text="Insert" OnClick="btnWedRecInsert_Click" />
And change your codebehind to:
protected void btnWedRecInsert_Click(object sender, EventArgs e)
{
btnWedRecInsert_Click1();
btnWedRecInsert_Click2();
}
and for readability maybe you should change the name of the insert functions to
insertWedding1();
insertWedding2();
As of now I can't see any difference between the two insertfunctions. mayby you will change theese later but they're quite similar. How about making a function out of them with parameters so you don't have to write so much code : ) eg.
insertWedding(object paramWedding1);
insertWedding(object paramWedding2);
Change the onClick event to btn_{NameOfYourButton}Click and then have
public void btn_{NameOfYourButton}Click() {
btnWedRecInsert_Click1();
btnWedRecInsert_Click2();
}
Related
Adding data from SQL Server table into textbox when entering data in another textbox
Here is my program: What I want to do: when I enter 1 in ProductID textbox, I want category, name and price for ProductID = 1 to be filled into their textboxes. I have tried to read from product table where ProductID = ProductIDTB.Text and then changed the other textboxes to show the data inside the other columns Here is my code when ProductID textbox is changed: protected void ProductIDTB_TextChanged(object sender, EventArgs e) { string connectionString1; SqlConnection cnn1; connectionString1 = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Greenwich_Butchers;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"; cnn1 = new SqlConnection(connectionString1); string selectSql1 = "SELECT * FROM [Product] WHERE ProductID = ('" + Convert.ToInt32(ProductIDTB.Text) + "') "; SqlCommand com1 = new SqlCommand(selectSql1, cnn1); try { cnn1.Open(); using (SqlDataReader read = com1.ExecuteReader()) { while (read.Read()) { String productcategory = Convert.ToString(read["ProductCategory"]); ProductCategoryTB.Text = productcategory; String productname = Convert.ToString(read["ProductName"]); ProductNameTB.Text = productname; String productprice = Convert.ToString(read["ProductPrice"]); ProdPriceTB.Text = productprice; } } } catch (Exception ex) { Response.Write("error" + ex.ToString()); } finally { cnn1.Close(); } } Work-around: as textbox_textchanged event was not working, I decided to add a button which finds product using the ID: protected void FindProductBtn_Click(object sender, EventArgs e) { string connectionString1; SqlConnection cnn1; connectionString1 = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Greenwich_Butchers;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"; cnn1 = new SqlConnection(connectionString1); string selectSql1 = "SELECT * FROM [Product] WHERE ProductID = (" + Convert.ToInt32(ProductIDTB.Text) + ") "; SqlCommand com1 = new SqlCommand(selectSql1, cnn1); try { cnn1.Open(); using (SqlDataReader read = com1.ExecuteReader()) { while (read.Read()) { String productcategory = Convert.ToString(read["ProductCategory"]); ProductCategoryTB.Text = productcategory; String productname = Convert.ToString(read["ProductName"]); ProductNameTB.Text = productname; String productprice = Convert.ToString(read["ProductPrice"]); ProdPriceTB.Text = productprice; } } } catch (Exception ex) { Response.Write("error" + ex.ToString()); } finally { cnn1.Close(); ProductCategoryTB.ReadOnly = true; ProductNameTB.ReadOnly = true; ProdPriceTB.ReadOnly = true; } }
Set the textbox's AutoPostBack attribute to true More info: https://meeraacademy.com/textbox-autopostback-and-textchanged-event-asp-net/ <asp:TextBox ID="ProductIDTB" runat="server" AutoPostBack="True" OnTextChanged="ProductIDTB_TextChanged"></asp:TextBox> By the way, use SqlParameter to use parameterized query. Aside from sql-injection attack prevention, parameterized query can help the RDBMS store and re-use the execution plan of similar queries, to ensure better performance. See: https://dba.stackexchange.com/questions/123978/can-sp-executesql-be-configured-used-by-default string selectSql1 = "SELECT * FROM [Product] WHERE ProductID = #productIdFilter"; int productIdFilter = Convert.ToInt32(ProductIDTB.Text); SqlCommand com1 = new SqlCommand(selectSql1, cnn1); com1.Parameters.AddWithValue("productIdFilter", productIdFilter);
OnTextChanged Event in Code Behind protected void txtProductId_TextChanged(object sender, EventArgs e) { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["_connect"].ToString()); int ProductId = Convert.ToInt32(txtProductId.Text); SqlCommand com = con.CreateCommand(); com.CommandText = "sp_ProductGetData"; com.CommandType = CommandType.StoredProcedure; com.Parameters.AddWithValue("#Mode", 1); com.Parameters.AddWithValue("#ProductId", ProductId); con.Open(); SqlDataReader dr = com.ExecuteReader(); if (dr.HasRows) { dr.Read(); txtProductCategory.Text = Convert.ToString(dr["ProductCategory"]); txtProductName.Text = Convert.ToString(dr["ProductName"]); txtPrice.Text = Convert.ToString(dr["Price"]); } else { ScriptManager.RegisterClientScriptBlock((Page)(HttpContext.Current.Handler), typeof(Page), "alert", "javascript:alert('" + Convert.ToString(("No Record Found with Prodcut Id: "+ProductId)) + "');", true); return; } con.Close(); } Stored Procedure CREATE PROCEDURE sp_ProductGetData ( #Mode INT=NULL, #ProductId INT=NULL ) AS BEGIN IF(#Mode=1) BEGIN SELECT ProductCategory,ProductName,Price FROM Product WHERE ProductId=#ProductId END END
How can we set catch exception in a label?
My Class public string Countryadd(string country, string id) { string data = "0"; try { string qry1 = "select Country from Country where Country='" + country + "'";//Checking weather txtcountry(Country Name) value is already exixst or not. If exist return 1 and not exists go to else condition SqlDataReader dr = conn.query(qry1); if (dr.Read()) { return data = "1"; } else { string qry = "insert into Country values('" + id + "','" + country + "')"; conn.nonquery(qry); return data = "3"; } } catch (Exception ex) { string x = ex.Message(); } return data; } this string value how can we set in a label My button_click function is protected void Button1_Click(object sender, EventArgs e) { string str = mas.Countryadd(txtcountry.Text, txtid.Text); if (str == "1") { Response.Write("<script>alert('Country Already Exist!!!!')</script>"); } else if (str == "3") { Response.Write("<script>alert('Country Added Succesfully')</script>"); } else { Label1.Text = str; } }
It's not the prettiest of code. Returning a string as a kind of status code is generally bad practice, because you don't know the range of possible values which can be returned, and what they mean. At the very least consider integer or even enum (which is named). That being said, I would handle the check and the insert in separate methods, and catch the exception in the click event handler - let a single method have a single responsibility: private void AddCountry(string country, string id) { using (SqlConnection conn = new SqlConnection()) { string sql = string.Format("INSERT INTO Country (Id, Country) VALUES ('{0}', '{1}')", id, country); using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.ExecuteNonQuery(); } } } private bool Exists(string country, string id) { using (SqlConnection conn = new SqlConnection()) { string sql = "SELECT Count(*) FROM Country WHERE Country='" + country + "'"; using (SqlCommand cmd = new SqlCommand(sql, conn)) { int count = (int)cmd.ExecuteScalar(); return count >= 1; } } } private void Button1_Click(object sender, EventArgs e) { try { if (Exists(txtcountry.Text, txtid.Text)) { Response.Write("<script>alert('Country Already Exist!!!!')</script>"); } else { AddCountry(txtcountry.Text, txtid.Text); Response.Write("<script>alert('Country Added Succesfully')</script>"); } } catch (Exception ex) { Label1.Text = ex.Message; } }
Catch(Exception e) { Label.Text= e.Message; }
Retrieve image from MySQL database and display on webpage using c#
I am using asp.net with c# to build website, but now i come into a problem. I insert image with blob type into mysql database but i cannot retrieve it. There is no picturebox layout for web controls. I want to use image.imageURL to display this image. I searched a lot, some recommend use another aspx page, some recommend using ashx, but i cannot find a detailed solution. Here is what i have now: protected void Button1_Click(object sender, EventArgs e) { String myname = Request.QueryString["Name"]; string myConnection = "server=127.0.0.1;uid=root;" + "pwd=81210ZLK;database=database;" + "Allow User Variables=True"; try { MySqlConnection myConn = new MySqlConnection(myConnection); myConn.ConnectionString = myConnection; MySqlCommand SelectCommand = new MySqlCommand(); string mySQL = "SELECT iddb1,fullname,age,gender,healthrecord,headpicture FROM database.db1 where fullname = #myname "; SelectCommand.CommandText = mySQL; SelectCommand.Parameters.AddWithValue("#myname", myname); SelectCommand.Connection = myConn; MySqlDataReader myReader; myConn.Open(); myReader = SelectCommand.ExecuteReader(); while (myReader.Read()) { Int16 ID = myReader.GetInt16(0); string FName = myReader.GetString(1); Int16 FAge = myReader.GetInt16(2); string FGender = myReader.GetString(3); string FRecord = myReader.GetString(4); ShowID.Text = ID.ToString(); ShowName.Text = FName.ToString(); ShowAge.Text = FAge.ToString(); ShowGender.Text = FGender.ToString(); ShowRecord.Text = FRecord.ToString(); byte[] imgg = (byte[])(myReader["headpicture"]); if (imgg == null) Image1.ImageUrl = null; else { MemoryStream mstream = new MemoryStream(imgg); // Image1.ImageURL = System.Drawing.Image.FromStream(mstream); } } myConn.Close(); } catch (Exception ex) { MessageBoxShow(this, ex.Message); } } Here come with the problem and i marked it with \\
Try this , Image1.ImageURL = "data:image/jpeg;base64,"+Convert.ToBase64String(imgg);
Why is this ignoring the where clause?
Why is the where clause being ignored in this code? It seems to be ignoring the where clause on the update which means every records has been written over. How can i fix this? Any help would be greatly appreciated. namespace ResitAssignment2 { public partial class HomeCareVisitEddit : Form { public HomeCareVisitEddit() { InitializeComponent(); } private void SubmitHCVA_Click(object sender, EventArgs e) { SqlConnection a = Database.GetConnection(); a.Open(); string sqltext; sqltext = #"update HomeCareVisit set PatientNo=#PatientNo, FurtherVisitRequired=#FurtherVisitRequired, AdvisoryNotes=#AdvisoryNotes, Prescription=#Prescription, TreatmentProvided=#TreatmentProvided, ActualVisitDateTime=#ActualVisitDateTime, Priority=#Priority, ScheduledDateTime=#ScheduledDateTime, TreatmentInstructions=#TreatmentInstructions, MedicalStaffID=#MedicalStaffID WHERE VisitRefNo=VisitRefNo"; SqlCommand command = new SqlCommand(sqltext, a); try { using (a) { command.Parameters.AddWithValue("#PatientNo", PatientNo.Text); command.Parameters.AddWithValue("#FurtherVisitRequired", FurtherVisitRequired.Text); command.Parameters.AddWithValue("#AdvisoryNotes", AdvisoryNotes.Text); command.Parameters.AddWithValue("#Prescription", Prescription.Text); command.Parameters.AddWithValue("#TreatmentProvided", TreatmentProvided.Text); command.Parameters.AddWithValue("#ActualVisitDateTime",SqlDbType.DateTime ); { DateTime.Parse(ActualVisitDateTime.Text); }; command.Parameters.AddWithValue("#Priority", Priority.Text); command.Parameters.AddWithValue("#ScheduledDateTime",SqlDbType.DateTime ); { DateTime.Parse(ScheduledDateTime.Text); }; command.Parameters.AddWithValue("#TreatmentInstructions", TreatmentInstructions.Text); command.Parameters.AddWithValue("#MedicalStaffID", MedicalStaffID.Text); command.Parameters.AddWithValue("#VisitRefNo", VisitRefNo.Text); command.ExecuteNonQuery(); MessageBox.Show("Record altered"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } a.Close(); } private void HomeCareVisitEddit_Load(object sender, EventArgs e) { SqlConnection a = Database.GetConnection(); a.Open(); string sqlText = "select * from HomeCareVisit where VisitRefNo =" + VisitRefNo; SqlCommand command = new SqlCommand(sqlText, a); SqlDataReader HomeCareVisitData = command.ExecuteReader(); while (HomeCareVisitData.Read()) { //DateTime actual = DateTime.Parse("ActualVisitDateTime"); //DateTime scheduled = DateTime.Parse("ActualVisitDateTieme"); PatientNo.Text = HomeCareVisitData["PatientNo"].ToString(); FurtherVisitRequired.Text = HomeCareVisitData["FurtherVisitRequired"].ToString(); AdvisoryNotes.Text = HomeCareVisitData["AdvisoryNotes"].ToString(); Prescription.Text = HomeCareVisitData["Prescription"].ToString(); TreatmentProvided.Text = HomeCareVisitData["TreatmentProvided"].ToString(); ActualVisitDateTime.Text = HomeCareVisitData["ActualVisitDateTime"].ToString(); Priority.Text = HomeCareVisitData["Priority"].ToString(); ScheduledDateTime.Text = HomeCareVisitData["ScheduledDateTime"].ToString(); TreatmentInstructions.Text = HomeCareVisitData["TreatmentInstructions"].ToString(); MedicalStaffID.Text = HomeCareVisitData["MedicalStaffID"].ToString(); } a.Close(); } } }
WHERE VisitRefNo=VisitRefNo"; should be WHERE VisitRefNo=#VisitRefNo";.
WHERE VisitRefNo=VisitRefNo Should be WHERE VisitRefNo=#VisitRefNo
Use ContentEditable to Save Into DB With ASP.NET?
I'm trying to create a web page where a user can edit the text and when they are done, they hit save and the new text entered is saved into the database. I'm not getting any errors in my code, but for some reason, the old text is just being rewritten into the db instead of the new text. Here is my code-behind: protected void saveBtn_Click(object sender, EventArgs e) { string newName; string newIntro; string newEduc; string newWork; h1New.Text = h1.Text; newName = h1New.Text; newIntro = intro.Text; newEduc = educ.Text; newWork = employ.Text; string connectionInfo = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString; using (SqlConnection connection = new SqlConnection(connectionInfo)) { connection.Open(); SqlCommand myCommand = new SqlCommand("UPDATE simpleContent SET userName = #newName, infoContent = #newIntro, educContent = #newEduc, workContent = #newWork WHERE userID = #userName", connection); try { string username = HttpContext.Current.User.Identity.Name; myCommand.Parameters.AddWithValue("#userName", username.ToString()); myCommand.Parameters.AddWithValue("#newName", newName.ToString()); myCommand.Parameters.AddWithValue("#newIntro", newIntro.ToString()); myCommand.Parameters.AddWithValue("#newEduc", newEduc.ToString()); myCommand.Parameters.AddWithValue("#newWork", newWork.ToString()); myCommand.ExecuteNonQuery(); connection.Close(); } catch { Response.Redirect("http://www.google.co.uk"); } } } I would appreciate any pointers that you may have.
try to put you code in format: protected void saveBtn_Click(object sender, EventArgs e) { // add variables string connectionInfo = (...) string commandText = (...) using (...){ SqlCommand myCommand = (...) // add parameters try { connection.Open(); myCommand.ExecuteNonQuery(); connection.Close(); } catch (Exception ex) { (...) } }