ExecuteNonQuery: Connection property has not been initialized (access database) - c#

what's wrong with my code?I just want to add data into access database but it show ExecuteNonQuery:
Connection property has not been initialized.
It's pretty weird because in other project code similar to this works just fine.
OleDbCommand command = new OleDbCommand();
OleDbConnection connect = new OleDbConnection();
OleDbDataReader reader;
public Absen()
{
InitializeComponent();
}
MainForm form_utama;
private void Absen_Load(object sender, EventArgs e)
{
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Visual Studio Project\Minor baru - back up\Minor baru\Absensi.accdb;Persist Security Info=False;";
}
private void button1_Click(object sender, EventArgs e)
{
if (idkaryawantxt.Text != "")
{
string q = "insert into tableAbsensi (ID,ID_divisi,Waktu,Tanggal) values ('" + idkaryawantxt.Text.ToString() + "','" + iddivisitxt.Text.ToString() + "','" + (DateTime.Now.ToString("hh:mm :")) + "','" + (DateTime.Now.ToString("MM-dd-yyyy")) + "')";
dosomething(q);
}
}
private void dosomething(String q)
{
try
{
connect.Open();
command.CommandText = q;
command.ExecuteNonQuery();
connect.Close();
}
catch (Exception e)
{
connect.Close();
MessageBox.Show(e.Message.ToString());
}
}

You didn't set your Command's Connection property
command.Connection = connect;
Before execute your command you should set it as the error said

Related

how to fix "An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll"

when I run the code it runs. the login and register form appears. But after entering details when clicking on the register button it shows the error
"An unhandled exception of type 'system.data.sqlclient.sqlexception' occurred in system.data.dll"
and highlight the con and con.open()
the coding is given below
namespace MovieBookingSystemCSharp
{
public partial class Register : Form
{
public Register()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection **con** = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\dell\Documents\Visual Studio 2015\Projects\MovieBookingSystemCSharp\MovieBookingSystemCSharp\movie.mdf;Integrated Security=True");
**con.Open();**
try
{
string str = "INSERT INTO user1(name,mobile,email,pass) VALUES('" + textBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "'); ";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
//-------------------------------------------//
string str1 = "select max(Id) from user1;";
SqlCommand cmd1 = new SqlCommand(str1, con);
SqlDataReader dr = cmd1.ExecuteReader();
if (dr.Read())
{
MessageBox.Show("New User Registered Successfully..");
Form1 obj = new Form1();
obj.ShowDialog();
this.Hide();
}
}
catch (SqlException excep)
{
MessageBox.Show(excep.Message);
}
con.Close();
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
}
}
}
Try to modify the "AttachDbFilename" property without spaces in the path like shown below.
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\testuser1\Documents\vs2015\Projects\MovieBookingSystemCSharp\MovieBookingSystemCSharp\movie.mdf;Integrated Security=True");

Connecting to MS Access

I am trying to connect my small C# program which has only one Insert Query with MS Access database. I followed up some codes in Internet but i couldn't get it right.
public partial class Form1 : Form
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\HP\Desktop\victoriy\Database1.accdb);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbCommand cmd = con.CreateCommand();
con.Open();
cmd.CommandText = "Insert into Na(FirstName,LastName)Values('" + textBox1.Text + "','" + textBox2.Text + "')";
cmd.Connection = con;
cmd.ExecuteNonQuery();
MessageBox.Show("Record Submitted", "Congrats");
con.Close();
}
}
}

C# - Connecting to an Access MDB file using WPF (The ConnectionString Property has not been initialized)

Let me start by saying I've only been coding C# for about 3-4 month.
I am trying to get a basic understanding of how databases are accessed within Visual studio so that I can both insert, update and delete data. I have tried various different tests and I think I've come to the conclusion that there's something about WPF's that OleDb doesn't quite like. I have created 2 identical projects, one using Windows Forms and another using WPF. The Windows Forms version of the project works absolutely fine however the WPF project does not, giving me the error
"The ConnectionString Property has not been initialized"
I have no idea how to fix this. I've been scouring the internet for the best part of 12 hours and still had absolutely no success.
Here is the original code for the WPF file. It is the same as the Windows Form code
public partial class MainWindow : Window
{
OleDbCommand cmd = new OleDbCommand();
OleDbConnection cn = new OleDbConnection();
OleDbDataReader dr;
public MainWindow()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cn.ConnectionString = #"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\MarkB\Documents\testing.mdb";
cmd.Connection = cn;
loaddata();
}
private void loaddata()
{
listBox1.Items.Clear();
listBox2.Items.Clear();
listBox3.Items.Clear();
listBox4.Items.Clear();
try
{
string q = "select * from info";
cmd.CommandText = q;
cn.Open();
dr = cmd.ExecuteReader();
if(dr.HasRows)
{
while(dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
listBox2.Items.Add(dr[1].ToString());
listBox3.Items.Add(dr[2].ToString());
listBox4.Items.Add(dr[3].ToString());
}
}
dr.Close();
cn.Close();
}
catch(Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
if(l.SelectedIndex != -1)
{
listBox1.SelectedIndex = l.SelectedIndex;
listBox2.SelectedIndex = l.SelectedIndex;
listBox3.SelectedIndex = l.SelectedIndex;
listBox4.SelectedIndex = l.SelectedIndex;
}
}
private void button1_Click(object sender, EventArgs e)
{
if ((textBox1.Text!="") && (textBox2.Text!=""))
{
string q ="insert into info (firstname,surname,address) values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text +"')";
dosomething(q);
textBox1.Text = null;
textBox2.Text = null;
textBox3.Text = null;
}
}
private void dosomething(String q)
{
try
{
cn.Open();
cmd.CommandText = q;
cmd.ExecuteNonQuery();
MessageBox.Show("Data Saved");
cn.Close();
loaddata();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
if(listBox1.SelectedIndex !=-1)
{
string q = "delete from info where id =" + listBox1.SelectedItem.ToString();
dosomething(q);
}
}
}
If anyone can help it would be greatly appreciated. I know the problem must stem from the connection aspect of the code
The error suggests that the connection is being called at some point BEFORE the connection string has been passed to it. Maybe try setting the connection string right at the top when you first instantiate the OleDbConnection object:
OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\Users\\MarkB\\Documents\\testing.mdb");
Then create a new cmd object everytime you need it (rather than once at the top):
string query = "select * from somethingorother";
OleDbCommand cmd = new OleDbCommand(query, cn);

Data still getting added in spite of TextBox validation

Well, I have a simple program that is writing to a Database. I am trying to add validation to the textbox like this,
private void textBox1_TextChanged(object sender, EventArgs e)
{
try
{
if (textBox1.Text.Length < -1)
{
MessageBox.Show("Don't Leave this field blank!");
}
}
catch
{
//todo
}
}
and My save to database code,
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server = DAFFODILS-PC\\SQLEXPRESS;Database=Library;Trusted_Connection=True;");
SqlCommand sql1 = new SqlCommand("INSERT into Book VALUES('" + textBox1.Text + "' , '" + textBox2.Text + "','" + dateTimePicker1.Value.ToShortDateString() + "')", con);
con.Open();
sql1.ExecuteNonQuery();
con.Close();
this.bookTableAdapter.Fill(this.booksDataSet.Book);
MessageBox.Show("Data Added!");
this.Close();
}
But still it is adding blank data to the database and strange thing is in the database I have not allowed null but still data is getting added. Any clues where I am wrong?
I don't see you stopping the database to add empty content. You are validating on the textbox_textchanged event which will only validate the text when someone enters the data. You need to put the validation on button1's click event like this:
private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(textBox1.Text.Trim()))
{
MessageBox.Show("Null String !!!!!!!!");
return;
}
SqlConnection con = new SqlConnection("Server = DAFFODILS-PC\\SQLEXPRESS;Database=Library;Trusted_Connection=True;");
SqlCommand sql1 = new SqlCommand("INSERT into Book VALUES('" + textBox1.Text + "' , '" + textBox2.Text + "','" + dateTimePicker1.Value.ToShortDateString() + "')", con);
con.Open();
sql1.ExecuteNonQuery();
con.Close();
this.bookTableAdapter.Fill(this.booksDataSet.Book);
MessageBox.Show("Data Added!");
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(textBox1.Text) || textBox1.Text.Trim().Length == 0)
{
//log
return;
}
SqlConnection con = new SqlConnection("Server = DAFFODILS-PC\\SQLEXPRESS;Database=Library;Trusted_Connection=True;");
SqlCommand sql1 = new SqlCommand("INSERT into Book VALUES('" + textBox1.Text + "' , '" + textBox2.Text + "','" + dateTimePicker1.Value.ToShortDateString() + "')", con);
con.Open();
sql1.ExecuteNonQuery();
con.Close();
this.bookTableAdapter.Fill(this.booksDataSet.Book);
MessageBox.Show("Data Added!");
this.Close();
}
An empty textbox.Text has zero byte length , not -1.
To be sure the textbox is not empty you should apply the Trim() to the current text
Also there is no need to catch an exception on this code.
Moreover, don't use the TextChanged event to validate the text box.
There is the Validating event for this purpose. (Remember to set CauseValidation=True for the control)
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text.Trim().Length == 0)
{
MessageBox.Show("Don't Leave this field blank!");
e.Cancel = true;
}
}
of course you could move all the validation in the code where do you update the database
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim().Length == 0)
{
MessageBox.Show("Don't Leave this field blank!");
return;
}
using(SqlConnection con = new SqlConnection(
"Server=DAFFODILS-PC\\SQLEXPRESS;Database=Library;Trusted_Connection=True;");
{
SqlCommand sql1 = new SqlCommand("INSERT into Book " +
"VALUES(#text1, #text2,#dtValue", con);
sql1.Parameters.AddWithValue("#text1", textBox1.Text);
sql1.Parameters.AddWithValue("#text2", textBox2.Text);
sql1.Parameters.AddWithValue("#dtValue", dateTimePicker1.Value.ToShortDateString());
con.Open();
sql1.ExecuteNonQuery();
this.bookTableAdapter.Fill(this.booksDataSet.Book);
MessageBox.Show("Data Added!");
this.Close();
}
}

update not working

protected void Page_Load(object sender, EventArgs e)
{
txtHidden.Text = Request.QueryString["YKcode"];
Display();
}
private void Display()
{
SqlDataReader reader;
SqlConnection con = new SqlConnection("Data Source=Localhost;Initial Catalog=MLC000022;User ID=sa;Password=Adama6DaY; Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT " + " dbo.GMYAKU.NAME, " +"FROM " +
" dbo.GMYAKU " + " WHERE " +
" (dbo.GMYAKU.YKCODE = ('" + txtHidden.Text + "'))",con) ;
con.Open();
reader = cmd.ExecuteReader();
if (reader.Read())
{
this.TextBox1.Text = reader["NAME"].ToString();
}
else
{
// 読めないので画面を初期化する
}
cmd.Connection.Close();
cmd.Dispose();
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn;
SqlCommand cmd;
connetionString = ("Data Source=Localhost;Initial Catalog=MLC000022;User ID=sa;Password=redacted; Integrated Security=True");
string strSQL ;
strSQL = "UPDATE GMYAKU SET";
strSQL += " NAME = '" + (TextBox1.Text) + "'";
strSQL += " WHERE";
strSQL += " YKCODE= '" + txtHidden.Text + "'";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
cmd = new SqlCommand(strSQL, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
// cnn.Close();
//MessageBox.Show(" ExecuteNonQuery in SqlCommand executed !!");
}
catch (Exception ex)
{
// MessageBox.Show("Can not open connection ! ");
}
Response.Redirect("Default.aspx");
}
It may be something as simple as not having the control in an update panel to refresh with the new data, but without more information/context it is impossible to tell
I think you need to check the Request.QueryString["YKcode"]; before assigning value to txthidden.text like:
protected void Page_Load(object sender, EventArgs e)
{
if(!Request.QueryString["YKcode"].equals("") && Request.QueryString["YKcode"]!=null)
{
txtHidden.Text = Request.QueryString["YKcode"];
Display();
}
}

Categories