Solved

Need help with inserting data into a sql server database.

Posted on 2015-01-08
7
88 Views
Last Modified: 2015-01-12
Hello Experts,

I need some assistance with a bit of code that's not working for me.  I am attempting to insert the contents of a text box into a table.  Easy enough, but for some reason I can't get it to work.  I am not getting an error message.  When I click the submit button nothing happens.  Any help would be greatly appreciated.  

I am using Visual Studio 2012, SqlServer 2008, asp.net web forms, and c#.

Here is the c# code I am using:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

namespace saef_web_app
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        SqlConnection conn = new SqlConnection("Data Source = TESTMEPRDSQL\\TESTME;Initial Catalog=saef;Integrated Security=True");
        protected void Page_Load(object sender, EventArgs e)
        {      
        }
        
        public void peeps()
        {
            string firstName = txt_emp_fn.Text;
        }
        protected void newEmpBtn_Click(object sender, EventArgs e)
        {
            SqlCommand insertcmd = new SqlCommand("INSERT INTO tbl_emp(emp_fn) VALUES(txt_emp_fn.Text)",conn);
            
            try
            {
                conn.Open();
                insertcmd.ExecuteNonQuery();
                Literal1.Text = "Data inserted successfully";
                conn.Close();
                peeps();
            }
            catch (Exception ex)
            {
                Literal1.Text = ex.Message;
            }
        }
    }
}

Open in new window


Thanks,
J
0
Comment
Question by:ferguson_jerald
7 Comments
 
LVL 65

Expert Comment

by:Jim Horn
Comment Utility
> SqlCommand insertcmd = new SqlCommand("INSERT INTO tbl_emp(emp_fn) VALUES(txt_emp_fn.Text)",conn);
For starters, txt_emp_fn.Text is INSIDE the double-quotes, so the above statement would insert that exact text, and not the contents of txt_emp_fn.   I'm guessing you mean something like this...

 SqlCommand insertcmd = new SqlCommand("INSERT INTO tbl_emp(emp_fn) VALUES(" & txt_emp_fn.Text & ")",conn);

Disclaimer:  I know SQL well, but what I know about C# can be written on the back of a matchbook cover, in very large letters, using a grease pencil.
0
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
Change this line in the code

insertcmd.ExecuteNonQuery();

To this :

Dim effected As Integer = insertcmd.ExecuteNonQuery();

Then tell me what the value of effected is after the line executes.
0
 

Author Comment

by:ferguson_jerald
Comment Utility
Thanks for the quick responses.  

Jim, your suggestion didn't work for the code.  Instead I get the error message that "Operator '&' cannot be applied to operands of type 'string' and 'string'.

Fernando, I changed insertcmd.ExecuteNonQuery(); to Dim effected As Integer = insertcmd.ExecuteNonQuery(); and got the following errors:

'The type or namespace name 'Dim' could not be found (are you missing a using directive or an assembly reference?)'
AND
'The type or namespace 'As' could not be found (are you missing a using directive or an assembly reference?)'

Thanks for the help thus far.  Do you have any other suggestions?
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 62

Assisted Solution

by:Fernando Soto
Fernando Soto earned 250 total points
Comment Utility
Sorry, I don't know what I was thinking I gave you the code in VB not C#. Change  to this

int effected = insertcmd.ExecuteNonQuery();
0
 
LVL 45

Accepted Solution

by:
Vitor Montalvão earned 250 total points
Comment Utility
Jim's also gave you a VB solution instead of C#. In C# you need to use the '+' sign to concatenate strings:
 SqlCommand insertcmd = new SqlCommand("INSERT INTO tbl_emp (emp_fn) VALUES('" + txt_emp_fn.Text + "')",conn);

Open in new window

NOTE: I also add single quote because you'll need it for text fields.
0
 

Author Comment

by:ferguson_jerald
Comment Utility
Thanks for the feedback.  This seemed to be a tough one to learn with, but it makes sense now.  I need to pay attention to the syntax.  I was able to get it working by implementing your fixes along with a slight change in the code.  Here's what I got to work:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

namespace saef_web_app
{
    public partial class insertTblEmp : System.Web.UI.Page
    {
        SqlConnection conn = new SqlConnection("Data Source = TESTMEPRDSQL\\TESTME;Initial Catalog=saef;Integrated Security=True");
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void newEmpBtn_Click(object sender, EventArgs e)
        {
            SqlCommand insertcmd = new SqlCommand("INSERT INTO tbl_emp (emp_fn, emp_ln, emp_add, emp_city, emp_state, emp_zip) VALUES('" + txt_emp_fn.Text + "," + txt_emp_ln.Text + ", " + txt_emp_add.Text +", " + txt_emp_city.Text + ", " + txt_emp_state + ", " + txt_emp_zip.Text + "',)", conn);

            try
            {
                conn.Open();
                insertcmd.ExecuteNonQuery();
                Literal1.Text = "Data inserted successfully";
                conn.Close();
            }
            catch (Exception ex)
            {
                Literal1.Text = ex.Message;
            }
        }
    }
}

Open in new window


As you can see I added a couple more fields, and it works great.  Thanks for all of your assistance.
0
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
Not a problem, glad to help.
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
ssms - object execution statistics 12 37
Long URL in SMS 6 22
using t-sql EXISTS 8 23
Different Delete Messages 7 10
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now