SQLException Occured - asp.net

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

Related

Fetching data from remote SQL server

I have developed a asp.net web application using visual studio 2010. I'm using SQL server 2008 as database. I need to fetch data from one of the remote server through LAN connection and have to store to my database through C# code. I am beginner to web development using asp.net and C#. please tell me a very simple way to solve this.
This is an example which I tried. Is this code OK or wrong please guide me with this?
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection();
con1.ConnectionString = #"Data Source=172.16.7.127\inhouse;User ID=****;Password= *****;";
con1.Open();
string str = "select * from t_his_events Where patientMRN="+hosp_no.Text;
SqlDataReader dr;
SqlCommand myCommand = new SqlCommand(str,con1);
dr = myCommand.ExecuteReader();
if (dr.HasRows)
{
Console.WriteLine("connection established");
}
}
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection(<connectionstring>);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM table";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
And now you have a DataSet containing the results of your query. As for determining your , I suggest Connection Strings as a great resource for picking the perfect format.
Where is your database name in connectionString you created on remote server
using System.Data.SqlClient;
using system.Data;
string cs = Data Source=172.16.7.127\inhouse;database=databasename;User ID=User id create on remote server;Password= Your password for the ;
SqlConnection conn = new SqlConnection(cs);
SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM tableName",conn);
DataSet ds = new DataSet();
adp.Fill(ds);
now you can use the dataset object that contain your table

How to Resolve - "Object reference not set to an instance of an object" Error in C#

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;
using System.Configuration;
using System.Data;
public partial class FormCreationWithDataStoraget : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void sbmt_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["Data Source=RAJIM -PC;Initial Catalog=RajiDatabase;Integrated Security=True"].ConnectionString;
string insertSql = "INSERT INTO FamilyDetails(FirstName,LastName,Gender,Age,Relationship,MobileNumber)" + "values(#FirstName,#LaseName,#Gender,,#Age,#,#MobileNumber)";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand scmd = new SqlCommand();
scmd.Connection = conn;
scmd.CommandType = CommandType.Text;
scmd.CommandText = insertSql;
SqlParameter firstname = new SqlParameter("#FirstName", SqlDbType.VarChar, 40);
firstname.Value = tbx.Text.ToString();
scmd.Parameters.Add(firstname);
SqlParameter lastname = new SqlParameter("#LaseName", SqlDbType.VarChar, 40);
lastname.Value = tbx1.Text.ToString();
scmd.Parameters.Add(lastname);
SqlParameter gender=new SqlParameter("#Gender",SqlDbType.VarChar,40);
gender.Value = rbt.SelectedItem.ToString();
scmd.Parameters.Add(gender);
SqlParameter age = new SqlParameter("#Age", SqlDbType.Int);
age.Value = tbx2.Text.ToString();
scmd.Parameters.Add(age);
SqlParameter relationship = new SqlParameter("#Relationship", SqlDbType.VarChar, 40);
relationship.Value = tbx3.Text.ToString();
scmd.Parameters.Add(relationship);
SqlParameter mobilenumber=new SqlParameter("#MobileNumber",SqlDbType.VarChar, 10);
mobilenumber.Value = tbx4.Text.ToString();
scmd.Parameters.Add(mobilenumber);
try
{
conn.Open();
scmd.ExecuteNonQuery();
Response.Write("User Registration successful");
}
catch (SqlException ex)
{
string errorMessage = "Error in registering user";
errorMessage += ex.Message;
throw new Exception(errorMessage);
}
finally
{
conn.Close();
}
}
}
It looks like this line is causing your problem:
string insertSql = "INSERT INTO FamilyDetails(FirstName,LastName,Gender,Age,Relationship,MobileNumber)" + "values(#FirstName,#LaseName,#Gender,,#Age,#,#MobileNumber)";
Specifically:
#FirstName,#LaseName,#Gender,,#Age,#,#MobileNumber
It Should Be:
#FirstName,#LaseName,#Gender,#Age,#Relationship,#MobileNumber
The issue is that this line:
string connectionString = ConfigurationManager.ConnectionStrings["Data Source=RAJIM -PC;Initial Catalog=RajiDatabase;Integrated Security=True"].ConnectionString;
is not retrieving any object because you don't have a ConnectionString defined your web.config with the name of "Data Source=RAJIM ..." so basically calling the .ConnectionString at the end of it breaks it.
Add the "Data Source=RAJIM..." line as a connection string in your web.config (more info on connection strings here).
Once you give your connection string a name, i.e., "MyConnectionString" then change your code to be:
string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

Name does not exist in current context

I am trying to update a view using a gridview with edit and update buttons. I am using some code from code projects and the code looks like this :
private void BindData()
{
string strQuery = "SELECT * FROM [vw_GridviewSource] WHERE (([Annotation Date] = #Annotation_Date) AND ([Name] = #Name))";
SqlCommand cmd = new SqlCommand(strQuery);
gvSummary.DataSource = GetData(cmd);
gvSummary.DataBind();
}
I am getting an error that the name 'GetData' does not exist in the current context.
My using statements are:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
Do I need to add another statement?
It looks like you missed implementing the GetData function. After some quick Googling I found this which looks like it might suit your needs.
private DataTable GetData(SqlCommand cmd)
{
//string connectionString;
connectionString = "";
connectionString = "Integrated Security=SSPI;Persist Security Info=False;User ID=sa;Initial Catalog=TEST_DB;Data Source=DELL-PC";
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
}
}

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

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

SQL Connection variable not in the current context

I am a beginner in.NEt and having difficulty using the sql connection in a radio button index changed eventhandler that i defined on the page_load.
Below is my code
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;
using System.Configuration;
namespace Controls
{
public partial class Report_Selection : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.HeaderStyle.Font.Bold = true;
RadioButtonList1.SelectedIndexChanged += new EventHandler(RadioButtonList1_SelectedIndexChanged);
using (SqlConnection cnn = new SqlConnection("Data Source=DBSW9079;Initial Catalog=Underwriting;Integrated Security=SSPI;"))
{
SqlCommand cmd;
SqlDataReader sdr;
if (!IsPostBack)
{
cmd = new SqlCommand("select Categoryid,CategoryTitle from Report_Category", cnn);
cnn.Open();
sdr = cmd.ExecuteReader();
SelectCategorydlist1.DataSource = sdr;
SelectCategorydlist1.DataTextField = "CategoryTitle";
SelectCategorydlist1.DataValueField = "categoryid";
SelectCategorydlist1.DataBind();
cnn.Close();
}
else
{
//It's a Post back
//make the grid visible and fill it
GridView1.Visible = true;
RadioButtonList1.SelectedValue = "1";
cmd = new SqlCommand("Select rptdesc,rptdesctext,categoryid from report_description " + "where categoryid != 99999"
+ "and categoryid = " + Convert.ToInt32(SelectCategorydlist1.SelectedValue).ToString(), cnn);
cnn.Open();
sdr = cmd.ExecuteReader();
GridView1.DataSource = sdr;
GridView1.DataBind();
sdr.Close();
{
}
}
}
}
void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand cmd1;
SqlDataReader sdr1;
if (RadioButtonList1.SelectedIndex.Equals(1))
{
RadioButtonList1.ClearSelection();
cmd1 = new SqlCommand("Select rptdesc,rptdesctext,categoryid from report_description "
+ "and categoryid = " + Convert.ToInt32(SelectCategorydlist1.SelectedValue).ToString(), cnn);
cnn.Open();
sdr1= cmd1.ExecuteReader();
GridView1.DataSource = sdr1;
GridView1.DataBind();
sdr1.Close();
}
}
}
}
In the above code when i use the cnn sequel connection in the event handler i get an small r
Your query in RadioButtonList1_SelectedIndexChanged appears to be incorrect. There's an and without a where:
Select rptdesc,rptdesctext,categoryid from report_description
and categoryid = ...
^^^ should be WHERE

Resources