Save the data in database - c#

Here I am trying to save the data in data base. Whatever data user enters it has to save in database and it has to save in page it self also. when user opens page that data has to display.
Code for aspx page
<asp:Label runat="server" ID="lblCnct" Text="Contact Number" AssociatedControlID="txtCnct" CssClass="control-label" />
<asp:TextBox runat="server" ID="txtCnct" CssClass="form-control" />
<asp:Label runat="server" ID="lblAltCnct" Text="Alternative Contact Number" AssociatedControlID="txtAltCnct" CssClass="control-label" />
<asp:TextBox runat="server" ID="txtAltCnct" CssClass="form-control" />
<asp:Label runat="server" ID="lblEmcnct" Text="Emergency Contact Number" AssociatedControlID="txtEmrCnct" CssClass="control-label" />
<asp:TextBox runat="server" ID="txtEmrCnct" CssClass="form-control" />
Button code saving the data in database
<button type="button" class="btn btn-primary" aria-label="Left Align" runat="server" onserverclick="btnContactInfoSave_click">
code for aspx.cs page
btnContactInfoSave_click code for saving the data in database.
protected void btnContactInfoSave_click(object sender, EventArgs e)
{
string[] ContactInfoData = new string[4];
ContactInfoData[0] = GlobalVars.UserEmail;
ContactInfoData[1] = txtCnct.Text;
ContactInfoData[2] = txtAltCnct.Text;
ContactInfoData[3] = txtEmrCnct.Text;
Utilities.sqlUploadContactInfoData(ContactInfoData);
}
}
public static void sqlUploadContactInfoData(string[] Userdata)
{
using (SqlConnection sqlConn = jPortalDBConnection())
{
try
{
sqlConn.Open();
string spName = "spUploadContactInfoData";
SqlCommand cmd = new SqlCommand(spName, sqlConn);
cmd.Parameters.AddWithValue("#txtCnct", Userdata[0].ToString());
cmd.Parameters.AddWithValue("#txtAltCnct", Userdata[1].ToString());
cmd.Parameters.AddWithValue("#txtEmrCnct", Userdata[2].ToString());
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConn;
cmd.ExecuteNonQuery();
}
catch (SqlException)
{
ErrorMsg("Server Error", "Server Error ! Please try again Later.");
}
}
}
After entering the data when I am trying to save the data it is not saving the data. button is not triggering. Any wrong in this code..???

Try with This. This is the way to Insert data into DB
SQL connection code for connecting database...
public static void sqlUploadContactInfoData(string[] Userdata)
{
using (SqlConnection sqlConn = jPortalDBConnection())
{
try
{
sqlConn.Open();
string spName = "spUploadContactInfoData";
SqlCommand cmd = new SqlCommand(spName, sqlConn);
cmd.Parameters.AddWithValue("#txtCnct", txtCnct.Text);
cmd.Parameters.AddWithValue("#txtAltCnct", txtAltCnct.Text);
cmd.Parameters.AddWithValue("#txtEmrCnct", txtEmrCnct.Text);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConn;
cmd.ExecuteNonQuery();
}
catch (SqlException)
{
ErrorMsg("Server Error", "Server Error ! Please try again Later.");
}
}
}

From your web from designer double click on the button check weather it pointing to the Button event you expected to be invoked.else this will create a event handler for you.
If you are assigning the click handler in code behind, make sure that it is not inside an IsPostBack == false check :
make sure CausesValidation = "false" attribute of button like:
runat="server" and OnClick="btnContactInfoSave_click" check these attribute exist in your asp button

Try button in this way:
<asp:Button ID="AddMore_Button" class="btn btn-primary" runat="server" Text="" OnClick="btnContactInfoSave_click" />

Related

ASP.NET - Unable to insert data into database

I know that the connection string is not the problem because I can read data from the database fine but I cannot figure out why I cannot insert data into the database.
.aspx file
<div class="column one-second">
<asp:TextBox placeholder="Your name" type="text" name="name" id="namelbl" size="40" aria-required="true" aria-invalid="false" runat="server"></asp:TextBox>
</div>
<div class="column one-second">
<asp:TextBox placeholder="location" type="text" name="location" id="LocationLbl" size="40" aria-required="true" aria-invalid="false" runat="server"></asp:TextBox>
</div>
<div class="column one">
<asp:TextBox placeholder="Body" type="text" name="text" id="TextLBL" size="40" aria-required="true" aria-invalid="false" runat="server"></asp:TextBox>
</div>
<div class="column one">
<asp:FileUpload id="FileUpload1" runat="server"> </asp:FileUpload>
<asp:Label ID="lblmessage" runat="server" />
</div>
<div class="column one">
<asp:Button id="submit" Text="Submit" runat="server" OnClick="submit_Click"> </asp:Button>
</div>
C# function
protected void submit_Click(object sender, EventArgs e)
{
Console.WriteLine("BUTTON CLICKED");
string constr = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "INSERT INTO blo(Title, post, location) VALUES (#Title, #post, #location)";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
string title = namelbl.Text;
Console.WriteLine(title);
cmd.Parameters.AddWithValue("Title", title);
string post = TextLBL.Text;
cmd.Parameters.AddWithValue("post", post);
string location = LocationLbl.Text;
cmd.Parameters.AddWithValue("location", location);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Your query was not able to work as you mistype the parameter name in your .AddWithValue().
cmd.Parameters.AddWithValue("Title", title);
cmd.Parameters.AddWithValue("post", post);
cmd.Parameters.AddWithValue("location", location);
The correct way should be:
cmd.Parameters.AddWithValue("#Title", title);
cmd.Parameters.AddWithValue("#post", post);
cmd.Parameters.AddWithValue("#location", location);
RECOMMENDATIONS
1. It is recommended not to use `.AddWithValue()` as the concern mentioned in this [article](https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/). Please ensure that you need to pass the value with **exact datatype and length** that matches the respective table column in the `SqlParameter`.
cmd.Parameters.Add("#Param", <<MySqlDbType>>, <<Length>>).Value = value;
As you apply using block for MySqlConnection, MySqlCommand, you don't have to manually call con.Close() as these IDisposable objects will dispose the resources & connection automatically as mentioned in this article.
(Optional) Add try catch block and get value from ExecuteNonQuery() for verifying the record is inserted into the database and exception handling.
Exception handling will be useful in debugging and handling the exception hit during the execution. At the same time, you can provide a meaningful error message to notify the users.
ExecuteNonQuery() able to return the value indicate
The number of rows affected.
Hence, this will also be useful to return a useful message to notify whether the record is successfully inserted/updated into the database or not.
In the end, your code should be:
try
{
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "INSERT INTO blo(Title, post, location) VALUES (#Title, #Post, #Location)";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
string title = namelbl.Text;
Console.WriteLine(title);
cmd.Parameters.AddWithValue("#Title", title);
string post = TextLBL.Text;
cmd.Parameters.AddWithValue("#Post", post);
string location = LocationLbl.Text;
cmd.Parameters.AddWithValue("#Location", location);
con.Open();
var recordAffected = (int)cmd.ExecuteNonQuery();
if (recordAffected > 0)
{
// Record successfully inserted case
}
else
{
// Record fail inserted case
}
}
}
}
catch (Exception ex)
{
// Handling exception
}
Edited:
Much appreciated and credited to the comment provided by #BradleyGrainger, I had 'strikethrough' recommendation 1 as the concerns mentioned in Can We Stop Using .AddWithValue() are handled by MySql.
Start Using AddWithValue
The primary reason that AddWithValue is OK to use is that MySQL’s text protocol is not typed in a way that matters for client-side type inference.

Required Field Validation Error Message is working for Text Box but not working for Drop Down List

In my aspx page, I have 2 search options
One is for searching a product through text box.
Another is viewing category by drop down selection.
So this is what I have done in my .aspx file
<div class="searchbox">
<strong>Search by Product Name<br /></strong>
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button8" runat="server" OnClick="Search_Product" Text="Search Product" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="Please enter a product name"></asp:RequiredFieldValidator>
<asp:Label ID="Label3" runat="server"></asp:Label>
<br />
<br />
</div>
<br />
<div class="searchbox">
<strong>View by Category: View Product on Category Selection</strong><br />
<br />
<asp:DropDownList AppendDataBoundItems ="true" ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1" DataTextField="Product_Category_Name" DataValueField="Product_Category_Name">
<asp:ListItem>Select a Category</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Grocery_DemoConnectionString %>" SelectCommand="SELECT Product_Category_Name FROM Product_Category"></asp:SqlDataSource>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="DropDownList1" ErrorMessage="Please select a category"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Button ID="Button9" runat="server" OnClick="View_Product" CausesValidation="false" Text="View Product" />
</div>
And this is what I have done in my .cs file
private void DisplayProducts()
{
if (Session["BranchAdmin"] != null)
{
string branch = Session["BranchAdmin"].ToString();
string CS;
CS = "data source=LAPTOP-ODS96MIK\\MSSQL2014; database = Grocery_Demo; integrated security=SSPI";
SqlConnection con = new SqlConnection(CS);
SqlCommand cmd = new SqlCommand("AdminViewProductsOnBranch", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#GroceryBranchName", branch);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
}
protected void Search_Product(object sender, EventArgs e)
{
if (Session["BranchAdmin"] != null)
{
string branch = Session["BranchAdmin"].ToString();
string CS;
CS = "data source=LAPTOP-ODS96MIK\\MSSQL2014; database = Grocery_Demo; integrated security=SSPI";
SqlConnection con = new SqlConnection(CS);
SqlCommand cmd = new SqlCommand("AdminSearchProductsOnBranch", con);
cmd.Parameters.AddWithValue("#ProductName", TextBox1.Text + "%");
cmd.Parameters.AddWithValue("#GroceryBranchName", branch);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
con.Open();
SqlDataReader read = cmd.ExecuteReader();
read.Read();
if (read.HasRows == false)
{
Label3.Text = "Couldn't find your product";
con.Close();
}
}
}
protected void View_Product(object sender, EventArgs e)
{
if (Session["BranchAdmin"] != null)
{
string branch = Session["BranchAdmin"].ToString();
string CS;
CS = "data source=LAPTOP-ODS96MIK\\MSSQL2014; database = Grocery_Demo; integrated security=SSPI";
SqlConnection con = new SqlConnection(CS);
SqlCommand cmd = new SqlCommand("AdminViewCategoriesOnBranch", con);
cmd.Parameters.AddWithValue("#ProductCategoryName", DropDownList1.SelectedValue);
cmd.Parameters.AddWithValue("#GroceryBranchName", branch);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
con.Open();
SqlDataReader read = cmd.ExecuteReader();
read.Read();
con.Close();
}
}
If I search a Product in text box and click on the search button it shows the grid view display if it has the data in table. If the search result doesn't match with data in table, then it shows a Label Text Message: "Couldn't find your Product". And If I keep the text box blank and click on search button, it shows a required field validation message "Please enter a product name".
Everything is OK with product search option through text box.
On the other hand, when I select a category from drop down and click on view button, it works perfectly.
Now the issues is if I don't select any category from drop down and click on view button, then it is not showing the required field validation error message "Please select a category" and at the same time it is turning the grid view display into blank which I don't want.
What I'm trying to achieve is that if a category is not selected from drop down list and then a view button is clicked, it should show the required field validation error message "Please select a category" and at the same time it should not change the default Grid View display into blank.
If there is any mistake in the codes in either .aspx file or .cs, then it would be helpful if the recommended solution syntax is provided.
Specify ValidationGroup for TextBox1 required field validator and Search button controls like this:
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ValidationGroup="SearchByName" ErrorMessage="Please enter a product name"></asp:RequiredFieldValidator>
<asp:Button ValidationGroup="SearchByName" ID="Button8" runat="server" OnClick="Search_Product" Text="Search Product" />
Specify a different ValidationGroup from dropdown validator and View_Product button
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="DropDownList1" ErrorMessage="Please select a category" ValidationGroup="SearchByCategory"></asp:RequiredFieldValidator>
<asp:Button ID="Button9" runat="server" OnClick="View_Product" ValidationGroup="SearchByCategory" Text="View Product" />
Note: I have removed the CausesValidation="false" attribute from View Product button.
Set the value of default list item as -1 and then specifying the InitialValue of dropdown validator?
<asp:ListItem value="-1">Select a Category</asp:ListItem> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="DropDownList1" InitialValue="-1" ErrorMessage="Please select a category" ValidationGroup="SearchByCategory">
Please try this
<asp:RequiredFieldValidator runat="server" ControlToValidate="DropDownList1"
cssclass="required" display="dynamic" errormessage="Please select a category" setfocusonerror="true"
initialvalue="0"></asp:RequiredFieldValidator>
Add display="dynamic"property.

Code Not Preventing Duplicate E-mail Addresses in Database

The code I have is allowing duplicate e-mails to be added to the database. I added a line of code before allowing entry into the database to prevent duplicate e-mail addresses to be added, however with this code I am still getting duplicate e-mails. I have provided both the form code in asp.net & the c# code. Please help.
Originally I was getting an error & I debugged the code in VS & realized that I actually had the wrong specification for the email entry, that has been corrected. In the VS debugger I see values for TextBox1.Text & TextBox2.Text, i also see the e-mail address passing through the string query = the issue however is that even if the e-mail is already in the database, it still gets added again. Any improvements to fix this issue with my code? Is my logic wrong perhaps?
c# code:
protected void Button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["northwind"].ToString();
con.Open();
string query = "SELECT COUNT(ID) FROM Table1 WHERE pEmail= '" + TextBox2.Text +"'";
OleDbCommand cmd = new OleDbCommand(query, con);
var count = cmd.ExecuteNonQuery();
if (count > 0)
{
Label1.Text = "email is already in use";
}
else {
cmd.CommandText = "insert into[Table1](pName, pEmail)values(#nm,#em)";
cmd.Parameters.AddWithValue("#nm", TextBox1.Text);
cmd.Parameters.AddWithValue("#em", TextBox2.Text);
cmd.Connection = con;
int a = cmd.ExecuteNonQuery();
if (a>0)
{
Label1.Text = "Inserted Sucessfully!";
}
}
}
}
Form Code:
<form id="form1" runat="server">
<div style="height: 138px">
Enter Name:<asp:TextBox ID="TextBox1" runat="server" style="margin-left: 12px"></asp:TextBox>
<asp:RequiredFieldValidator
id="reqName"
ControlToValidate="TextBox1"
Style="color:Red"
ErrorMessage="Please enter your name!"
runat="server" />
<br />
Enter Email:
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator
id="ValidEmail"
ControlToValidate="TextBox2"
Style="color:Red"
ValidationExpression="^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"
ErrorMessage="Invalid Email Entry"
runat="server" />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>
You should use ExecuteScalar instead of ExecuteNonQuery to get the row count
Original:
var count = cmd.ExecuteNonQuery();
Suggest to change:
var count = cmd.ExecuteScalar();
Refer to https://stackoverflow.com/a/4269651/1050927
The ExecuteNonQuery Method returns the number of row(s) affected by either an INSERT, an UPDATE or a DELETE. This method is to be used to perform DML (data manipulation language) statements as stated previously.
The ExecuteScalar Method will return a single value in the first row, first column from a SELECT statement. This method is to be used when you expect only one value from the query to be returned.
Use ExecuteScalar and Convert the result to int. I also recommend you to change the sql query concatenation to parameters, and if you are using ASP.NET Validators, you must check the property IsValid of the page as it will tell you if the controls has passed validation (remember that users can disable javascript and post the form).
protected void Button1_Click(object sender, EventArgs e)
{
if (IsValid)
{
using (var con = new OleDbConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["northwind"].ToString();
con.Open();
using (var cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT COUNT(ID) FROM Table1 WHERE pEmail= #em";
cmd.Parameters.AddWithValue("#em", TextBox2.Text);
int count = Convert.ToInt32(cmd.ExecutScalar());
if (count > 0)
{
Label1.Text = "email is already in use";
}
else
{
cmd.CommandText = "insert into[Table1](pName, pEmail)values(#nm, #em)";
cmd.Parameters.AddWithValue("#nm", TextBox1.Text);
// not need to add #em parameter, it was added previously
int insertedRows = cmd.ExecuteNonQuery();
if (insertedRows > 0)
{
Label1.Text = "Inserted Sucessfully!";
}
}
}
}
}
}

How do I get the textbox value to the database within a repeater?

I have a repeater that I populate from a database:
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(#"SELECT CommunityName, CID, Budget FROM Donation WHERE Year = year(getdate()) ORDER BY CommunityName", conn);
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet myDataSet = new DataSet();
adp.Fill(myDataSet);
myRep.ItemDataBound += new RepeaterItemEventHandler(myRep_ItemDataBound);
myRep.DataSource = myDataSet;
myRep.DataBind();
}
void myRep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var textbox = e.Item.FindControl("community");
textbox.ClientIDMode = ClientIDMode.Static;
textbox.ID = "community" + (e.Item.ItemIndex + 1);
}
Repeater:
<asp:UpdatePanel ID="UpdatePanel" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:Repeater ID="myRep" runat="server">
<ItemTemplate>
<div class="form-group">
<asp:Label ID='thisLbl' runat="server" Text='<%# Eval("CommunityName") %>' />
<asp:TextBox runat="server" ID="community" Text='<%# Eval("Budget") %>' CssClass="form-control" />
</div>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
This creates 6 textboxes with labels and values, now my question is how do I detect which of these boxes belongs to the record it was initially pulled from in the database? I want to be able to modify the value in these boxes and hit a button to save them back to the database but I can't seem to wrap my head around getting them to the proper records.
Should I set the ID of the textbox to something I can parse through and match with the proper record? In the ItemDataBound?
You have to put a hidden field inside the repeater item template that takes the value from budget, and another hidden field to keep the CID value that has to be read in the post back request. Of course you need also a button and its click event handler.
<asp:Repeater ID="myRep" runat="server">
<ItemTemplate>
<div class="form-group">
<asp:Label ID='thisLbl' runat="server" Text='<%# Eval("CommunityName") %>' />
<asp:TextBox runat="server" ID="txtBudget" Text='<%# Eval("Budget") %>' CssClass="form-control" />
<asp:HiddenField runat="server" ID="hdOriginalBudget" Value='<%# Eval("Budget") %>' />
<asp:HiddenField runat="server" ID="hdCID" Value='<%# Eval("CID") %>' />
</div>
</ItemTemplate>
</asp:Repeater>
<br />
<asp:Button ID="btn" runat="server" OnClick="btn_Click" />
In your code behind you need to loop inside the repeater to check whether the text box has been changed by comparing its value to the hidden field. After you save the budget value in the database you need to realign the hidden field value to the the new value entered by the user, otherwise you will always save that value after each post back:
protected void btn_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in myRep.Items)
{
var txtBudget = item.FindControl("txtBudget") as TextBox;
var hdOriginalBudget = item.FindControl("hdOriginalBudget") as HiddenField;
var hdCID = item.FindControl("hdCID") as HiddenField;
if (txtBudget.Text != hdOriginalBudget.Value)
{
//If you enter here means the user changed the value of the text box
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(#"UPDATE Donation SET Budget = #Budget WHERE CID = #CID", conn);
cmd.Parameters.Add(new SqlParameter("#Budget", int.Parse(txtBudget.Text)));
cmd.Parameters.Add(new SqlParameter("#CID", int.Parse(hdCID.Value)));
conn.Open();
cmd.ExecuteNonQuery();
}
//After you write in the database realign the values
hdOriginalBudget.Value = txtBudget.Text;
}
}
}
Take care that my code is missing the most basic validation, so if the user writes an invalid value in the textbox (for example "yyy") it breaks. So please don't put it in production as it is!

Using a SQL Server Stored Procedure in Visual Studio

My Experience & What I'm Using
So I'm just starting off with a very basic web application in ASP.NET to gain a little more familiarity with SQL Server Management Studios and Visual Studios 2010. Normally, I use MySQL, PHP, and Sublime Text Editor 2. I'm not very experienced with C# and implementing a database in Visual Studios. So I'm trying to use a stored procedure from SQL Server Management Studios and implement it in Visual Studios 2010.
The Issue
So here's my problem: I'm trying to create a basic webpage that links to a SQL Server and be able to add, delete, search and display all records from the database. Now I've written my own code based on what I thought was correct for add/delete and nothing happens when I click the buttons. So I'm sure you can see where my frustration derives from. I'm not sure if the issue is in my C# coding or in my SQL coding.
I'd like to focus on just getting my add/delete buttons to work and then to figure out the logic to display all files. I'd like to be able to click a button and then have it show all files instead of just displaying a grid. My database is called FirstApp.
Here's what's in my web.config file:
<add name="FirstApp" connectionString="Data Source=PCNAME\SQLEXPRESS;Initial Catalog=FirstApp;Integrated Security=True"
providerName="System.Data.SqlClient" />
Now this is what's in my Default.aspx.cs file:
*CORRECT CODE NOW!*
namespace FirstApp
{
public partial class _Default : System.Web.UI.Page
{
public string CommandArgument { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
}
private void MessageBox(string msg)
{
Label lbl = new Label();
lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + msg + "')</script>";
Page.Controls.Add(lbl);
}
//Add a new company to the database
protected void add_Click(object sender, EventArgs e)
{
SqlDataReader rdr = null;
string connectionString = null;
SqlConnection cnn;
connectionString = "Data Source=ITXDK29M91\\SQLEXPRESS;Initial Catalog=FirstApp;Integrated Security=True";
cnn = new SqlConnection(connectionString);
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand("dbo.Add_Company", cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#companyname", companyname.Text);
cmd.Parameters.AddWithValue("#companyphone", companyphone.Text);
cmd.Parameters.AddWithValue("#companyid", companyid.Text);
cmd.Parameters.AddWithValue("#companytype", companytype.Text);
rdr = cmd.ExecuteReader();
}
finally
{
//Close the connections
if (cnn != null)
{
cnn.Close();
}
if (rdr != null)
{
rdr.Close();
}
}
}
//Delete a company from the database
protected void delete_Click(object sender, EventArgs e)
{
SqlDataReader rdr = null;
SqlConnection cnn;
string connectionString = null;
connectionString = "Data Source=ITXDK29M91\\SQLEXPRESS;Initial Catalog=FirstApp;Integrated Security=True";
cnn = new SqlConnection(connectionString);
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand("dbo.deleteCo", cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ID", SqlDbType.Int);
rdr = cmd.ExecuteReader();
}
finally
{
//Close the connections
if (cnn != null)
{
cnn.Close();
}
if (rdr != null)
{
rdr.Close();
}
}
}
protected void Search_Click(object sender, EventArgs e)
{
}
protected void Getall_Click(object sender, EventArgs e)
{
}
}
}
This is what's in my Source Code in Default.aspx
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2>Ready for an Adventure? Let's get started!
</h2> <hr />This is where you can enter information about your company.
<br />
<form method="post" action="">
Company Name:<br />
<asp:TextBox ID="companyname" runat="server"></asp:TextBox>
<br />
Company Phone Number:<br />
<asp:TextBox ID="companyphone" runat="server"></asp:TextBox>
<br />
Company Tax ID Number:
<br />
<asp:TextBox ID="companyid" runat="server"></asp:TextBox>
<br />
Type of business: <br />
<asp:TextBox ID="companytype" runat="server"></asp:TextBox>
<br />
<asp:Button ID="add" runat="server" BackColor="DeepSkyBlue"
BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"
CssClass="submitButton" Font-Names="Palatino Linotype" ForeColor="White"
onclick="add_Click" Text="Submit" Width="128px" />
</form> <hr />
Want to delete your company information?<br />
Enter in the Company ID Number:
<br />
<asp:TextBox ID="PrimaryKey" runat="server" Width="120px"></asp:TextBox>
<br />
<asp:Button ID="delete" runat="server" BackColor="DeepSkyBlue"
BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"
CssClass="submitButton" Font-Names="Palatino Linotype" ForeColor="White"
onclick="delete_Click" Text="Delete Info" Width="119px" />
<br />
<hr />
Looking for similar companies?
<br />
(Ex: Retail, Designer, Restaurant, etc.)
<br />
Enter the type of company:
<br />
<asp:TextBox ID="scompanyid" runat="server" Width="120px"></asp:TextBox>
<br />
<asp:Button ID="Search" runat="server" BackColor="DeepSkyBlue"
BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"
CssClass="submitButton" Font-Names="Palatino Linotype" ForeColor="White"
onclick="Search_Click" Text="Start Searching!" Width="119px" />
<br />
<hr />
Want to see all the companies that we work with? <br />
Click the button below!
<br />
<asp:Button ID="Getall" runat="server" BackColor="DeepSkyBlue"
BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"
CssClass="submitButton" Font-Names="Palatino Linotype" ForeColor="White"
onclick="Getall_Click" Text="Get all records!" Width="119px" />
<br />
<br />
</asp:Content>
UPDATE: I've updated the code to display the correct code. The add button works but my delete button is not. I'm still trying to figure that one out.
You're not actually opening a connection or executing your SQL commands. Generally, the way you execute a simple command is:
using (var conn = new SqlConnection(connectionString))
{
using (var comm = conn.CreateCommand())
{
conn.Open();
comm.CommandText = "SOME SQL HERE";
// command type, parameters, etc.
//pick one of the following
comm.ExecuteNonQuery();
int value = (int)comm.ExecuteScalar();
SqlDataReader reader = comm.ExecuteReader();
}
}
You need to actually execute the command. There are four types of execution (depending on the type of results you'll be expecting from your query statement)
ExecuteReader - Rows and columns returned (e.g. Normal select queries)
ExecuteNonquery - No results expected. (e.g. Deleting a record)
ExecuteScalar - Single value (e.g. Count, Max, etc..)
ExecuteXMLReader - For XML stuff
Something like this for the add
cmd.ExecuteNonquery();
Even before worrying about executing the command though, you always need an open connection through which you execute commands and you need to link your command to it:
SqlConnection cn = new SqlConnection(connStr);
cn.Command = cmd;
cn.Open();
<your command/parameter code here>
cmd.ExecuteNonquery();
And don't forget to put stuff back the way you found it:
cmd.Close();
cn.Close();
There are other suggestions I'd make--like making the phone number varchar since you're not going to do arithmetic on it as a number--but this is not your real question here and now.
Best wishes!
FYI: Side topic: Whenever you begin to use commands to return results, you will not need a "new" for your SqlDataReaders because commands executed with ExecuteReader create and return an SqlDataReader object. This means you can just do this
//This next line not needed
//dr = new SqlDataReader()
SqlDataReader dr = cmd.ExecuteReader();
It looks like you aren't executing your SQL statements. Try creating a method that does the below then call that method from your delete button click event.
public static void DeleteSomething()
{
using (var conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("usp_proc_delete", conn.CreateCommand()))
{
conn.Open()
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PrimaryKey", SqlDbType.Int);
cmd.ExecuteNonQuery();
}
}
}

Categories