WHERE TO ADD CONNECTION STRING OF SQL SERVER IN ASP.NET PAGE

Mark Devid

Total Post:102

Points:714
Posted by  Mark Devid
 1189  View(s)
Ratings:
Rate this:
Hi All!

I am having an ASP.NET page that is containing the textboxes namely username and password and a button named cmdlogin. I want that when I enter the data in text boxes 

then that data should be saved into the database.

In SQL server of Visual studio, I have created table and even also have given the

INSERT INTO cmd_login VALUES(".......").
Now the problem is when I entered the data in textbooxes it is not saved in the database table. what can I do.

I have put my connection string into the class file. Do I need to put my connection string in the web.config?

my code is

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
public class Db
{
    public static SqlConnection GetConnection()
    {
        SqlConnection cn = new SqlConnection();
        cn.ConnectionString =@"Data                 Source=.\SQLEXPRESS;AttachDbFilename=E:\talat\MyRealSacaProject\App_Data\SACALogin.mdf;Inte    grated 

Security=True;User Instance=True;";
        cn.Open();
        return cn;
    }
    public static void SaveAdmin(admin a)
    {
        SqlConnection cn = GetConnection();
        string sql = "INSERT INTO admin_login VALUES(@[User-Name],@Password)";
        SqlCommand cmd = new SqlCommand(sql, cn);
        cmd.Parameters.AddWithValue("@[User-Name]",a.username);
        cmd.Parameters.AddWithValue("@Password", a.password);
        cmd.ExecuteNonQuery();
        cn.Close();
    }
    }

Thanks in advance! 

  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: where to add connection string of SQL server in asp.net page

    Hi Mark!


    try this simple code:

    SqlConnection _conn = new SqlConnection(_connString);
    _conn.Open();
    SqlCommand _cmd = new SqlCommand();
    _cmd.CommandType = CommandType.StoredProcedure;
    _cmd.Parameters.Clear();
    _cmd.Connection = _conn;
    _cmd.CommandText = "INSERT INTO [tablename] VALUE ([fieldvalue])"; //here your textbox    
    int _execute = _cmd.ExecuteNonQuery();

    bool _result = false;
    if(_execute != 1)
        _result = true;

    _conn.Close();

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!