Insert data into Npgsql/Postgresql database with C# windows forms - c#

I am completely new to programming and I am trying to create a small app as a school project. I want it to be able to register and login users. I have already figured out how to create login part, but I am stuck on registration. I have created Insert function inside pgAdmin and it works but I cant make it work with my windows forms app.
This is my code so far:
using Npgsql;
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;
namespace ProjektV0._0._2
{
public partial class frmRegister : Form
{
public frmRegister()
{
InitializeComponent();
}
private NpgsqlConnection conn;
string connstring = String.Format("Server={0}; Port={1};" +
"User Id = {2}; Password={3};Database={4};",
"localhost", "5432", "postgres", "23112001", "demo2");
private NpgsqlCommand cmd;
private string sql = null;
private void frmRegister_Load(object sender, EventArgs e)
{
conn = new NpgsqlConnection(connstring);
}
private void Register_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
private void btnRegister_Click(object sender, EventArgs e)
{
try
{
conn.Open();
sql = #"select * from u_insert(:_username,:_password)";
cmd = new NpgsqlCommand(sql, conn);
cmd.Parameters.AddWithValue("_username", txtEmail.Text);
cmd.Parameters.AddWithValue("_password", txtPswrd.Text);
if ((int)cmd.ExecuteScalar() == 1)
{
conn.Close();
MessageBox.Show("Registered successfuly", "Well done", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
txtEmail.Text = txtPswrd.Text = txtConPswrd.Text = null;
}
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show("Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
pgAdmin part:
create function u_insert
(
_username character varying,
_password character varying
)returns int as
$$
begin
insert into tbl_users
(
username,
password
)values
(
_username,
_password
);
if found then
return 1;-----success-----
else
return 0;-----fail-----
end if;
end
$$
language plpgsql
As I said my login part work even through my program and all other functions (insert,update) work only inside pgAdmin.

To clarify my comment... why the function/procedure? It seems dramatic overkill for an insert. I would put something like this outside of my form (in a CRUD class somewhere):
public static int UpdateUser(string UserId, string Password, out string ErrorMessage)
{
int result = 0;
ErrorMessage = null;
NpgsqlConnectionStringBuilder sb = new NpgsqlConnectionStringBuilder();
sb.Host = "localhost";
sb.Port = 5432;
sb.Username = "postgres";
sb.Password = "23112001";
sb.Database = "demo2";
using (NpgsqlConnection conn = new NpgsqlConnection(sb.ToString()))
{
conn.Open();
string dml = "insert into tbl_users (username, password) values (:USER, :PW)";
using (NpgsqlCommand cmd = new NpgsqlCommand(dml, conn))
{
cmd.Parameters.AddWithValue("USER", UserId);
cmd.Parameters.AddWithValue("PW", Password);
try
{
result = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
}
}
}
return result;
}
And then within the Button Click event you can simplify it to this:
private void btnRegister_Click(object sender, EventArgs e)
{
string error;
int insertedRows = CrudClass.UpdateUser(txtEmail.Text, txtPassword.Text, out error);
if (insertedRows == 1)
{
MessageBox.Show("Registered successfuly", "Well done", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
txtEmail.Text = txtPswrd.Text = txtConPswrd.Text = null;
}
else
{
MessageBox.Show("Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

The connection string is invalid for Postgres. It should rather be "Host={0}; Port={1}; Username= {2}; Password={3};Database={4};"
Then the parameter placeholder should be #, not :
Tip 1: read the doc of the proper database
Note that the connection string is invalid, and opening the connection likely throws an error. In the catch section, you start by closing the connection then you display the error message. If closing the connection fails and throws an error, the code after it will never be executed.
Tip 2: don't do anything that can throw an error within a catch section. You can nest another try..catch though.

Related

No value given for one or more required parameters - C#/Access

This is my first time attempting to read an Access database and write each row to the console. When I execute the application I get thrown an exception that says, "No value given for one or more required parameters" on the following statement:
OleDbDataReader reader = cmd.ExecuteReader();
I'm relatively new to c# programming and after hours of research, I can't figure out what I'm doing wrong. Here's my code:
private void maintenanceToolStripMenuItem_Click(object sender, EventArgs e)
{
//Use a variable to hold the SQL statement.
string inputString = "SELECT Full_Name, First_Name, Last_Name, Company FROM CONTACTS";
try
{
//Create an OleDbCommand object and pass in the SQL statement and OleDbConnection object
OleDbCommand cmd = new OleDbCommand(inputString, conn);
//Send the CommandText to the connection, and then build an OleDbDataReader.
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader.GetString(1));
reader.NextResult();
}
}
reader.Close();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
In response to the commenters, I'm posting a larger piece of code to eliminate any assumptions and give a better overall picture of what I'm trying to do:
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.OleDb;
using System.IO;
namespace AzFloodSquad
{
public partial class frm1DefaultScreen : Form
{
//Initialize the application
String conn_string = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\\Databases\\AzFloodSquad\\AzFloodSquad.accdb;Persist Security Info=False;";
OleDbConnection conn = null;
String error_message = "";
String q = "";
string varReportId = "";
public frm1DefaultScreen()
{
InitializeComponent();
}
//Load the default form
private void frm1DefaultScreen_Load(object sender, EventArgs e)
{
connectToolStripMenuItem.PerformClick();
contactsToolStripMenuItem.PerformClick();
}
//Exit the application
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
//Start the database
private void connectToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
conn = new OleDbConnection(conn_string);
conn.Open();
disconnectToolStripMenuItem.Enabled = true;
connectToolStripMenuItem.Enabled = false;
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
//Stop the database
private void disconnectToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
conn.Close();
disconnectToolStripMenuItem.Enabled = false;
connectToolStripMenuItem.Enabled = true;
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
//Clean up database whem form close button clicked
private void frm1DefaultScreen_FormClosing(object sender, FormClosingEventArgs e)
{
disconnectToolStripMenuItem.PerformClick();
}
private void contactsToolStripMenuItem_Click(object sender, EventArgs e)
{
varReportId = "Contacts";
q = "SELECT * " +
"FROM CONTACTS WHERE CONTACTS.CONTACT_TYPE = 'CUSTOMER' " +
"OR CONTACTS.CONTACT_TYPE = 'HOMEOWNER' OR CONTACTS.CONTACT_TYPE = 'HOME OWNER' " +
"OR CONTACTS.CONTACT_TYPE = 'TENANT'" +
"ORDER BY FULL_NAME";
this.Cursor = Cursors.WaitCursor;
run_Query_Parm(q);
this.Cursor = Cursors.Default;
}
//Pull data from the database using the parameter field
private void run_Query_Parm(String q)
{
error_message = "";
try
{
OleDbCommand cmd = new OleDbCommand(q, conn);
OleDbDataAdapter a = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
a.SelectCommand = cmd;
a.Fill(dt);
results.DataSource = dt;
results.AutoResizeColumns();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
}
//Clear all data from the screen
private void clearFormToolStripMenuItem_Click(object sender, EventArgs e)
{
varReportId = "";
if (this.results.DataSource != null)
{
this.results.DataSource = null;
}
else
{
this.results.Rows.Clear();
}
}
private void maintenanceToolStripMenuItem_Click(object sender, EventArgs e)
{
//Use a variable to hold the SQL statement.
string inputString = "SELECT Full_Name, First_Name, Last_Name, Company FROM CONTACTS";
try
{
//Create an OleDbCommand object and pass in the SQL statement and OleDbConnection object
OleDbCommand cmd = new OleDbCommand(inputString, conn);
//Send the CommandText to the connection, and then build an OleDbDataReader.
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader.GetString(1));
reader.NextResult();
}
}
reader.Close();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
}
Any help provided would be greatly appreciated. Thanks in advance.
I found the problem. Apparently, I had improper syntax on my SELECT statement. When I replaced my SELECT, (shown in the first code example I posted), with the following, it worked fine:
string inputString = "SELECT Contacts.[Account_Number], " +
"Contacts.[Full_Name], Contacts.[ID], Contacts.[Street], " +
"Contacts.[City], Contacts.[State], Contacts.[Zip] FROM Contacts";

Is there a better way to connect my DB to my Form?

I'm trying to connect my DB to my ListView, and I'm trying to find a better way than what's in the book. I looked at a couple forums and a lot of them have the same thing like what's in my code down below.
We didn't have a lot of time to go over databases in class, so a lot of my knowledge with connection strings come from the internet and a small chapter in the book.My Database name is GameStoreLibrary.
using System.Data;
using System.Data.SqlServerCe;
public partial class DisplayGameStoreTable : Form
{
//WHAT THE C# FORUMS SAY TO DO
public SqlCeConnection cn = new SqlCeConnection(#"
Data Source=.;
Initial Catalog=DB GameStoreLibrary;
Integrated Security=True;
MultipleActiveResultSets=True");
private void DisplayGameStoreTable_Load(object sender, EventArgs e)
{
try
{
cn.Open();
}
catch(SqlCeException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
}
private void NewGameBttn_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
SqlCeCommand cm = new SqlCeCommand("SELECT * FROM newGames ORDER BY gametitle ASC", cn);
try
{
SqlCeDataAdapter da = new SqlCeDataAdapter(cm);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
ListViewItem item = new ListViewItem(dr["gametitle"].ToString());
item.SubItems.Add(dr["releasedate"].ToString());
item.SubItems.Add(dr["console"].ToString());
item.SubItems.Add(dr["company"].ToString());
item.SubItems.Add(dr["gameprice"].ToString());
item.SubItems.Add(dr["quantity"].ToString());
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Small Tip :
Try to use a DBConnect class instead of typing connection string every single time and closing the connection.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace InventoryManagementSystem
{
class DBConnect : IDisposable
{
private static String connectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\Private\InventoryManagementSystem\InventoryManagementSystem\InventoryDB.mdf;Integrated Security=True";
public SqlConnection con = new SqlConnection(connectionString);
public DBConnect()
{
try
{
con.Open();
Console.WriteLine("Database connected");
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
Console.WriteLine("Database Connection Failed");
throw new Exception();
}
}
public void Dispose()
{
con.Close();
}
}
}
After you have this in your project you just have to create an object whenever you want to access the database.
public void getData(){
using(DBConnect db = new DBConnect()){
String q = "select * from TestTable";
SqlCommand cmd = new SqlCommand(q,db.con);
SqlDatareader r = cmd.ExcecuteReader();
}
}
This will automatically close the connections too.
To add on to Gihan's answer, it's also an accepted practice to create the App.Config file and put the connection string in there so it's not inside your source code. Then it's easier to change without recompiling anything.
Use the ConnectionStrings section of the App.Config and then you can get the connection string using the code:
System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;

Executing a SQL query with C#

I would like to add some information to my database. I searched for some tutorials, but none of them work.
NonQuery can do what he needs to do, because the messagebox returns "Success" (1). But it does not update my database. If I put the same query to "Add New Query", directly to my database, it works.
Can someone help me?
My class code at the moment:
namespace BurnThatFat
{
class databaseconnection
{
//fields
SqlConnection connection;
string connectionstring;
public databaseconnection()
{
// fields waarde toewijzen
connectionstring = #"Data Source=(LocalDB)\MSSQLLocalDB;" +
#"AttachDbFilename=|DataDirectory|\Database2.mdf;Integrated Security=True";
connection = new SqlConnection(connectionstring);
OpenConnection();
CloseConnection();
}
public List<Object> getObjectsFromDatabase()
{
try
{
OpenConnection();
// sql query
// Datareader
// sqlcommand
// return list van objecten , objecten veranderd naar jouw wens van data.
CloseConnection();
}
catch (Exception)
{
throw;
}
return new List<object>();
}
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
public void AddGebruiker()
{
string query = "insert into Gebruiker VALUES(3, 'Cihan', 'Kurt', 18, 'Man', 85, 75, 'Admin1', 'Test123', 'testen');";
using (connection)
{
SqlCommand command = new SqlCommand(query, connection);
OpenConnection();
int resultaat = command.ExecuteNonQuery();
if (resultaat == 1)
{
MessageBox.Show("succes");
}
else
{
MessageBox.Show("fail");
}
}
}
}
}
Edit:
And this is the code for my buttons etc:
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;
// voor sql connectie.
using System.Data.SqlClient;
namespace BurnThatFat
{
public partial class SignUp : Form
{
databaseconnection db = new databaseconnection();
public SignUp()
{
InitializeComponent();
gb_login.Visible = false;
gb_Voornaam.Visible = false;
gb_Achternaam.Visible = false;
gb_leeftijdgeslacht.Visible = false;
gb_gewicht.Visible = false;
gb_email.Visible = false;
gb_Start.Visible = true;
}
private void btn_SignUp_Click(object sender, EventArgs e)
{
gb_Start.Visible = false;
gb_Voornaam.Visible = true;
}
private void btn_login_Click(object sender, EventArgs e)
{
gb_Start.Visible = false;
gb_login.Visible = true;
}
private void btn_loginvolgende_Click(object sender, EventArgs e)
{
gb_login.Visible = false;
// hier moet nog een GB!!!!!!
}
private void btn_voornaamvolgende_Click(object sender, EventArgs e)
{
gb_Voornaam.Visible = false;
gb_Achternaam.Visible = true;
}
private void btn_achternaamvolgende_Click(object sender, EventArgs e)
{
gb_Achternaam.Visible = false;
gb_leeftijdgeslacht.Visible = true;
}
private void btn_leeftijdvolgende_Click(object sender, EventArgs e)
{
gb_leeftijdgeslacht.Visible = false;
gb_gewicht.Visible = true;
}
// einde registratie
// opslaan van gegevens in database
private void btn_emailvolgende_Click(object sender, EventArgs e)
{
// gebruiker = new Gebruikerklasse();
// gebruiker.Naam = Convert.ToString(tb_voornaam.Text);
//// gebruiker.Achternaam = Convert.ToString(tb_achternaam.Text);
// gebruiker.Leeftijd = Convert.ToInt32(nud_leeftijd.Value);
/// gebruiker.Geslacht = Convert.ToString(cb_geslacht.Text);
// gebruiker.Huidig_gewicht = Convert.ToInt32(nud_huidiggewicht.Value);
// gebruiker.Streef_gewicht = Convert.ToInt32(nud_streefgewicht.Value);
/// gebruiker.Gebruikersnaam = Convert.ToString(tb_gebruikersnaam2.Text);
// gebruiker.Email = Convert.ToString(tb_email.Text);
// gebruiker.Wachtwoord = Convert.ToString(tb_wachtwoordsignup.Text);
db.AddGebruiker();
gb_email.Visible = false;
// hier moet nog een GB!!!!!
}
private void btn_gewichtvolgende_Click(object sender, EventArgs e)
{
gb_gewicht.Visible = false;
gb_email.Visible = true;
}
}
}
The simplest way to insert into a SQL Server database:
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database2.mdf;Integrated Security=True";
string commandText = "INSERT INTO MyTable (ID, Name, Address) VALUES (10, 'Bob', '123 Main Street');";
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(commandText, conn))
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
As long as commandText is a working query, it should insert a row. It would be better to use parameters for your values instead of hard coding them like I did here - that avoids SQL injection attacks and other potential problems. You can search Google for that (or the question you are asking now) and find tons of resources to help you.
If you need more specific help, post details such as what is actually happening when you try to run your code - are you getting an exception?
I'd clean up a bunch of things before doing anything else.
First, get rid of the openconnection and closeconnection methods all together. And don't keep an instance property for the connection in your class. Create the connection ondemand with a using statement, because at the end of the using statement the compiler will insert a call to the Dispose method on the connection's IDisposable interface implementation and it will close the connection automatically for you.
So after cleaning up all the unnecessary code all you really should have in this class is an implementation of your Addgebrukier method which would look like this
public void AddGebruiker()
{
string query = "insert into Gebruiker VALUES(3, 'Cihan', 'Kurt', 18, 'Man', 85, 75, 'Admin1', 'Test123', 'testen');";
using (SqlConnection connection = new SqlConnection(connectionstring))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
int resultaat = command.ExecuteNonQuery();
if (resultaat == 1)
{
MessageBox.Show("succes");
}
else
{
MessageBox.Show("fail");
}
}
}
}
You should also load your connection string from the section in the app/web.config, but you can do that later after you get it running.
Here is a simple concept that should work perfectly fine for you. Just change the ServerName, DatabaseName, etc.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
sql = "insert into product (Product_id,Product_name,Product_price) values(6,'Product6',600)";
try
{
connection.Open();
adapter.InsertCommand = new SqlCommand(sql, connection);
adapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show ("Row inserted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

How to check if ID already exists in MS Access database file, and how to check it by using TextChanged in TextBox?

I am working on part of my program where I am deleting entry by using provided Entry ID.
As of right now I am deleting any entry specified by user. This works great but, what I am trying to do is to inform user that there is no such ID to delete. Also, I am using textbox TextChanged which let me to check for certain things in user input while user is typing.
Now, how do I check if Entry ID already exists? What should I include in my if statement to do this?
Also, is there a way I could check that by using TextChanged event handler? I'm not sure about that because I know that if I would have opening and closing connection in TextChanged event, then connection would be opened/closed every time user is typing, so I don't think this is a good idea. But how can I avoid this and so I can do this in real time? Perhaps when user stop typing, and then take a second or two to check for entry id?
This is a code of my delete entry window:
public partial class DeleteEntryWindow : Form
{
string user, pass, filePath;
// Initializing MainWindow form.
MainWindow mainWindow;
public DeleteEntryWindow()
{
InitializeComponent();
txtEntryID.TextChanged += new EventHandler(ValidateInput);
}
public DeleteEntryWindow(MainWindow viaParameter,
string user, string pass, string filePath)
: this()
{
mainWindow = viaParameter;
this.user = user;
this.pass = pass;
this.filePath = filePath;
}
private void ValidateInput(object sender, EventArgs e)
{
int intNumber;
if (!string.IsNullOrEmpty(txtEntryID.Text) &&
int.TryParse(txtEntryID.Text, out intNumber) &&
intNumber > 0)
{
lblMessage.Text = "Entry ID is valid.";
lblMessage.ForeColor = Color.Green;
btnDeleteEntry.Enabled = true;
}
else
{
lblMessage.Text = "You must enter Entry ID number!";
lblMessage.ForeColor = Color.IndianRed;
btnDeleteEntry.Enabled = false;
}
}
private void btnDeleteEntry_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show
("Are you sure you want to remove this entry?",
"Information", MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
// SQL query which will delete entry by using entry ID.
string sql = "DELETE FROM PersonalData WHERE DataID = " +
txtEntryID.Text;
DeleteData(sql);
lblMessage.Text = "Entry was deleted!";
lblMessage.ForeColor = Color.Green;
}
else
{
// Do nothing.
}
}
private void DeleteData(string sql)
{
HashPhrase hash = new HashPhrase();
string hashShortPass = hash.ShortHash(pass);
// Creating a connection string. Using placeholders make code
// easier to understand.
string connectionString =
#"Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0};
Persist Security Info=False; Jet OLEDB:Database Password={1};";
using (OleDbConnection connection = new OleDbConnection())
{
// Creating command object.
// Using a string formatting let me to insert data into
// place holders I have used earlier.
connection.ConnectionString =
string.Format(connectionString, filePath, hashShortPass);
using (OleDbCommand command = new OleDbCommand(sql, connection))
{
OleDbParameter prmDataID = new OleDbParameter
("#DataID", txtEntryID.Text);
command.Parameters.Add(prmDataID);
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
}
}
To check if the ID already exists, you will need to use SQL just as your delete method does. The following may give you a starting point:
private bool DoesIDExist(string ID)
{
string filePath = ""; //TODO
string hashShortPass = ""; //TODO
DataTable temp = new DataTable();
bool result = false;
string connectionString =""; //TODO
using (OleDbConnection connection = new OleDbConnection(ConnectionString))
{
string sql = #"SELECT * FROM PersonalData WHERE DataID = #DataID";
using (OleDbCommand command = new OleDbCommand(sql, connection))
{
command.Parameters.Add(new OleDbParameter("#DataID", ID));
using (OleDbDataAdapter oda = new OleDbDataAdapter(command))
{
try
{
oda.Fill(temp);
if (temp != null && temp.Rows.Count > 0)
result = true; //ID exists
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
}
return result;
}

Null reference on SQL connection object

I am new to C#. I have created the login screen.I this one am not able to check the username and password.This is my code.Can anyone help me please.Thanks in advance.Please don't hesitate to copy 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;
using System.Data.Sql;
namespace Voting_Editor_Tool
{
public partial class Form1 : Form
{
SqlConnection cn;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
string username = txtusername.Text;
string password = txtpassword.Text;
if (ValidateUserNamePassword(username, password))
{
// move to next form or do whatever you need to do after a successfull login
}
else
{
MessageBox.Show("Invalid user name or password", "Invalid Login");
return;
}
}
public bool ValidateUserNamePassword(string _username, string _password)
{
// string connectionString = "Data Source=[servername];Initial Catalog=[databaseName];User ID=[Admin Login];Password=[Admin Password];";
using (SqlConnection cn= new SqlConnection(#"User ID=sa;Password=password123;Initial Catalog=dish_tv;Data Source=ENMEDIA-CCDDFE5\ENMEDIA"));
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "tsp_GetUserNameAndPassword";
SqlParameterCollection sqlParams = cmd.Parameters;
sqlParams.AddWithValue("#username", _username);
sqlParams.AddWithValue("#password", _password);
cn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleRow);
if (dr.Read())
{
// this will return true if a row matching the username and password is found.
// this means that the user's input is valid
return true;
}
else
{
return false;
}
dr.Close();
cn.Close();
}
}
}
}
Remove your using clause and put that piece of code into Try.. catch block. Catch the exception object and read its stacktrace. Check the connection string carefully for any typo mistakes. This should give you much more details to debug than generic error like "Object reference not set to an instance of an object"
You have a semi-colon at the end of your using statement, therefore terminating the using. Remove the semi-colon and it will work.

Categories

Resources