I seem to have a problem with VS 2015.
It gets me the same error and i don't know why. I inserted below the code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
textBox2.PasswordChar = '*';
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Exit_Click(object sender, EventArgs e)
{
this.Close();
}
private void LogIn_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Gigabyte\\Desktop\\apps\\WindowsFormsApplication3\\WindowsFormsApplication3\\Database1.mdf;Integrated Security=True");
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("SELECT Status FROM Login1 WHERE Username'" + textBox1.Text + "'AND Parola='" + textBox2.Text + "' ", con);
con.Close();
DataTable dt = new System.Data.DataTable();
sda.Fill(dt);
if(dt.Rows.Count==1)
{
Form2 ss = new Form2();
ss.Show();
}
}
}
}
The Application form stopped at the line with the sda.Fill(dt); and shows me this error:
Blockquote An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Blockquote
Additional information: Incorrect syntax near 'aa'.
Any help it is great! Thank you in advance!
Edit:
Problem Solved!
You are missing an = sign in your sql.
Additionally, you should be sanitizing your database inputs by using SqlParameters, not concatinating a string. You're setting yourself up for SQL Injection if you continue with your implementation.
One other optimization is that the SqlDataAdapter automatically manages your SqlConnection, so you don't need to call Open() or Close() when using Fill()
var cmd = new SqlCommand();
cmd.CommandText = "SELECT Status FROM Login1 WHERE Username = #username AND Parola= #parola";
cmd.Parameters.AddWithValue("#username", textbox1.Text);
cmd.Parameters.AddWithValue("#parola", textbox2.Text);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new System.Data.DataTable();
sda.Fill(dt);
Your string should be this I suppose :
Status FROM Login1 WHERE Username ='" + textBox1.Text + "' AND Parola='" + textBox2.Text + "'
You might have missed extra spaces ;)
Related
I have login issue authentication on windows form C# application. Once I register user it send user data to a SQL Server database. When I am trying to log in. Even if credentials match to data in data base message box showing up. Please see the code below.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using travel_booking.UserControlers;
using System.Data.SqlClient;
namespace travel_booking
{
public partial class UserContrLogin : UserControl
{
internal Action<object, EventArgs> OnUserLogin;
UserContrRegister userContrRegister;
public UserContrLogin()
{
InitializeComponent();
}
public void setUserContrRegister(UserContrRegister userContrRegister)
{
this.userContrRegister = userContrRegister;
}
private void Exit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void LoginButton_Click(object sender, EventArgs e)
{
SqlConnection sqlConnection = new SqlConnection(#"//Removed by me as it is sensitive data");
sqlConnection.Open();
string query = "Select * from tblUser Where Email = ' " + txtEmail.Text.Trim() + "' and Password = '" + txtPassword.Text.Trim() + "'";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query, sqlConnection);
DataTable dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
if (dataTable.Rows.Count > 0)
this.Hide();
else
MessageBox.Show("Email or/and Password is/are invalid. Please try again");
sqlConnection.Close();
}
}
}
You can use this code to work much better
public void Login()
{
SqlConnection sqlConnection = new SqlConnection(#"//Removed by me as it is sensitive data");
sqlConnection.Open();
string query = "Select * from tblUser Where Email = #Email and Password = #Password";
SqlCommand command = new SqlCommand();
command.Connection = sqlConnection;
command.CommandType = CommandType.Text;
command.Text = query;
command.Parameters.AddWithValue("#Email", txtEmail.Text.Trim());
command.Parameters.AddWithValue("#Password", txtPassword.Text.Trim());
SqlDataReader reader = command.ExecuteReader();
if(reader.Read() == true)
{
this.Hide();
}
else
{
MessageBox.Show("Email or/and Password is/are invalid. Please try again");
}
}
I use the command.Parameters.AddWithValue() to avoid the concatenation of the string of your query that can cause an SQL INJECTION
I facing error when want to pass my data which insert at Form1(frmLogin) to Form2(frmMain) SQL Query.
Form1(frmLogin)coding
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace SytelineAutoGenerateDocNum
{
public partial class frmLogin : Form
{
public frmLogin()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection sqlcon = new SqlConnection(#"Data Source=P13L3CFN756\SQLEXPRESS;Initial Catalog=Syteline_Misc_DocNum;Persist Security Info=True;User ID=sa;Password=1234;");
string query = "SELECT *FROM [Syteline_Misc_DocNum].[dbo].[users] Where username = '" + txtUsername.Text.Trim() + "' and password = '" + txtPassword.Text.Trim() + "'";
SqlDataAdapter sda = new SqlDataAdapter(query, sqlcon);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
if (dtbl.Rows.Count == 1)
{
frmMain objFrmMain = new frmMain();
//objFrmMain.Value = txtUsername.Text;
//objFrmMain.ShowDialog();
objFrmMain.Show();
this.Hide();
}
else
{
MessageBox.Show("Check your username and password");
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Form2(frmMain)Coding
private void buttonGDN_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("Insert into DocNum (Date,UserID,BusinessUnit,RunningNumber,DocumentNumber)values('" + txtUsername.Text + "')");
}
My Error is (The Name "txtUsername" does not exist in the current context).
I have provided an image of the error I am getting Error screenshot
Any help is much appreciated, Thanks
What I have tried:
I have no idea on the Error.
I have tried to enable the System Configuration on the reference, this did not solve the issue.
I am writing a C# windows forms program. When I want to login in the windows form, I get an error that says:
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Invalid object name 'Login'.
If there is a handler for this exception, the program may be safely continued.
What should I do? Thanks.
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 WindowsFormsApplication1
{
public partial class LOGIN : Form
{
public LOGIN()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\kenlui\Documents\LoginDate.mdf;Integrated Security=True;Connect Timeout=30;");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) from Login where Username ='" + textBox1.Text + "' and Password = '" + textBox2.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
main ss = new main();
ss.Show();
}
else
{
MessageBox.Show("Please Check Username and Password");
}
}
}
}
Either dbo.Login table does not exist OR it is associated with a different schema. When you create your tables and database objects you should prefix them with dbo. unless you know what schemas are and how to use them.
Some additional issues I find with your code:
You should never use string concatenation to create a sql statement. This leaves your code vulnerable to sql injection attacks and also syntax error (if the user name or password contained a ' for example.). Use parameterized sql instead.
Never store passwords in plain text. Use a hashing library and create a secure 1 way hash and persist that. When logging in create a hash from the presented password in the UI and compare that to the value in the database.
Your code never closes the database connection. To ensure it is always closed after you are done with it wrap it in a using block to ensure it is closed and disposed, this will help even if an exception is thrown.
Code with some corrections.
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\kenlui\Documents\LoginDate.mdf;Integrated Security=True;Connect Timeout=30;"))
using (SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) from Login where Username = #userName and Password = #password", con))
using (DataTable dt = new DataTable())
{
sda.SelectCommand.Parameters.Add(new SqlParameter("#userName", SqlDbType.VarChar) { Value = textBox1.Text });
// this should be a hash of the password, not the plain text value
sda.SelectCommand.Parameters.Add(new SqlParameter("#password", SqlDbType.VarChar) { Value = textBox2.Text });
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
main ss = new main();
ss.Show();
}
else
{
MessageBox.Show("Please Check Username and Password");
}
}
}
Finally instead of using a SqlDataAdapter consider using SqlCommand with ExecuteScalar instead.
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\kenlui\Documents\LoginDate.mdf;Integrated Security=True;Connect Timeout=30;"))
using (SqlCommand sda = new SqlCommand("Select 1 from Login where Username = #userName and Password = #password", con))
{
sda.Parameters.Add(new SqlParameter("#userName", SqlDbType.VarChar) { Value = textBox1.Text });
// this should be a hash of the password, not the plain text value
sda.Parameters.Add(new SqlParameter("#password", SqlDbType.VarChar) { Value = textBox2.Text });
var result = sda.ExecuteScalar();
if (result != null && 1 == (int)result)
{
this.Hide();
main ss = new main();
ss.Show();
}
else
{
MessageBox.Show("Please Check Username and Password");
}
}
}
I'm trying to writing a basic c# program that read datas from SQL and writes results on 3 textboxes and a label. Here is my code;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace PLAKA
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=TESTDB;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Project where ID = '" + textBox1.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
textBox1.Text = dt.Rows[0][0].ToString();
textBox2.Text = dt.Rows[0][1].ToString();
textBox3.Text = dt.Rows[0][2].ToString();
textBox4.Text = dt.Rows[0][3].ToString();
SqlDataAdapter oks = new SqlDataAdapter("SELECT * FROM Project where Status = 'YES'", con);
if (oks)
{
label1.Text = "POSITIVE";
}
else
{
label1.Text = "NEGATIVE";
}
}
}
}
I'm writing ID number and see the informations of this ID on text boxes in my first part of my code and this works perfectly
All i need that when value in the 'Status' raw is "YES", my program writes "POSITIVE", other else writes 'NEGATIVE' on label1
Meanwhile Status information writes on Textbox3.
For this code i got this error message: "Error 1 Cannot implicitly convert type 'System.Data.SqlClient.SqlDataAdapter' to 'bool'
How can i solve this problem?
Your If condition is wrong.
use this.
SqlDataAdapter oks = new SqlDataAdapter("SELECT * FROM Project where Status = 'YES'", con);
oks.fill(dataSet)
if (dataSet.Tables["Table"].Rows.Count > 1)
{
label1.Text = "POSITIVE";
}
else
{
label1.Text = "NEGATIVE";
}
I'm trying to search my database to retrieve some results and populate those to a gridview.
However, I get the above error in the title, and some research hasn't really helped me on why this kind of error flags, and was wondering whether someone with a sharper mind could explain the reason for this error. My code for the code behind file of the specific page is shown below:
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.Configuration;
namespace StarksComics
{
public partial class search : System.Web.UI.Page
{
SqlConnection con = new SqlConnection();
string b = "";
protected void Page_Load(object sender, EventArgs e)
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["DBVS"].ConnectionString; // the error occurs at this line. ---- nullreference exception was unhandled by code.
if (con.State == ConnectionState.Closed)
{
con.Open();
}
}
private void user_chk()
{
string a;
a = TextBox1.Text;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from tbCharacters where CharName like'" + a + "%'";
cmd.Connection = con;
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
rep_bind();
GridView1.Visible = true;
TextBox1.Text = "";
}
else
{
GridView1.Visible = false;
b = TextBox1.Text + "is not available in list";
TextBox1.Text="";
}
}
private void rep_bind()
{
string a;
a = TextBox1.Text;
SqlDataAdapter adp = new SqlDataAdapter("select * from tbCharacters where CharName like'" + a + "%'",
ConfigurationManager.ConnectionStrings["DBVS"].ConnectionString);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
user_chk();
}
}
}
once again, thank you all kindly for reviewing my code. (I've commented out the line, it's just not visible unless you drag the bar, in the page load method.)
Obviously it can't find the connection string DBVS.
Check your web.config whether it exists.
Try this code to check for null on the connection:
ConnectionString connStr = ConfigurationManager.ConnectionStrings["DBVS"];
if (connStr == null)
{
throw new Exception("Cannot find connection string DBVS in web.config");
}