Search code examples
c#asp.netado.net

How to insert data into DB from textbox


Consider:

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

namespace Elibrary_management2
{
    public partial class user_registration : System.Web.UI.Page
    {
        string strcon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        // Signup button click
        protected void Button1_Click(object sender, EventArgs e)
        {
            // Response.Write("<script>alert('successfull')</script>");
            try
            {
                SqlConnection con = new SqlConnection(strcon);
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }

                string sqlquary = ("insert into member_master_tbl(full_name,dob,contact_no,email,state,city,pincode,full_address,member_id,password,account_status) values(@full_name,dob,@contact_no,@email,@state,@city,@pincode,@full_address,@member_id,@password,@account_status");
                SqlCommand cmd = new SqlCommand(sqlquary, con);
                cmd.Parameters.AddWithValue("@full_name", TextBox1.Text.Trim());
                cmd.Parameters.AddWithValue("@dob", TextBox2.Text.Trim());
                cmd.Parameters.AddWithValue("@contact_no", TextBox2.Text.Trim());
                cmd.Parameters.AddWithValue("@email", TextBox4.Text.Trim());
                cmd.Parameters.AddWithValue("@state", DropDownList1.SelectedItem.Value);
                cmd.Parameters.AddWithValue("@city", TextBox6.Text.Trim());
                cmd.Parameters.AddWithValue("@pincode", TextBox7.Text.Trim());
                cmd.Parameters.AddWithValue("@full_address", TextBox8.Text.Trim());
                cmd.Parameters.AddWithValue("@member_id", TextBox9.Text.Trim());
                cmd.Parameters.AddWithValue("@password", TextBox5.Text.Trim());
                cmd.Parameters.AddWithValue("@account_status", "pending");

                cmd.ExecuteNonQuery();
                con.Close();
                Response.Write("<script>alert('Signup Successfull');</script>");
            }
            catch(Exception ex)
            {
                Response.Write("<script>alert('" + ex.Message + "')</script>");
            }
        }
    }
}

Error:

Msg 2809, Level 16, State 1, Line 13
The request for procedure 'member_master_tbl' failed because 'member_master_tbl' is a table object.

What is the problem?


Solution

  • Your errors are for several reasons.

    Firstly, you have

    member_master_tbl(
    

    Well, you have a table name with "(" in it - it going to confuse SQL.

    (Do you really have a table named above?)

    So, place a space after the table name

    Next up: don't ever let code spread off the screen like that. You can't see, nor look at the SQL. It becomes like coding in a dark room with a blindfold on. You can't see your code, and as result, you're just now guessing and hacking to make this work.

    The fact of surrounding the string with "(" shows that you just guessing now.

    The connection will always have been closed. Since it always been closed by your correct previous working code, then you never will have to test or check your connection object, right? In other words, work on the assumption that your previous code was good, and correct, and since one makes that assumption, then you never have to close the connection!

    And since your previous code is assumed to be correct, then you never have to check if the connection is open either!

    And how do you always make sure you don't have that stray connection?

    Answer: you let the system take care of this, and it will always have closed and cleaned up and disposed the connection for you, that's how!

    And how do you do the above? You adopt using blocks. It will actually save you writing code!

    Worse yet, since your SQL statement runs off the edge of the screen: note how your missing the closing ")" for your VALUES list.

    but then again, you can't see or notice this, right!

    Remember, good developers are not really that good.

    But, what they do really fantastically? They write code that humans can read easy, so then seeing errors is also easy!

    In other words, good developers are actually better at writing code that easy to see and fix, not that they have super brains that see errors!

    Next up:

    Strong type your parameters. That means if a value is "int", then tell the system that the value supposed to be int, etc.

    So, let's fix the table name, since your table name is not "member_master_tbl("

    Without a space, you seeing a error message that this looks like a function!

    eg:    abc(
    

    Wrap your SQL connection block in using statements. This means you can leave work early, make happy hour and have time to get lucky. It also means the connection will be closed for you, disposed for you, and you don't care, or nor have to worry about it (again, makes things easy).

    You find that good coders are not better at coding, but they learned to avoid code that hard to read, and hard to fix. The result is such code is child's play, since it was easer to write, read, fix.

    So, I would suggest this code as a start:

    using (SqlConnection con = new SqlConnection(strcon))
    {
        string sqlquary =
            @"insert into member_master_tbl
            (
                full_name, dob, contact_no, email, state, city, pincode,
                full_address, member_id, password, account_status
            )
            VALUES
            (
                @full_name, dob, @contact_no, @email, @state, @city, @pincode,
                @full_address, @member_id, @password, @account_status
            )";
    
        using (SqlCommand cmd = new SqlCommand(sqlquary, con))
        {
            cmd.Parameters.Add("@full_name", SqlDbType.NVarChar).Value = TextBox1.Text;
            cmd.Parameters.Add("@dob", SqlDbType.Date).Value = TextBox2.Text;
            cmd.Parameters.Add("@contact_no", SqlDbType.NVarChar).Value = TextBox2.Text;
            cmd.Parameters.Add("@email", SqlDbType.NVarChar).Value = TextBox4.Text;
            cmd.Parameters.Add("@state", SqlDbType.NVarChar).Value = DropDownList1.SelectedItem.Value;
            cmd.Parameters.Add("@city", SqlDbType.NVarChar).Value = TextBox6.Text;
            cmd.Parameters.Add("@pincode", SqlDbType.Int).Value = TextBox7.Text;
            cmd.Parameters.Add("@full_address", SqlDbType.NVarChar).Value = TextBox8.Text;
            cmd.Parameters.Add("@member_id", SqlDbType.Int).Value = TextBox9.Text;
            cmd.Parameters.Add("@password", SqlDbType.NVarChar).Value = TextBox5.Text;
            cmd.Parameters.Add("@account_status", SqlDbType.NVarChar).Value = "pending";
    
            con.Open();
            cmd.ExecuteNonQuery();
        }
    }
    Response.Write("<script>alert('Signup Successfull');</script>");
    

    Even if the above code has some errors, it going to be far more easy to change, fix, and read. However, strong type the parameter's as above shows, and edit + fix the above to MATCH the data types in the table.

    And those name for text boxes? Really, don't use TextBox1 unless there is only 1 or 2 text boxes on the webform. Beyond 1 or 2 text boxes on the page: then always give each text box a nice readable id of what it means.

    So, how would I have written the above code?

    My version looks like this:

           int PK = General.FwriterAdd(EditArea, "member_master_tbl")
    

    EditArea in above is a div. Since after one day of hand coding the sending or loading of controls on a page? It is way too much work!

    So, I wrote one general routine that takes the controls, and sends them to the database for me, and now for every page with a bunch of controls, I don't have to write the same thing over and over, and I have one routine that works for all web pages. But, let's leave how that code works for another day and time.