Runtime Error after Button click - c#

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.

Related

Checking if username is available in database

I'm trying to check if the username is already in use in C# database and it's giving me this error
SqlConnection cn = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\admin\Desktop\241 Project sem 1 2020-2021\Online Banking - ITIS 241 project group 9\UobBankDatabase.mdf; Integrated Security = True; Connect Timeout = 30");
cn.Open();
SqlCommand cmd = new SqlCommand("select * from LoginTable where user_name='" + textBox1.Text + "'", cn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
dr.Close();
MessageBox.Show("Username Already exist please try another ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
dr.Close();
}
and yes I'm a newbie
Use this:
SqlCommand cmd = new SqlCommand("Select count(*) from LoginTable where user_name='" + textBox1.Text + "'", cn);
Then:
var dr = cmd.ExecuteScalar();
if (dr != null)
{
//Exists
}
else
{
//Unique username
}
Google it please:
Since the error is SqlException: Invalid object name 'Movie' , that
means the table named 'Movie' has not created or the Database you are
referring has not created. To see if the Database or table 'Movie' has
created, open SQL Server Object Explorer and check the Database name
is the same as in appsettings. json
And Please tell us at what line do you get that?
Is that this line =>if (dr.Read())
Let's extract method for the check:
private static bool NameAvailable(string name) {
//DONE: wrap IDisposable into using
using (SqlConnection cn = new SqlConnection("Connection String Here")) {
cn.Open();
//DONE: keep Sql readable
//DONE: make Sql parametrize
//DONE: select 1 - we don't want entire record but a fact that record exists
string sql =
#"select 1
form LoginTable
where user_name = #prm_user_name";
using (var cmd = new SqlCommand(sql, cn)) {
cmd.Parameters.Add("#prm_user_name", SqlDbType.VarChar).Value = name;
using (var dr = cmd.ExecuteReader()) {
return !dr.Read(); // Not available if we can read at least one record
}
}
}
}
Then you can put
if (!NameAvailable(textBox1)) {
// Let's be nice and put keyboard focus on the wrong input
if (textBox1.CanFocus)
textBox1.Focus();
MessageBox.Show("Username Already exist please try another ",
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
some changes only.it is better to get what is the error than a temporary solution so print your query first and run it in the sqlserver . also add initial catalog instead of attacjing mdf files its way better in my opinion.
<connectionStrings>
<add name="stringname" connectionString="Data Source=mssql;Initial Catalog=databasename; Persist Security Info=True;User ID=sa;Password=*****;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
using a connection string instead also
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["stringname"].ConnectionString);
cn.Open();
string query = "select * from LoginTable where user_name='" + textBox1.Text.ToString() + "'";
SqlCommand cmd = new SqlCommand(query, cn);
SqlDataReader dr = cmd.ExecuteReader();
//print query if error and comment the execute reader section when printing the query to know the error Respone.Write(query);
if (!dr.HasRows)
{
// ur code to insert InsertItemPosition values
}
else
{
//show username exist
}
dr.Close();
Try this:
string conString = ConfigurationManager.ConnectionStrings["YourConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT COUNT(UserName) as UserCount FROM LoginTable WHERE user_name = #user_name", con))
{
con.Open();
cmd.Parameters.AddWithValue("#user_name", TextBox1.Text);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows)
{
if(Convert.ToInt32(dr["UserCount"].ToString()) >= 1)
{
// Exists
}
else
{
// Doesn't Exist
}
}
}
con.Close();
}
}

object reference not set to an instance of an object, sql query not runnable?

I'm pretty sure that the Sql Syntax is right since it's a legit query.
However i've never stumbled on this issue before.
private void button1_Click(object sender, EventArgs e)
{
string ett = textBox1.Text;
if (ett == "")
{
MessageBox.Show("Du måste fylla i UID, vilket du finner i användarlistan.");
return;
}
try
{
if (connect.State == ConnectionState.Open)
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
MySqlDataReader accessed = cmd.ExecuteReader();
MessageBox.Show("Användaren borttagen.");
}
else
{
MessageBox.Show("Något gick tyvärr fel, kontakta systemadministratören.");
}
}
catch (Exception ex)
{
{ MessageBox.Show(ex.Message); }
}
}
The problem may be related to this:
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
MySqlDataReader accessed = cmd.ExecuteReader();
MessageBox.Show("Användaren borttagen.");
}
try
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandType = CommandType.Text
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
cmd.ExecuteNonQuery
MessageBox.Show("Användaren borttagen.");
}
Now you've shown us your whole code in the comments, the problem is obvious.
You have written a method to initialise, set up and open your database connection; and this other method which runs on a button click, which uses it.
However, nowhere in your code do you call the method which initialises your database connection, therefore it is not set up when you try to use it - obvious really.
I can see you think you are checking to see if the connection is working by checking its State property, but calling any sort of method or property accessor on an uninitialised reference type won't work, you'll get the NullReferenceException you've been getting.
To fix, call the connection set up method from your button press, before trying to use the connection:
private void button1_Click(object sender, EventArgs e)
{
string ett = textBox1.Text;
if (ett == "")
{
MessageBox.Show("Du måste fylla i UID, vilket du finner i användarlistan.");
return;
}
try
{
db_connection(); //added this line
if (connect.State == ConnectionState.Open)
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
MySqlDataReader accessed = cmd.ExecuteReader();
MessageBox.Show("Användaren borttagen.");
}
else
{
MessageBox.Show("Något gick tyvärr fel, kontakta systemadministratören.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You have not defined the variable, "connect".

NullReferenceException in SQL Server 2014

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.

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

Getting Data From Sql Server 2008 with C#

I'm trying to make a login facility for Windows Forms Application project. I'm using Visual Studio 2010 and MS Sql Server 2008.
I referenced this article:
http://www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C
Here is my database table named user:
I have TextBox1 for user name , TextBox2 for user password and Button1 for starting login process. Here is my code for Button1_Click method:
private void button1_Click(object sender, EventArgs e)
{
string kullaniciAdi; // user name
string sifre; // password
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Data Source=localhost; database=EKS; uid=sa; pwd=123; connection lifetime=20; connection timeout=25; packet size=1024;";
myConn.Open();
try
{
SqlDataReader myReader;
string myQuery = ("select u_password from user where u_name='" + textBox1.Text + "';");
SqlCommand myCommand = new SqlCommand(myQuery,myConn);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
sifre = myReader["u_password"].ToString();
}
}
catch (Exception x)
{
MessageBox.Show(x.ToString());
}
myConn.Close();
}
I don't have much experience with C# but i think i'm missing something small to do it right. Below i share exception message that i catched. Can you show me what i'm missing? (line 33 is myReader = myCommand.ExecuteReader();)
Considerin given answers, i updated my try block as in below but it still does not work.
try
{
SqlDataReader myReader;
string myQuery = ("select u_password from [user] where u_name=#user");
SqlCommand myCommand = new SqlCommand(myQuery, myConn);
myCommand.Parameters.AddWithValue("#user", textBox1.Text);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
sifre = myReader["u_password"].ToString();
}
if (textBox2.Text.Equals(sifre))
{
Form2 admnPnl = new Form2();
admnPnl.Show();
}
}
After changing whole code as below by sine's suggestion, screenshot is also below:
And i think, somehow i cannot assign password in database to the string sifre.
code:
string sifre = "";
var builder = new SqlConnectionStringBuilder();
builder.DataSource = "localhost";
builder.InitialCatalog = "EKS";
builder.UserID = "sa";
builder.Password = "123";
using (var conn = new SqlConnection(builder.ToString()))
{
using (var cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select u_password from [user] where u_name = #u_name";
cmd.Parameters.AddWithValue("#u_name", textBox1.Text);
conn.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var tmp = reader["u_password"];
if (tmp != DBNull.Value)
{
sifre = reader["u_password"].ToString();
}
}
if (textBox2.Text.Equals(sifre))
{
try
{
AdminPanel admnPnl = new AdminPanel();
admnPnl.Show();
}
catch (Exception y)
{
MessageBox.Show(y.ToString());
}
}
else
{
MessageBox.Show("incorrect password!");
}
}
}
}
User is a reserved keyword in T-SQL. You should use it with square brackets like [User].
And you should use parameterized sql instead. This kind of string concatenations are open for SQL Injection attacks.
string myQuery = "select u_password from [user] where u_name=#user";
SqlCommand myCommand = new SqlCommand(myQuery,myConn);
myCommand.Parameters.AddWithValue("#user", textBox1.Text);
As a general recomendation, don't use reserved keywords for your identifiers and object names in your database.
Try to put user into [ ] because it is a reseved Keyword in T-SQL and use Parameters, your code is open to SQL-Injection!
private void button1_Click(object sender, EventArgs e)
{
var builder = new SqlConnectionStringBuilder();
builder.DataSource = "servername";
builder.InitialCatalog = "databasename";
builder.UserID = "username";
builder.Password = "yourpassword";
using(var conn = new SqlConnection(builder.ToString()))
{
using(var cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select u_password from [user] where u_name = #u_name";
cmd.Parameters.AddWithValue("#u_name", textBox1.Text);
conn.Open();
using(var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var tmp = reader["u_password"];
if(tmp != DBNull.Value)
{
sifre = reader["u_password"].ToString();
}
}
}
}
}
}
USER is a reserved word in T-SQL
Try putting [] around reserved words.
string myQuery = ("select u_password from [user] where u_name='" + textBox1.Text + "';");
user is a keyword.
Change it to something like
string myQuery = ("select u_password from [user] where u_name='" + textBox1.Text + "';");
Futher to that I recomend you have a look at Using Parameterized queries to prevent SQL Injection Attacks in SQL Server
User is a reserved keyword in SQL, you need to do this:
select u_password from [user] where u_name=#user
And as ever, with basic SQL questions, you should always use parameterised queries to prevent people from running any old commands on your DB via a textbox.
SqlCommand myCommand = new SqlCommand(myQuery,myConn);
myCommand.Parameters.AddWithValue("#user", textBox1.Text);

Categories