NullReferenceException in SQL Server 2014 - c#

I want to save checkboxlist data in a database. I created a table in SQL named 'tblSubject' and made connectionstring in web.config. However I still get the erorr :
NullReferenceException was unhandled by user code
object reference not set to an instance of an object.
This is the code in c#:
private void PopulateSubjects()
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["constr"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select * from subjects";
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
ListItem item = new ListItem();
item.Text = sdr["Subject"].ToString();
item.Value = sdr["Id"].ToString();
item.Selected = Convert.ToBoolean(sdr["IsSelected"]);
chbox.Items.Add(item);
}
}
conn.Close();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["constr"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "update subjects set IsSelected = #IsSelected" +
" where Id=#Id";
cmd.Connection = conn;
conn.Open();
foreach (ListItem item in chbox.Items)
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#IsSelected", item.Selected);
cmd.Parameters.AddWithValue("#Id", item.Value);
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
}
And in Web.config:
<connectionStrings>
<add name=" constr" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;
Initial Catalog = dbtblSubject; Integrated Security = true" providerName="System.Data.SqlClient" />
</connectionStrings>
Any help would be much appreciated.

Remove the white space in Web.config:
<add name=" constr" ...
To
<add name="constr" ...

First of all, you should look at your stack trace for where the nullreference occurs.
It looks like you're on the right track, thinking that the connection string is the cause of this exception. If you look at your Web.config, the name of the connection string is " constr", with an extra space in the start. This does not match your code:
conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
Remove the first space in the connection string name in Web.Config, and your code will probably work.

Related

Getting the error already an open DataReader associated with this Command which must be closed first

I know It's a repeated question but I tried to add MARS MultipleActiveResultSets=True; in my connection string and it didn't work and still getting the same issue. I'm using SQL Server Management Studio v17.5.
Here's my connection string.
<connectionStrings>
<add name="DefaultConnection"
connectionString="Server=myserver;Database=mydb;User ID=myuser;Password=mypassword;MultipleActiveResultSets=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
What could be the issue which preventing MARS from getting activated?
public SqlListener()
{
ConnectionString = "DefaultConnection";
connString = ConfigurationManager.ConnectionStrings[ConnectionString].ConnectionString;
sqlCmd = new SqlCommand();
sqlConn = new SqlConnection(connString);
sqlCmd.Connection = sqlConn;
sqlCmd.Connection.Open();
SqlDependency.Start(connString);
}
public void executeSQLCMD(string queryType, string queryTxt)
{
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = queryTxt;
SqlDataReader reader = sqlCmd.ExecuteReader();
}
and then another switch with multiple data readers
switch (queryType)
{
case "SelectAHTQ":
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = "SP_1";
// fails here--> SqlDataReader AHTReader = sqlCmd.ExecuteReader();
while (AHTReader.Read())
{
LiveAHTDetails details = new LiveAHTDetails();
details.AHT = AHTReader.GetDouble(0);
details.ccName = AHTReader.GetString(1);
details.connectionID = connectionId;
this.liveStatus.liveDetails.Add(details);
}
break;
.....
Thanks
You must close the DataReader object before executing another SQL statement.

Error when trying to connect to a local instance

I am trying to get a connection from my webapp to a database to get values for a dropdownlist but somehow I always get the same Error at the con.Open. Tells me networkname was not found!
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string query = "SELECT HobbyId, Hobby, IsSelected FROM Hobbies";
//string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection("server=localhost/testserver; database=MyDB.dbo; integrated security=true"))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
ListItem item = new ListItem();
item.Text = sdr["Hobby"].ToString();
item.Value = sdr["HobbyId"].ToString();
item.Selected = Convert.ToBoolean(sdr["IsSelected"]);
ddlHobbies.Items.Add(item);
}
}
con.Close();
}
}
ddlHobbies.Items.Insert(0, new ListItem("--Select Hobby--", "0"));
}
}
You need to use a backward slash (\) instead of a forward slash (/): server=localhost/testserver should be server=localhost\testserver.
You can also replace localhost with a simple dot (.): server=.\testserver.
Make sure that your SQL server instance is actually running. You can open SQL server configuration manager to check this.
You will also need to enable at least one network protocol for your instance (e.g. named pipes, TCP/IP or shared memory).

Runtime Error after Button click

this is how when I need to create user into my database you will see it with a runtime error, and it only appears when I click the button.
problems are just the only appears when I click the button on the page.
Here we have c # code from opretbruger.aspx.cs
protected void ButtonOpretbruger_Click(object sender, EventArgs e)
{
string fejl = "Hov Hov, Du skal læse vore betingelser";
if (CheckBoxBetingelser.Checked)
{
LabelError.Visible = false;
cmd.Connection = conn;
string brugernavn = System.Globalization.CultureInfo.CurrentUICulture.TextInfo.ToTitleCase(TextBoxBrugernavn.Text);
cmd.CommandText = "SELECT Id, brugernavn, rank FROM brugere WHERE brugernavn = #brugernavn";
cmd.Parameters.AddWithValue("#brugernavn", brugernavn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
LabelErrorBesked.Text = "Hov hov, denne her email er optaget " + brugernavn;
}
else
{
conn.Close();
cmd.Connection = conn;
//ligger noget sikkert på password
string brugernavn1 = System.Globalization.CultureInfo.CurrentUICulture.TextInfo.ToTitleCase(TextBoxBrugernavn.Text);
string adgangskode = Hash.getHashSha256(TextBoxAdgangskode.Text);
string fornavn = TextBoxFornavn.Text;
string efternavn = TextBoxEfternavn.Text;
cmd.CommandText = #"INSERT INTO brugere (brugernavn, adgangskode, fornavn, efternavn)
VALUES (#brugernavn, #adgangskode, #fornavn, #efternavn);";
cmd.Parameters.AddWithValue("#brugernavn", brugernavn1);
cmd.Parameters.AddWithValue("#adgangskode", adgangskode);
cmd.Parameters.AddWithValue("#fornavn", fornavn);
cmd.Parameters.AddWithValue("#efternavn", efternavn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Response.Redirect("login.aspx");
}
}
else
{
LabelError.Text = fejl;
}
}
here we have html from opretbruger.aspx
<asp:Button ID="ButtonOpretbruger" runat="server" CssClass="btn pi-btn-base pi-btn-wide pi-weight-600" OnClick="ButtonOpretbruger_Click" ValidationGroup="opretbruger" />
The problem is it appears here typing this:
Server Error in '/' Application.
Runtime Error
Description: An application error occurred on the server. The current
custom error settings for this application prevent the details of the
application error from being viewed remotely (for security reasons).
It could, however, be viewed by browsers running on the local server
machine.
Details: To enable the details of this specific error message to be
viewable on remote machines, please create a tag within
a "web.config" configuration file located in the root directory of the
current web application. This tag should then have its
"mode" attribute set to "Off".
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration>
Notes: The current error page you are seeing can be replaced by a
custom error page by modifying the "defaultRedirect" attribute of the
application's configuration tag to point to a custom
error page URL.
<configuration>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>
</system.web>
</configuration>
in my web.config looks like this:
<system.web>
<compilation targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<globalization uiCulture="en-US" />
<!--<globalization uiCulture="da" culture="da-DK" />-->
</system.web>
EIDT UPDATE
protected void ButtonOpretbruger_Click(object sender, EventArgs e)
{
string fejl = "Hov Hov, Du skal læse vore betingelser";
if (CheckBoxBetingelser.Checked)
{
LabelError.Visible = false;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
string brugernavn = System.Globalization.CultureInfo.CurrentUICulture.TextInfo.ToTitleCase(TextBoxBrugernavn.Text);
cmd.CommandText = "SELECT Id, brugernavn, rank FROM brugere WHERE brugernavn = #brugernavn";
cmd.Parameters.AddWithValue("#brugernavn", brugernavn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
LabelErrorBesked.Text = "Hov hov, denne her email er optaget " + brugernavn;
}
else
{
conn.Close();
SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = conn;
string adgangskode = Hash.getHashSha256(TextBoxAdgangskode.Text);
string fornavn = TextBoxFornavn.Text;
string efternavn = TextBoxEfternavn.Text;
cmd1.CommandText = #"INSERT INTO brugere (brugernavn, adgangskode, fornavn, efternavn)
VALUES (#brugernavn, #adgangskode, #fornavn, #efternavn);";
cmd1.Parameters.Add("#brugernavn", brugernavn);
cmd1.Parameters.Add("#adgangskode", adgangskode);
cmd1.Parameters.Add("#fornavn", fornavn);
cmd1.Parameters.Add("#efternavn", efternavn);
conn1.Open();
cmd1.ExecuteNonQuery();
conn1.Close();
Response.Redirect("login.aspx");
}
}
else
{
LabelError.Text = fejl;
}
}
Error are: The variable name '#brugernavn' has already been declared. Variable names must be unique within a query batch or stored procedure.
Must declare the scalar variable "#adgangskode".
You are reusing the same command (variable named cmd) twice. That is the cause of your error since your previous code interferes with your later code.
Split the cmd variable in two. One for the first statement, one for the second.
This should be the full code:
protected void ButtonOpretbruger_Click(object sender, EventArgs e)
{
string fejl = "Hov Hov, Du skal læse vore betingelser";
if (CheckBoxBetingelser.Checked)
{
LabelError.Visible = false;
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
string brugernavn = System.Globalization.CultureInfo.CurrentUICulture.TextInfo.ToTitleCase(TextBoxBrugernavn.Text);
cmd.CommandText = "SELECT Id, brugernavn, rank FROM brugere WHERE brugernavn = #brugernavn";
cmd.Parameters.AddWithValue("#brugernavn", brugernavn);
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
LabelErrorBesked.Text = "Hov hov, denne her email er optaget " + brugernavn;
}
else
{
using (SqlCommand cmd1 = new SqlCommand())
{
cmd1.Connection = conn;
string adgangskode = Hash.getHashSha256(TextBoxAdgangskode.Text);
string fornavn = TextBoxFornavn.Text;
string efternavn = TextBoxEfternavn.Text;
cmd1.CommandText = #"INSERT INTO brugere (brugernavn, adgangskode, fornavn, efternavn)
VALUES (#brugernavn, #adgangskode, #fornavn, #efternavn);";
cmd1.Parameters.Add("#brugernavn", brugernavn);
cmd1.Parameters.Add("#adgangskode", adgangskode);
cmd1.Parameters.Add("#fornavn", fornavn);
cmd1.Parameters.Add("#efternavn", efternavn);
cmd1.ExecuteNonQuery();
}
Response.Redirect("login.aspx");
}
}
}
}
conn.Close();
}
else
{
LabelError.Text = fejl;
}
}
Your problem is with cmd object. That object is used many time and each time you have updated same object. In such case it may possible that you might add same parameter twice.
Instead of that try to get command following way
Command cmd = conn.CreateCommand();
//Now use your cmd over here.

fill asp:CheckBoxList from database

i have problems filling my checkboxlist from a sql in c#. The list is empty when it have been loaded.
I know it would probably be easier with a connection to web.config, but i have decieded not to have web.config in this project. It would be helpfull if anyone could see what i have done wrong.
This is my code:
string connetionString = "Data Source=[DATA-SOURCE];Initial Catalog=[CATALOG];User ID=[USER-ID];Password=[PASSWORD]";
SqlConnection cnn = new SqlConnection(connetionString);
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT ModuleID, ModuleName, InternalName, Active FROM dbo.Zodiac_System_Modules WHERE Active = 1 ORDER BY ModuleName ASC";
cmd.Connection = cnn;
cnn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
ListItem item = new ListItem();
item.Text = sdr["ModuleName"].ToString();
item.Value = sdr["InternalName"].ToString();
chkModules.Items.Add(item);
}
}
cnn.Close();
}
You Are Missing CommandType This:
cmd.CommandType=CommandType.Text;

Error querying the database for the first time

I have a curious problem. When do the first query in the database it's wrong, but on the second attempt it works perfectly, and not of the problem. What do I need to run it first?
This is the action button:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(AcessoBD.ConnectionString);
try
{
con.Open();
SqlCommand cmd = new SqlCommand("con", con);
//cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM usuario";
//cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
MessageBox.Show(dr["usuario"].ToString());
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}
Class AcessoBD:
public class AcessoBD
{
static public String ConnectionString
{
get
{ // pega a string de conexão do web.config
return ConfigurationManager.ConnectionStrings["Conexao"].ConnectionString;
//return WebConfigurationManager.ConnectionStrings["Conexao"].ConnectionString;
}
}
}
App.config:
<connectionStrings>
<add name="Conexao"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Base\Database.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
That's because of this line :
cmd.ExecuteNonQuery();
just remove it.
ExcuteNonQuery used for executing queries that haven't any table result like INSERT INTO ...
In this line :
MessageBox.Show(dr["usuario"].ToString());
if you want to get a string from a table you should use like this:
MessageBox.Show(dr.GetString(colIndex));
Yes, it looks like you run two questions.
Change this:
SqlCommand cmd = new SqlCommand("con", con);
cmd.CommandText = "SELECT * FROM usuario";
To:
SqlCommand cmd = new SqlCommand("SELECT * FROM usuario", con);

Categories