I am making a simple project where I take "id" and "name" from user and store it into the Access Data base. Whenever I press the Store button System.NullReferenceException Error Comes out. Here is the Code
Where I declared Oledpconnection.
public OleDbConnection Con;
public Form1()
{
InitializeComponent();
string connetionString = null;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/Users/Mujahid/Documents/Visual Studio 2008/Projects/ts/ts/ts.accdb";
OleDbConnection Con = null;
Con = new OleDbConnection(connetionString);
try
{
Con.Open();
MessageBox.Show("Connection Open ! ");
Con.Close();
}
catch (Exception)
{
MessageBox.Show("Can not open connection ! ");
}
}
And here is the insert button programing
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText="insert into ts(ID,Name)" +"Values ('"+textBox1.Text+"','"+textBox2.Text+"')" ;
cmd.Connection= Con;
Con.Open();
cmd.ExecuteNonQuery();
Con.Close();
please Help !!
Con needs to be a form scope object, not redeclare in the forms constructor.
public OleDbConnection Con;
public Form1()
{
InitializeComponent();
string connetionString = null;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/Users/Mujahid/Documents/Visual Studio 2008/Projects/ts/ts/ts.accdb";
Con = new OleDbConnection(connetionString);
try
{
Con.Open();
MessageBox.Show("Connection Open ! ");
Con.Close();
}
catch (Exception)
{
MessageBox.Show("Can not open connection ! ");
}
}
public OleDbConnection Con;
...
OleDbConnection Con = null;
You never initialize the class scoped connection instance.
Related
This is my connection class
class connection
{
public SqlConnection con;
public SqlCommand cmd;
public SqlDataAdapter sda;
String pkk;
public void connectionFunc()
{
con = new SqlConnection(#"Data Source=.;Initial Catalog=payroll;Integrated Security=True");
con.Open();
}
public void dataSend(String SQL)
{
try
{
connectionFunc();
cmd = new SqlCommand(SQL, con);
cmd.ExecuteNonQuery();
pkk = "";
}
catch(Exception)
{
pkk = "error";
}
con.Close();
}
public void dataGet(String SQL)
{
try
{
connectionFunc();
sda = new SqlDataAdapter(SQL, con);
}
catch(Exception)
{
}
}
}
And this is the use of the class:
connection con = new connection();
con.dataGet("Select * from [users] Where Userame = '" + textBox1.Text + "' and Password = '" + textBox2.Text + "'");
DataTable dt = new DataTable();
// this line throws an error
con.sda.Fill(dt);
if(dt.Rows.Count > 0)
{
this.Hide();
Mainpage obj = new Mainpage();
obj.Show();
}
else
{
MessageBox.Show("Invalid UserName Or Password..!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
I get the following error:
An unhandled exception of type 'System.NullReferenceException' occurred in Payroll_Manegement.exe
I don't know what is the issue here if someone could help me that would be great.
To answer your question: the error comes from the fact that your DataTable only is instantiated but not populated before the SqlDataAdapter.Fill is fired, so when the latter tries to do something useful it can only return an exception explaining exactly what is wrong.
Your connection class pains my eyes in terms of insecure variable scope (why use public everywhere?) and non-existent connection pooling. Using a class like this opens up your application for all kinds of insecure horror. Please try to keep things simple if your application is not too complicated; the basics from the .NET Framework should already be enough for your purposes. Just do something similar to the code below (with regard to parameterization of your queries like the others suggested):
string connectionString = "server=myServer;User ID=myUser;Password=myPwd;"; // could also be internal static on class level
string theQuery = "SELECT * FROM dbo.Users WHERE Username = #userName AND Password = #password";
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
using (SqlCommand sqlCommand = new SqlCommand(theQuery, sqlConnection))
{
sqlCommand.Parameters.AddWithValue("#userName", textBox1.Text);
sqlCommand.Parameters.AddWithValue("#password", textBox2.Text);
DataTable dataTable = new DataTable();
dataTable.Load(sqlCommand.ExecuteReader());
if (dataTable.Rows > 0)
{
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
sqlDataAdapter.Fill(dataTable);
}
}
}
Alternatively, for the more complex applications you could study the Entity Framework https://learn.microsoft.com/en-us/ef/ef6/get-started first and train yourself in not re-inventing wheels. It will take some time to adapt but will really pay off.
Good luck improving your code!
I am trying to store the username and password inside a table called 'User' which is inside a service-based database.
Below is code of what i have tried.
private void Btn_register_Click(object sender, RoutedEventArgs e)
{
try
{
//Create the conection string and open the conn
SqlConnection conne = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=\\CUC-SRV-FS02\Studio-StuHome$\13mihailovs.m\Documents\IT_Unit4\IT_Unit4\ITUnit4.mdf;Integrated Security=True");
//Open the connection string
conne.Open();
//Get all the values from the text boxes etc and pass them over to the DB
string insertQuery = "insert into User(Username, Password) " +
"values(#Username, #Password)";
SqlCommand com = new SqlCommand(insertQuery, conne);
//Get values from the controls such as the text boxes and pass them over to the DB
com.Parameters.AddWithValue("#Username", txt_username.Text);
com.Parameters.AddWithValue("#Password", txt_password.Text);
//This actually executes the query with the given values above.
com.ExecuteNonQuery();
//Dispose the connection string once the data has been passed over the DB
conne.Close();
}
catch (Exception problem)
{
MessageBox.Show("error has occured");
}
}
currect way for insert into database in Ado.Net:
private readonly SqlConnection _con = new SqlConnection("Data Source=.;Initial
Catalog=dbPhoneBook;Integrated Security=True");
public string Add(string user , string pass)
{
string result = "";
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = _con;
cmd.CommandText = "insert into tbl_login(user,pass)values(#user,#pass)";
cmd.Parameters.AddWithValue("#user", user);
cmd.Parameters.AddWithValue("#pass", pass);
if (_con.State != ConnectionState.Open)
{
_con.Open();
}
cmd.ExecuteNonQuery();
result = "Ok";
cmd.Dispose();
}
catch
{
cmd.Dispose();
result = "NOk";
}
return result;
}
Also check the following
Check out the web site https://www.connectionstrings.com/ link to the database.
namespace PCJ_System
{
class DB_CONNECTION
{
public SqlConnection getConnection()
{
SqlConnection conn = null; ;
try
{
conn = new SqlConnection("data source= DESKTOP-LKEG8FM\\SQLEXPRESS;initial catalog= PCJ_DB ; Integrated Security=True;");
conn.Open();
}
catch (Exception ex)
{
MessageBox.Show("Can't Open Connection !" + ex);
}
return conn;
}
}
}
This is my forms code: public partial class Form1 : this below code is working but i typing the sqlconnection again. which should be wrong way of coding.
namespace PCJ_System
{
public partial class Form1 : Form
{
SqlConnection conn;
SqlCommand cmd;
// SqlDataReader dr;
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string str = "server = DESKTOP-LKEG8FM\\SQLEXPRESS;initial catalog= PCJ_DB ; Integrated Security=True;";/again and again i am calling the=is to every other forms is it the correct way /
SqlConnection conn = new SqlConnection(str);
// DB_CONNECTION x = new DB_CONNECTION();
conn.Open();
string GetData = "Select [FC_Rate] from Forcur where FC_TYPE ='" + comboBox1.Text + "' ";
cmd = new SqlCommand(GetData, conn);
var returnValue = cmd.ExecuteScalar();
textBox1.Text = returnValue.ToString();
conn.Close();
}
}
}
How can I call the my Dbconnection to every single function.
Please help.
Replace your Code:
string str = "server = DESKTOP-LKEG8FM\\SQLEXPRESS;initial catalog= PCJ_DB ;Integrated Security=True;";
/again and again i am calling the=is to every other forms is it the correct way /
SqlConnection conn = new SqlConnection(str);
// DB_CONNECTION x = new DB_CONNECTION();
conn.Open();
With the following:
DB_CONNECTION x = new DB_CONNECTION();
SqlConnection conn = x.getConnection();
One way that you could do to avoid repeating your code is create BaseForm and put you general codes in it then All your forms should Inherit BaseForm
public abstract class BaseForm:Form{
public SqlConnection getConnection()
{
SqlConnection conn = null; ;
try
{
conn = new SqlConnection("data source= DESKTOP-LKEG8FM\\SQLEXPRESS;initial catalog= PCJ_DB ; Integrated Security=True;");
conn.Open();
}
catch (Exception ex)
{
MessageBox.Show("Can't Open Connection !" + ex);
}
return conn;
}
}
and your Form should change like this :
public partial class Form1 : BaseForm
{
SqlCommand cmd;
// SqlDataReader dr;
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string str = "server = DESKTOP-LKEG8FM\\SQLEXPRESS;initial catalog= PCJ_DB ; Integrated Security=True;";/again and again i am calling the=is to every other forms is it the correct way /
string GetData = "Select [FC_Rate] from Forcur where FC_TYPE ='" + comboBox1.Text + "' ";
cmd = new SqlCommand(GetData, getConnection());
var returnValue = cmd.ExecuteScalar();
textBox1.Text = returnValue.ToString();
conn.Close();
}
}
I wrote this code but I do not know why this line gives error!
String sname = dr.GetString ("name");
My code:
SqlConnection cn = new SqlConnection(
"Data Source=.;Initial Catalog=logindb;Integrated Security=True");
string query1 = "select * from tbllogin";
SqlCommand cmd = new SqlCommand(query1);
SqlDataReader dr;
try
{
cn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
String sname = dr.GetString("name");
comboBox1.Items.Add(sname);
}
}
catch (Exception e)
{
// do smth about exception
}
First of all you have to check this again:
SqlConnection cn = new SqlConnection(
"Data Source=.;Initial Catalog=logindb;Integrated Security=True");
Data Source=.; This is wrong and it will give you an error.
After that you can use the code below to achieve what you want. The code below also uses using statement to dispose the connection.
using (
SqlConnection connection = new SqlConnection(strCon)) // strCon is the string containing connection string
{
SqlCommand command = new SqlCommand("select * from tbllogin", connection);
connection.Open();
DataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
comboBox1.Items.Add(reader.GetString(int index)); // index of column you want, because this method takes only int
}
}
reader.Close();
}
(Amazingly) GetString only take an index as parameter.
See MSDN
public override string GetString(int i)
With no other signatures :-(
However you could write:
String sname = dr.Item["name"].ToString();
MSDN says that SqlDataReader.GetString method accepts an int as a parameter, which is the index of the column.
What you need is this:
while (dr.Read())
{
String sname = (string)dr["name"];
comboBox1.Items.Add(sname);
}
Here's your code:
SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=logindb;Integrated Security=True");
string query1 = "select * from tbllogin"; SqlCommand cmd = new SqlCommand(query1); SqlDataReader dr;
try {
cn.Open(); dr = cmd.ExecuteReader();
while (dr.Read())
{ String sname = (string)dr["name"];
comboBox1.Items.Add(sname);
}
}
catch (Exception e) { MessageBox.Show(e.Message, "An error occurred!"); }
The catch block wasn't written correctly, you missed the (Exception e) part.
I keep getting an exception when I try to fill the adapter and i can't figure out why. Here is my code. Thank you very much in advance for any information!
public partial class MainWindow : Window
{
private OleDbConnection connection;
private OleDbCommand command;
private OleDbDataAdapter adapter;
private DataSet dataset;
public MainWindow()
{
InitializeComponent();
connection = new OleDbConnection();
command = new OleDbCommand();
adapter = new OleDbDataAdapter();
dataset = new DataSet();
connection.ConnectionString =
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/SoBeWFF.accdb;" +
"Persist Security Info=False";
command.Connection = connection;
command.CommandText = "SELECT * FROM Dishes";
adapter.SelectCommand = command;
try
{
adapter.Fill(dataset, "Dishes");
}
catch (OleDbException)
{
MessageBox.Show("Error occured while connecting to database.");
// Application.Exit();
}
}
}
Try the following connection string. (Close the MS-Access/database file if it is opened)
connection.ConnectionString =#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\SoBeWFF.accdb";