1

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&#39;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:&nbsp;
<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.) &nbsp;
<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.

Closet Techy
  • 51
  • 1
  • 1
  • 7
  • You don't seem to have any connections. Every example has connections. Why didn't you use connections? – Hogan Mar 06 '13 at 22:15
  • Have you considered using some of the more convenient constructs in ASP.NET like a `SQLDataSource` or `ObjectDataSource` component? – Robert Harvey Mar 06 '13 at 22:15
  • Oh, and what Hogan said. You're retrieving a connection string, but you're not creating and using a connection with it. – Robert Harvey Mar 06 '13 at 22:16
  • Also, when you are working with parameters, make sure you are being consistent and use the "@parameterName". – Brian Mar 06 '13 at 22:17
  • @Brian - He does not have a connection object, how can he call open on it? – Hogan Mar 06 '13 at 22:19
  • @Hogan - Oops, you are right. Deleting that comment. – Brian Mar 06 '13 at 22:19
  • Ok - I added in a connection and it still doesn't seem to be working. Am I missing something in the connection string?... – Closet Techy Mar 06 '13 at 22:54
  • "FirstApp" is a string value, not a reference to your configuration item. You'll need to get the value via the configuration manager. See: http://stackoverflow.com/questions/6536715/get-connection-string-from-app-config – Quintium Mar 06 '13 at 23:00
  • just out of curiosity, what examples were you looking at to get your code from? As folks have stated, you're not opening a connection, or executing your query. Also, I use your way also, but there's a .NET object specifically tailored to DML SQL, http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.aspx – RandomUs1r Mar 06 '13 at 23:03
  • I finally got the connection to work. I used many different examples and some of them had different ways of connecting. VS kept giving me errors saying that there was no variable called "open" so that's why I took the statement out, thinking it was wrong. However, I got everything up and running now. Just can't get the delete button to work. Thanks for everyone's help! – Closet Techy Mar 08 '13 at 21:20

3 Answers3

6

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();

    }
}
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Joe Enos
  • 39,478
  • 11
  • 80
  • 136
  • 2
    AH! Someone using a connection, I feel better now. – Hogan Mar 06 '13 at 22:17
  • But I'm not trying to execute a SQL command inside of VS. I'm trying to use a stored procedure in SQL Server Management studios. So how would I still use the "conn.open();" and then implement my stored procedure?... That's what I'm trying to do. I just don't know how to do it. >. – Closet Techy Mar 06 '13 at 22:23
  • 1
    @ClosetTechy A stored proc is no different from any other SQL statement - you still create a command for it and execute it. The only difference is your `CommandText` is the stored proc name, and you set the `CommandType` to be `StoredProcedure`. Other than that, you execute it the same as you would any other SQL statement. – Joe Enos Mar 06 '13 at 22:25
  • Ahhh! That makes so much more sense. Thank you! I will go try that then! – Closet Techy Mar 06 '13 at 22:30
4

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();
0

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();
            }
        }
    }
bsmith95610
  • 53
  • 1
  • 9
  • I actually think this is a good idea but it doesn't seem to want to work for me. The line: "using (SqlCommand cmd = new SqlCommand("usp_proc_delete", conn.CreateCommand()))" is throwing me two different errors. 1) The best overloaded method match for 'System.Data.SqlClient.SqlCommand.SqlCommand(string, System.Data.SqlClient.SqlConnection)' has some invalid arguments and 2) Argument 2:(conn.CreateCommand()) cannot convert from 'System.Data.SqlClient.SqlCommand' to 'System.Data.SqlClient.SqlConnection – Closet Techy Mar 06 '13 at 22:41