Why I am receiving an Object reference not set error - c#

My C# 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.Xml.Linq;
using System.Configuration;
public partial class zzsearch : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
PopulatePhysician();
}
public void PopulatePhysician()
{
string myQuery = "SELECT * FROM tblPhysician";
string conn = ConfigurationManager.ConnectionStrings["ConnStringTEST"].ConnectionString;
SqlConnection cn = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand(myQuery, cn);
SqlDataReader ddlValues = default(SqlDataReader);
ddlValues = cmd.ExecuteReader();
if (!IsPostBack)
{
name.DataSource = ddlValues;
name.DataValueField = "content_id";
name.DataTextField = "content_title";
name.DataBind();
//set the default value for the drop down
ListItem Item = new ListItem();
Item.Text = "Select a Last Name...";
Item.Value = "0";
//Item.Selected = True
name.Items.Insert(0, Item);
}
cmd.Connection.Close();
cmd.Connection.Dispose();
}
}
My partial web.config file:
<appSettings file="Application.config">
<add key="ConnStringTEST" value="Data Source=ep-db;Initial Catalog=DSCONTENT;Integrated Security=FALSE;user=zytuid;pwd=testingitout;" />
</appSettings>
ASP code:
<asp:DropDownList ID="name" runat="server" ClientIDMode="Static">
</asp:DropDownList>
Why do I receive the following error:
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 21: {
Line 22: string myQuery = "SELECT * FROM tblPhysician";
Line 23: string conn = ConfigurationManager.ConnectionStrings["ConnStringTEST"].ConnectionString;
Line 24: SqlConnection cn = new SqlConnection(conn);
Line 25: SqlCommand cmd = new SqlCommand(myQuery, cn);
Source File: c:\Webserver\WWESTEXEC\zzsearch.aspx.cs Line: 23

Because ConfigurationManager.ConnectionStrings["ConnStringTEST"] is returning null.
ConnectionStrings does not reference the appSettings section. It references the connectionStrings section.

The problem is that the connection string is added as an AppSettings entry, not as a connection string in your config file. That's why ConfigurationManager.ConnectionStrings["ConnStringTEST"] returns null and the call to the ConnectionString property results in a NullReferenceException.
Change this
<appSettings file="Application.config">
<add key="ConnStringTEST" value="Data Source=ep-db;Initial Catalog=DSCONTENT;Integrated Security=FALSE;user=zytuid;pwd=testingitout;" />
</appSettings>
To this;
<connectionStrings>
<add name="ConnStringTEST" connectionString="Data Source=ep-db;Initial Catalog=DSCONTENT;Integrated Security=FALSE;user=zytuid;pwd=testingitout;" />
</connectionStrings>
For detailed information on how to configure and retrieve connection strings in ADO.NET, see this link.

You should check if the value is set before you can call ConnectionString .
Replace your code with the following:
string conn = ConfigurationManager.ConnectionStrings["ConnStringTEST"].ConnectionString
to
if(!string.IsNullOrEmpty(ConfigurationManager.ConnectionStrings["ConnStringTEST"])){
string conn = ConfigurationManager.ConnectionStrings["ConnStringTEST"].ConnectionString ;
}

I think your issue is that you are looking in ConfigurationManager.ConnectionStrings and not ConfigurationManager.AppSettings. What i mean is that your connection string in your web config is in the AppSettings section and not in the connectionStrings section.
Try This:
string conn = ConfigurationManager.AppSettings["ConnStringTEST"];

Related

SQL Server Database Connection C# ASP.NET

To initialize the connection string, it needs to be a static string. Why that happens?
using System.Data.SqlClient;
namespace CDemoLib
{
public class Connecting
{
static string conString = #"connection string here";
Also when I am trying to open a connection using the conn.Open()am getting an error saying that
The name conn.Open() does not exist in the current context
Why that error occurs ?
using System.Data.SqlClient;
namespace CDemoLib
{
public class Connecting
{
static string conString = #"connection string here";
SqlConnection conn = new SqlConnection(conString);
conn.Open();
I have anwsered this question but i will replay it for you.
(Connection String Is not Working Object instance reference is null)
Put your connection string at you web.config as the foloow example:
<add name="MovieDB"
connectionString="Data Source=LocalDb)\MSSQLLocalDB;Initial Catalog=aspnet- MvcMovie;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Movies.mdf"
providerName="System.Data.SqlClient"/>
to read it within your code:
System.Configuration.Configuration rootWebConfig =System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
System.Configuration.ConnectionStringSettings connString;
if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
{
connString =
rootWebConfig.ConnectionStrings.ConnectionStrings["MovieDB"];
if (connString != null)
Console.WriteLine("MovieDB connection string = \"{0}\"",
connString.ConnectionString);
else
Console.WriteLine("No MovieDB connection string");
}
The name at your web.config tag 'name'
<add name="MovieDB".....
has to be the same one from your c# code:
connString = rootWebConfig.ConnectionStrings.ConnectionStrings["MovieDB"]
from: https://msdn.microsoft.com/en-us/library/ms178411.aspx
Here a method to open it:
private static void OpenSqlConnection(string connString)
{
using (SqlConnection connection = new SqlConnection(connString))
{
connection.Open();
Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
Console.WriteLine("State: {0}", connection.State);
}
}
from: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open(v=vs.110).aspx
DonĀ“t forget to secure your connection string at your web.config. Please, read this: https://msdn.microsoft.com/en-us/library/ms178372.aspx

Asp.net MVC SQL Server connection return null

I am trying to connect to Microsoft SQL Server on localhost. My code is as follows.
public SqlConnection con;
// To Handle connection related activities
private void connection()
{
string constr = ConfigurationManager.ConnectionStrings["Data Source = MACHINE-VOIV7EH\\SQLEXPRESS; Initial Catalog = geolog; Persist Security Info = False; "].ToString();
con = new SqlConnection(constr);
}
public List<Bob> GetAllBobs()
{
try
{
connection();
con.Open();
IList<Bob> EmpList = SqlMapper.Query<Bob>(con, "GetBobs").ToList();
con.Close();
return EmpList.ToList();
}
catch (Exception)
{
throw;
}
}
con return null
SQL Server settings:
Configuration from Pyton (try, but another database):
conn = pypyodbc.connect('DRIVER={SQL Server};'
r'SERVER=MACHINE-VOIV7EH\SQLEXPRESS;'
r'DATABASE=vibori;'
r' autocommit=True'
)
The Problem is with your connection string. You should reference your connection string from the web.config file.
Web.Config
<connectionStrings>
<add name="master" providerName="System.Data.SqlClient" connectionString="Data Source=ACHINE-VOIV7EH\\SQLEXPRESS;Initial Catalog=geolog;Integrated Security=False;User Id=your_user_id;Password=xxxxxx;MultipleActiveResultSets=True" />
</connectionStrings>
C# File
SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["master"].ConnectionString);
Or you can just send a connection string as follows
private void connection()
{
string constr = "Data Source=MACHINE-VOIV7EH\\SQLEXPRESS; Initial Catalog = geolog; Persist Security Info = False;";
con = new SqlConnection(constr);
}
The string index of ConfigurationManager.ConnectionStrings[string] is the connection name, not the connection string which is what it returns. Use your web configuration file (web.config) to add one or more named connection strings which can be returned by this indexer.
Example:
string constr = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString
and partial web.config content
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<connectionStrings>
<add name="MyConnection" connectionString="Data Source=MACHINE-VOIV7EH\SQLEXPRESS;Initial Catalog=vibori" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>

Random Generator To Use Values From SQL Server DB

I have an asp.net application which is a random generator of places.
At present I am the values sat in my code behind but I would like to move these into my SQL Server DB but I have no idea on how to do this. For reference I am using SQL Server Management Studio.
Is this possible or am I just over complicating it?
Code Behind
protected void BtnDecideForMe_Click(object sender, EventArgs e)
{
List<string> Eat = new List<string>();
Eat.Add("Chinese Buffet");
Eat.Add("Harvester");
Eat.Add("Frankie & Benny's");
Eat.Add("Hungry Horse");
Eat.Add("Blaize");
Eat.Add("Chiquito");
Eat.Add("Cafe Football");
Eat.Add("Nando's");
Random Place = new Random();
int Places = Place.Next(0, Eat.Count);
txtDestination.Text = Eat[Places];
}
View
<div class="row">
<div class="col-sm-3">
<asp:TextBox class="form-control" ID="txtDestination" runat="server" disabled></asp:TextBox>
</div>
<div class="col-sm-2">
<asp:Button class="btn btn-success" ID="BtnDecideForMe" runat="server" Text="Decide For Me" OnClick="BtnDecideForMe_Click" />
</div>
</div>
Code For Suggestion But Cant Get It Working
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;
namespace PaydayLunchGenerator
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void BtnDecideForMe_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=DEV-116\\ONLINE;" +
"Initial Catalog=PaydayLunch;" +
"Integrated Security=True;";
conn.Open();
//using (SqlConnection conn = new SqlConnection(PaydayLunchConnectionString1))
using (SqlCommand cmd = new SqlCommand("dbo.GetRandomPlace", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// set up the parameters
cmd.Parameters.Add("#OutputVar", SqlDbType.VarChar).Direction = ParameterDirection.Output;
// open connection and execute stored procedure
conn.Open();
cmd.ExecuteNonQuery();
// read output value from #OutputVar
string place = Convert.ToString(cmd.Parameters["#OutputVar"].Value);
conn.Close();
txtDestination.Text = place;
}
}
}
}
You can achieve this by creating a view in SQL server and loading that view into a dataset. That way you can select from the dataset and refresh the data whenever you require.
Populating Dataset
Note - You could even go a step further and create a stored procedure that will just give you a random value from the table on demand :)
Create a stored procedure with an output variable, then inside create a select like this
CREATE PROC sp_RandomPlace
#OutputVar nvarchar(100) OUTPUT
AS
SET #OutputVar = (select top 1 percent Place from [PlaceTable] order by newid())
Then in your c#
using(SqlConnection conn = new SqlConnection(ConnectionString ))
using(SqlCommand cmd = new SqlCommand("dbo.sp_RandomPlace", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// set up the parameters
cmd.Parameters.Add("#OutputVar", SqlDbType.Nvarchar).Direction = ParameterDirection.Output;
// open connection and execute stored procedure
conn.Open();
cmd.ExecuteNonQuery();
// read output value from #OutputVar
string place= Convert.ToString(cmd.Parameters["#OutputVar"].Value);
conn.Close();
}
The code above is untested but you get the jist
With the thanks to Alec, i manged to get it working eventually using the following:
protected void BtnDecideForMe_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=DEV-116\\ONLINE;Initial Catalog=PaydayLunch;Integrated Security=True";
using (SqlCommand cmd = new SqlCommand("dbo.GetRandomPlace", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// set up the parameters
cmd.Parameters.Add("#OutputVar", SqlDbType.VarChar, 25).Direction = ParameterDirection.Output;
// open connection and execute stored procedure
conn.Open();
cmd.ExecuteNonQuery();
// read output value from #OutputVar
string place = Convert.ToString(cmd.Parameters["#OutputVar"].Value);
conn.Close();
txtDestination.Text = place;
}
}

connecting to database - connectionString connect.Open() error

So I am trying to run a query in a database that searches the database table from a textbox input. My code is
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Query
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void employeeBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.employeeBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.personnelDataSet);
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'personnelDataSet.employee' table. You can move, or remove it, as needed.
this.employeeTableAdapter.Fill(this.personnelDataSet.employee);
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
string connectionString = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;";
private void btnSearch_Click(object sender, EventArgs e)
{
string commandText = "SELECT employeeID, name, position, hourlyPayRate " +
"FROM dbo.employee WHERE name LIKE '%'+ #Name + '%'";
using (SqlConnection connection = new SqlConnection(connectionString))
{
//Create a SqlCommand instance
SqlCommand command = new SqlCommand(commandText, connection);
//Add the parameter
command.Parameters.Add("#Name", SqlDbType.VarChar, 20).Value = textBox1.Text;
//Execute the query
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch
{
//Handle excepetion, show message to user...
MessageBox.Show("Error bitch!");
}
finally
{
connection.Close();
}
}
}
}
}
When I take the catch out I can see the error occurs at connection.Open(). The error takes a while to happen which makes me wonder whether there is an issue with string connectionString = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;";
This is the error that I receive:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
You need to validate the connection string. If Open() is throwing an SqlException then the connection string is invalid. To enable you to establish the exact form of the connection string you require, take a look at connectionstrings.com.
As to why the exception is showing as unhanded, you need to 'consume' the exception as follows:
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception e)
{
// Handle excepetion, show message to user...
MessageBox.Show(e.Message);
}
I hope this helps.
Check this out:
string connectionString = "Server=.\InstanceName;Database=myDataBase;Integrated Security=True;";
Also
string commandText = "SELECT employeeID, name, position, hourlyPayRate
FROM dbo.employee WHERE name LIKE '%#Name%'";
try:
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User id=myUser;Password=myPAss;Connect Timeout=15;Integrated Security=false";
Try declaring your connection string inside the event.
An alternate method is to link your database through web.config as follows:
<connectionStrings>
<connectionString="Data Source=(localdb)\v11.0;Initial Catalog=DBName;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
And then the connection string can be as:
string cs = ConfigurationManager.ConnectionStrings["DBName"].ConnectionString;

asp.net login with database

I have a big problem with Login and database. I was searching a lot but couldn't find a solution. First of all I'm trying to get row from my DB. When everything is true, I want to redirect. But when I'm writing my login and password, after around 30 sec I receive "A network-related or instance-specific error occurred while establishing a connection to SQL Server..."
Here 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.Web.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace _29
{
public partial class Default : System.Web.UI.Page
{
private string strcon = WebConfigurationManager.ConnectionStrings["UserConnectionString1"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if ((Session["Check"] != null) && (Convert.ToBoolean(Session["Check"]) == true))
{
// If User is Authenticated then moved to a main page
if (User.Identity.IsAuthenticated)
Response.Redirect("Welcome.aspx");
}
}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
Boolean wynik;
wynik = false;
wynik = Authentication(Login1.UserName, Login1.Password);
if (wynik == true) {
e.Authenticated = true;
Session["Check"] = true;
}
else
{
e.Authenticated = false;
}
}
private bool Authentication(string p1, string p2)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("Select count(UserName) from Users where UserName='" + p1 + "' and Password ='" + p2 + "'", con);
con.Open();
int result = (int)cmd.ExecuteScalar();
if (result == 1)
{
return true;
}
else
{
return false;
}
}}
}
Here is my Web.Config
<configuration>
<connectionStrings>
<add name="UserConnectionString1" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirect`enter code here`ory|\User.mdf;Integrated
Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
</configuration>
Trying to get the result by rows but it doesn't work.
Please help me :)
Your connection string seems to be wrong.
It should be like
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|User.mdf;Database=dbname;
Trusted_Connection=Yes;
Not as you've used in you web.config
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirect`enter codehere`ory|\User.mdf;Integrated Security=True
Always check this website to get the proper connection string. It's very useful.
Cheers!
I think connection is Ok, because when i use connection on Page_Load, i can recieve information from my database. In this case "result" is 1 because only 1 row exist. But as you can see, i have to put already strings on my code. I want to use input (login control).
THank you
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace _29
{
public partial class Default : System.Web.UI.Page
{
private string strcon = WebConfigurationManager.ConnectionStrings["UserConnectionString1"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
string p1 ="david";
string p2 = "1234a";
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("Select count(UserName) from Users where UserName='" + p1 + "' and Password ='" + p2 + "'", con);
con.Open();
int result = (int)cmd.ExecuteScalar();
Response.Write(result);
}
}

Categories