where to add connection string of SQL server in asp.net page - asp.net

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

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

chnage your code as given below, it will work
public static SqlConnection GetConnection()
{
string ConString="Data Source=.\SQLEXPRESS;AttachDbFilename=E:\talat\MyRealSacaProject\App_Data\SACALogin.mdf;Integrated Security=True;User Instance=True";
SqlConnection cn = new SqlConnection(ConString);
cn.Open();
return cn;
}

try this change from your code :
public static void SaveAdmin(admin a)
{
SqlConnection cn = GetConnection();
string sql = "INSERT INTO admin_login VALUES('" + a.username + "','" + a.Password + "')";
SqlCommand cmd = new SqlCommand(sql, cn);
cmd.ExecuteNonQuery();
cn.Close();
}

Related

Code to help change data in the SQL Server from lower case to upper case?

I require help to use data from the SQL Server to extract it then decrpyt it, convert it to capital and then encrypt it and send back to database. Is there code to help upper case the columns in the database?
// connection string
static string connStr = ConfigurationManager.ConnectionStrings["tmsdbConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
protected Cryptography a = new Cryptography();
protected void btnUpdate_Click(object sender, EventArgs e)
{
conn.Open();
// Response.Write("Connection Established");
this.getdataTable();
this.getDataSet();
// retrieve data
SqlCommand command;
String sql, Output = " ";
sql = "SELECT applicantId, fullName, idNumber, idType, nationality, race, gender, birthDate, highestEducation, spokenLanguage, getToKnowChannel FROM applicant";
// command = new SqlCommand(sql, conn);
command = new SqlCommand("SELECT applicantId, fullName, idNumber, idType, nationality, race, gender, birthDate, highestEducation, spokenLanguage, getToKnowChannel FROM applicant");
Cryptography c = new Cryptography();
lblRecords.Text = c.encryptInfo(lblRecords.Text);
}
These are the database methods:
public DataTable getDataTable(SqlCommand cmd)
{
cmd.Connection = getDBConnection();
cmd.Connection.Open();
cmd.CommandTimeout = 1200;
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
dataAdapter.Fill(dt);
cmd.Connection.Close();
return dt;
}
public DataSet getDataSet(SqlCommand cmd)
{
cmd.Connection = getDBConnection();
cmd.Connection.Open();
cmd.CommandTimeout = 1200;
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
cmd.Connection.Close();
return ds;
}
and these are the cryptography methods:
public string encryptInfo(string inputText)
{
cipherData = AES_256.encryptStringToBytes(inputText, keyBytes, ivBytes);
string userinfo64Text = Convert.ToBase64String(cipherData);
return userinfo64Text;
}
public string decryptInfo(string outputText)
{
byte[] inputbytes = Convert.FromBase64String(outputText);
string plainText = AES_256.decryptStringFromBytes(inputbytes, keyBytes, ivBytes);
return plainText;
}
There is a built-in SQL Server Function called UPPER:
SELECT UPPER('myvalue')

How do i fill up textbox from database in asp.net visual studio without id?

I am trying to get details of an account in a row using the Username instead of id. I have limited knowledge on this matter so im only stuck with the code that i learned in class.
I have tried changing variables, but probably wont help and the code i have provided below, would not retrieve any data from the database...
(Username are retrieved from previous page and yes it did show up in this page)
This is the code used on previous page: (code is placed on a button)
string username = Session["Username"].ToString();
Response.Redirect("EditAccountDetail.aspx?Username="+ username);
private DataTable GetData()
{
string constr = ConfigurationManager.ConnectionStrings["myDbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Guest"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
This is the code im working on right now:
String Uname = Request.QueryString["Username"];
string constr = ConfigurationManager.ConnectionStrings["MyDbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Guest WHERE Username='" + Uname+"'"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
foreach (DataRow row in dt.Rows)
{
string id = row["Id"].ToString();
string Full_name = row["Full_name"].ToString();
string Username = row["Username"].ToString();
string Password = row["Password"].ToString();
string Email = row["Email"].ToString();
string DOB = row["DOB"].ToString();
string Gender = row["Gender"].ToString();
this.HiddenField1.Value = id;
this.TextBox_Name.Text = Full_name;
this.TextBox_Username.Text = Username;
this.TextBox_Password.Text = Password;
this.TextBox_Email.Text = Email;
this.TextBox_DOB.Text = DOB;
this.RadioButtonList_Gender.Text = Gender;
}
}
}
}
}
This is the code in the button:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnectionString"].ConnectionString);
try
{
string query = "UPDATE Guest SET Full_name=#Full_name, Username=#Username, Password=#Password, Email=#Email, DOB=#DOB, Gender=#Gender WHERE Id=#id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#id", HiddenField1.Value);
cmd.Parameters.AddWithValue("#Full_name", TextBox_Name.Text);
cmd.Parameters.AddWithValue("#Username", TextBox_Username.Text);
cmd.Parameters.AddWithValue("#Password", TextBox_Password.Text);
cmd.Parameters.AddWithValue("#Email", TextBox_Email.Text);
cmd.Parameters.AddWithValue("#DOB", TextBox_DOB.Text);
cmd.Parameters.AddWithValue("#Gender", RadioButtonList_Gender.Text);
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("GuestMenu.aspx");
con.Close();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.ToString());
}
If you are redirecting to the "GuestMenu" page, then you have to add username in the query string so that you can retrieve this on the page.
Response.Redirect("GuestMenu.aspx?Username="+TextBox_Username.Text);
By seeing your current code, you should be getting some error. Please post the error details if any.
You can try changing the query as below and check for database result
new SqlCommand("SELECT * FROM Guest WHERE Username='" + Uname + "'")

SQLException Occured

A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
I was trying database connection. But I am getting this error. Please help me.
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 OLSWebApp
{
public partial class ItemTypeWebForm : System.Web.UI.Page
{
static string constr = "server=DESKTOP-3N4UH9N; user=sa; pwd=ZEESHAN#123; Initial Catalog=Online Order System";
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SaveButton_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(constr);
conn.Open();
string q = "Insert INTO ItemType values ('"+ TypeIdTextBox.Text +"'), ('"+ TypeTextBox.Text +"'),('"+ NameTextBox.Text +"')";
SqlCommand cmd = new SqlCommand(q,conn);
cmd.ExecuteNonQuery();
}
}
}
con.Open() statement generates error..
For SQL Server Connection types please first read this document.
https://www.connectionstrings.com/sql-server/
For your example I think DESKTOP-3N4UH9N is your local PC not the server instance name, isn't it?
Please first find the server instance name by using SQL Server Management Studio (SSMS).
Please try below codes
Standard Security
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Server=myServerAddress; " +
"Database=myDataBase;" +
"User Id=myUsername;" +
"Password=myPassword;"
conn.Open();
Trusted Connection
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Server=myServerAddress;" +
"Database=myDataBase;" +
"Trusted_Connection=True;"
conn.Open();
Connection to a SQL Server instance
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Server=myServerName\myInstanceName;" +
"Database=myDataBase;" +
"User Id=myUsername;" +
"Password=myPassword;"
conn.Open();
Integrated Security
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=MyLocalSqlServerInstance;" +
"Initial Catalog=MyDatabase;" +
"Integrated Security=SSPI;"
conn.Open();
change this
conn.Open();
string q = "Insert INTO ItemType values ('"+ TypeIdTextBox.Text +"'), ('"+ TypeTextBox.Text +"'),('"+ NameTextBox.Text +"')";
SqlCommand cmd = new SqlCommand(q,conn);
cmd.ExecuteNonQuery();
into this
conn.Open();
string q = "Insert INTO ItemType values (#id, #type ,#name)";
SqlCommand cmd = new SqlCommand(q,conn);
cmd.Parameters.AddWithValue("#id", TypeIdTextBox.Text);
cmd.Parameters.AddWithValue("#type", TypeTextBox.Text);
cmd.Parameters.AddWithValue("#name", NameTextBox.Text);
cmd.ExecuteNonQuery();
conn.Close();
make sure the connection can open without any error

ASP.Net db connection issue

I'm new to ASP.Net & SQL Server and have the following code:
protected void btnShowData_Click(object sender, EventArgs e)
{
string connectionString;
SqlConnection cnn;
connectionString = #"Data Source=DESKTOP-RV7DDL4;Initial Catalog=Demodb
;User ID=DESKTOP-RV7DDL4\dbname;Password=test123";
cnn = new SqlConnection(connectionString);
SqlCommand command;
SqlDataReader dataReader;
String sql, Output = "";
sql = "Select TutorialID, TutorialName from demotb";
command = new SqlCommand(sql, cnn);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + "</br>";
}
Response.Write(Output);
dataReader.Close();
command.Dispose();
cnn.Close();
lblName.Visible = false;
txtName.Visible = false;
lstLocation.Visible = false;
chkC.Visible = false;
chkASP.Visible = false;
rdMale.Visible = false;
rdFemale.Visible = false;
btnSubmit.Visible = false;
}
When I run the project I receive the following error:
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code
Additional information: ExecuteReader requires an open and available Connection. The connection's current state is closed.
I thought the connection was made so not sure why it says the db is closed?
Try to to explicitly open the connection via the Open method on the SQL connection class.
Perhaps a using statement is more appropriate here. Like so:
using (var cnn = new SqlConnection(connectionString))
{
// Use the connection
}
Thanks for your help. I re-jigged things around and added the .Open method and it works!
string connectionString = null;
SqlConnection cnn;
SqlCommand command;
string sql, Output = "";
connectionString = #"Data Source=DESKTOP-RV7DDL4\SQLEXPRESS;Initial Catalog=DemoDBase
;User ID=sa;Password=test1234";
cnn = new SqlConnection(connectionString);
sql = "Select TutorialID, TutorialName from demoTable";
cnn.Open();
command = new SqlCommand(sql, cnn);
SqlDataReader dataReader;
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + "</br>";
}
Response.Write(Output);
dataReader.Close();
command.Dispose();
cnn.Close();

login page asp.net sql

I have this code and need to complete it..
string conn_str =
#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\mydb.mdf;
Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection(conn_str);
SqlCommand cmd = new SqlCommand("SELECT Password FROM Users WHERE UserName=#un", conn);
cmd.Parameters.Add("#un", SqlDbType.NVarChar);
cmd.Parameters["#un"].Value = **???**;
conn.Open();
string pwd = (string)cmd.ExecuteScalar();
conn.Close();
I have some values in sql data:
Tables:
Users
Username
Password
Now in login page i have textboxNAME and textboxPassword and if user type right login info(that in database) it refers him to default.aspx
Try
cmd.Parameters["#un"].Value = textboxName.Text;
and
if(textboxPassword.Text.Equals(pwd))
{
Request.Redirect("default.aspx");
}
else
{
//login failed
}
Try This:
string conn_str = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\mydb.mdf; Integrated Security=True;User Instance=True";
private string _password;
SqlConnection conn = new SqlConnection(conn_str);
SqlCommand cmd = new SqlCommand("SELECT Password FROM Users WHERE UserName=#un", conn);
cmd.Parameters.Add("#un", SqlDbType.NVarChar,50).Value=txtusername.text;
//use add with value to specify which object you want to use
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
//load data to datatable
DataTable dt = new Datatable();
conn.Open();
adapt.Fill(dt);
//get Password on Datatable
Foreach(DataRow a in dt.Rows)
{
_password = a["Password"].Tostring();
}
//Check password
if(_password==string.Empty)
{
//remain
}
else if(_password==txtpassword.Text)
{
Response.Redirect("My page");
}
conn.Close();
Regards

Resources