How to fix save button - c#

I wrote a code for my pleasure.
i have access data file "mdb" and i show him on gridview from gridview i select row and shown on text box.
i edit the textbox and try to press on Save button and show me error msg.
what i do wrong?
save button didnt save and show me error msg.
add pictures and my code:
Error msg
gridview+textbox
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;
namespace Center image description hereDHW
{
public partial class Form2 : Form
{
private OleDbConnection connection = new OleDbConnection();
public Form2()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\Users\RBA\Desktop\123\users1.mdb;
Persist Security Info=False;";
}
private void button9_Click(object sender, EventArgs e)
{
this.Close();
Form1 f1 = new Form1();
f1.Show();
}
private void btn_save_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into GRL1 (NoBoard,Site,Group,Kind,Unit) values ('" + txt_noboard.Text + "','" + txt_site.Text + "','" + txt_group.Text + "','" + txt_kind.Text + "','" + txt_unit.Text + "',)";
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
private void Form2_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'users1DataSet.GRL1' table. You can move, or remove it, as needed.
this.gRL1TableAdapter.Fill(this.users1DataSet.GRL1);
}
private void btn_loadGR_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from GRL1";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
private void button3_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from GRS1";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
txt_noboard.Text = row.Cells[0].Value.ToString();
txt_site.Text = row.Cells[1].Value.ToString();
txt_group.Text = row.Cells[2].Value.ToString();
txt_kind.Text = row.Cells[3].Value.ToString();
txt_unit.Text = row.Cells[4].Value.ToString();
txt_com.Text = row.Cells[5].Value.ToString();
}
}
}
}

You have a typo in your sql text. There is a comma before the close brace. But there is also an error caused by the usage of a reserved keyword in MS-Access (Group). You need to put square brackets around that name.
Finally, do not use string concatenation to build sql commands but always use parameters.
This avoid sql injection hacks and remove problem with parsing your inputs (for example if there is a single quote in your input text the whole query will fail again with a syntax error)
private void btn_save_Click(object sender, EventArgs e)
{
try
{
using(OleDbConnection connection = new OleDbConnection(....con string...))
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
// Notice how Group field is between square brackets.
// If you can I suggest to change the name of this field
string cmdText = #"insert into GRL1 (NoBoard,Site,[Group],Kind,Unit)
values (#nob, #sit, #grp, #knd, #uni)";
command.CommandText = cmdText;
// Is NoBoard an integer? If yes you should pass an integer not a string
command.Parameters.Add("#nob", OleDbType.Integer).Value = Convert.ToInt32(txt_noboard.Text);
command.Parameters.Add("#sit", OleDbType.VarWChar).Value = txt_site.Text;
command.Parameters.Add("#grp", OleDbType.VarWChar).Value = txt_group.Text;
command.Parameters.Add("#knd", OleDbType.VarWChar).Value = txt_kind.Text;
command.Parameters.Add("#uni", OleDbType.VarWChar).Value = txt_unit.Text;
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
}
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
The parameters collection is filled with the values required by your query text. Notice that I don't know exactly the datatype of your columns in the database. The parameter OleDbType should exactly match the types expected to avoid Type Mismatch exceptions
Last tip. Connections should be created, opened and closed when needed. Do not keep a global connection object. You don't get much gain in performance because ADO.NET employs a technique called Connection Pooling

Related

Inserting multiple queries in table instead of one C#

I am using winform C#,
database name "School"
my "fees" table has 2 columns,
stu_id,fees
The issue I am facing is that it adds multiple (same) entries into the database instead of single.
I have code on other forms but I don't know why is this happening here, any help would be appreciated.
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 SchoolManagementSystem
{
public partial class Fees : Form
{
public Fees()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=DRAGON\SQLEXPRESS;Initial Catalog=School;Integrated Security=True;");
con.Open();
try
{
string str = " INSERT INTO fees VALUES('" + textBox1.Text + "','" + textBox2.Text + "')";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
MessageBox.Show("Your Fees Submitted..");
this.Hide();
Home obj2 = new Home();
obj2.ShowDialog();
}
this.Close();
}
catch (SqlException excep)
{
MessageBox.Show(excep.Message);
}
con.Close();
}
private void textBox1_MouseLeave(object sender, EventArgs e)
{
textBox2.Text = "";
SqlConnection con = new SqlConnection(#"Data Source=DRAGON\SQLEXPRESS;Initial Catalog=School;Integrated Security=True;");
con.Open();
if (textBox1.Text != "")
{
try
{
string getCust = "select name,standard,medium from student where std_id=" + Convert.ToInt32(textBox1.Text) + " ;"; // saving new custmer info
SqlCommand cmd = new SqlCommand(getCust, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.Read())
{
label9.Text = dr.GetValue(0).ToString();
label6.Text = dr.GetValue(1).ToString();
label7.Text = dr.GetValue(2).ToString();
}
else
{
MessageBox.Show("Sorry '" + textBox1.Text + "' This Registration Id is Invalid, Please Insert Correct Id");
textBox1.Text = "";
textBox2.Text = "";
}
}
catch (SqlException excep)
{
MessageBox.Show(excep.Message);
}
con.Close();
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void Fees_Load(object sender, EventArgs e)
{
}
}
}
when I enter fees from front end, it adds same 2 rows into database instead of 1.
Because you're executing your INSERT statement twice:
cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
Why? Why do you even need the SqlDataReader? Just execute the INSERT once:
cmd.ExecuteNonQuery();
MessageBox.Show("Your Fees Submitted..");
If you want to confirm that a row was inserted, ExecuteNonQuery returns the number of rows affected:
var rows = cmd.ExecuteNonQuery();
if (rows != 1)
{
// handle error
}
else
{
MessageBox.Show("Your Fees Submitted..");
}
You are executing the command twice here:
cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
Why are you calling ExecuteReader when there's nothing to read? ExecuteReader is for when you execute a SELECT statement with multiple columns and/or multiple rows and you want to read the result set. For an INSERT statement, you only need to call ExecuteNonQuery... because it's not a query.

why it is not showing any error and it is also not inserting data into ms access file using C #?

I am new on c# and i am facing problem. i made two buttons, one for case another for credit card. when i click on button, my data is not inserting into ms access file.why is it not showing any error and how can i fix it ?
private void CashButton_Click(object sender, EventArgs e)
{
SaveOrder((int)PaymentTypes.Cash);
}
private void CreditCardButton_Click(object sender, EventArgs e)
{
SaveOrder((int)PaymentTypes.CreditCard);
}
private void SaveOrder(int paymentType)
{
try
{
string connstring = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand("INSERT INTO [Orders](OrderNummber,TransactionDate,ClientName,TotalAmount,PaymentType) VALUES(#OrderNummber,#TransactionDate,#ClientName,#TotalAmount,#PaymentType)",conn))
{
cmd.Parameters.AddWithValue("#OrderNummber",OrderNumberTextBox.Text);
cmd.Parameters.AddWithValue("#TransactionDate",TransactionDateDateTimePicker.Value.Date);
cmd.Parameters.AddWithValue("#ClientName",ClientNameTextBox.Text);
cmd.Parameters.AddWithValue("#TotalAmount",Convert.ToDecimal(TotalAmountTextBox.Text));
cmd.Parameters.AddWithValue("#PaymentType", paymentType);
cmd.ExecuteNonQuery();
}
foreach (DataGridViewRow row in CartDataGridView.Rows)
{
using (OleDbCommand cmd = new OleDbCommand("INSERT INTO [OrdersItems](OrderNumber,Quantity,UnitPrice,TotalPrice) VALUES(#OrderNumber,#Quantity,#UnitPrice,#TotalPrice)", conn))
{
cmd.Parameters.AddWithValue("#OrderNumber", OrderNumberTextBox.Text);
cmd.Parameters.AddWithValue("#Quantity", Convert.ToInt16(row.Cells["Quantity"].Value));
cmd.Parameters.AddWithValue("#UnitPrice",Convert.ToDecimal(row.Cells["UnitPrice"].Value));
cmd.Parameters.AddWithValue("#TotalPrice", Convert.ToDecimal(row.Cells["TotalPrice"].Value));
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("Order is processed successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
}
}
Do it like this.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind.mdb";
string fstName = textBox1.Text.Trim();
string lstName = textBox2.Text.Trim();
string adres = textBox3.Text.Trim();
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO MyExcelTable (FName, LName, Address) VALUES (#FName, #LName, #Address)")
{
Connection = conn
};
conn.Open();
if (conn.State == ConnectionState.Open)
{
// you should always use parameterized queries to avoid SQL Injection
cmd.Parameters.Add("#FName", OleDbType.VarChar).Value = fstName;
cmd.Parameters.Add("#LName", OleDbType.VarChar).Value = lstName;
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = adres;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show(#"Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source + "\n" + ex.Message);
conn.Close();
}
}
else
{
MessageBox.Show(#"Connection Failed");
}
}
}
}
This will definitely work. Just change the connection string and the variables to suit your needs.

How do i add textbox values to Access database?

I want to add textbox values to relevant columns in access database, the connection has been established but when i click the submit button the values are not added.
here is the code i tried, any help is appreciated
protected void Button1_Click(object sender, EventArgs e)
{
string EmailAddress = TextBox1.Text;
string UserName = TextBox2.Text;
string Password = TextBox3.Text;
try
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\Bheki Ndhlovu\source\WebSites\WebSite8\App_Data\UserDatabase.accdb; Persist Security Info = False;");
OleDbCommand cmd = new OleDbCommand();
cmd = new OleDbCommand("INSERT INTO User(EmailAddress, UserName, Password) VALUES(#EmailAddress, #UserName, #Password)");
con.Open();
if (con.State == ConnectionState.Open)
{
TextBox1.Text = "sssss";
cmd.Parameters.Add("#EmailAddress", OleDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.Add("#UserName", OleDbType.VarChar).Value = TextBox2.Text;
cmd.Parameters.Add("#Password", OleDbType.VarChar).Value = TextBox3.Text;
cmd.ExecuteNonQuery();
con.Close();
}
}
catch (Exception error)
{
//Show error message as error.Message
}
}
Try adding connection string with OleDbCommand.
cmd = new OleDbCommand("INSERT INTO User(EmailAddress, UserName, Password) VALUES(#EmailAddress, #UserName, #Password)",con);
Here is an example were all data operations reside in a class. If the add new record is successful the new primary key is returned. On failure you can query the exception that raised the problem for failure.
using System;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
namespace MS_AccessAddNewRecord_cs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void addRecordButton_Click(object sender, EventArgs e)
{
var ops = new Operations();
var newId = 0;
if (ops.AddNewRow(companyTextBox.Text, contactNameTextBox.Text, contactTitleTextBox.Text, ref newId))
{
newIdentifierTextBox.Text = $"{newId}";
}
else
{
MessageBox.Show($"{ops.Exception.Message}");
}
}
}
/// <summary>
/// This class should be in a separate class file, I placed it here for easy of learning
/// </summary>
public class Operations
{
private OleDbConnectionStringBuilder Builder = new OleDbConnectionStringBuilder
{
Provider = "Microsoft.ACE.OLEDB.12.0",
DataSource = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database1.accdb")
};
private Exception mExceptiom;
public Exception Exception
{
get
{
return mExceptiom;
}
}
/// <summary>
/// Add a new record, upon success return the new primary key for the record in pIdentifier parameter
/// </summary>
/// <param name="pName"></param>
/// <param name="pContactName"></param>
/// <param name="pContactTitle"></param>
/// <param name="pIdentfier"></param>
/// <returns></returns>
public bool AddNewRow(string pName, string pContactName, string pContactTitle, ref int pIdentfier)
{
bool Success = true;
try
{
using (OleDbConnection cn = new OleDbConnection { ConnectionString = Builder.ConnectionString })
{
using (OleDbCommand cmd = new OleDbCommand { Connection = cn })
{
cmd.CommandText = "INSERT INTO Customers (CompanyName,ContactName, ContactTitle) " +
"Values(#CompanyName,#ContactName, #ContactTitle)";
cmd.Parameters.AddWithValue("#CompanyName", pName);
cmd.Parameters.AddWithValue("#ContactName", pContactName);
cmd.Parameters.AddWithValue("#ContactTitle", pContactTitle);
cn.Open();
int Affected = cmd.ExecuteNonQuery();
if (Affected == 1)
{
cmd.CommandText = "Select ##Identity";
pIdentfier = Convert.ToInt32(cmd.ExecuteScalar());
}
}
}
}
catch (Exception ex)
{
Success = false;
mExceptiom = ex;
}
return Success;
}
}
}
Perhaps in the Page_Load method you do not have a if(!isPostback) and so the value of the TextBoxes are getting reset on a postback before the Button1_Click method is executed.
If EmptyWaterHole's answer is not the problem, is it erroring out on the connection?
Be sure 'VarChar' is the correct data type for each of the fields.
Also, be sure the values do not exceed the size (ie: if you set the field to only allow up to 25 characters and your value is over 25 characters, the value will not be added).
In addition, if you are not allowing nulls and one of the values exceeds the limit, the whole record will not be added.
Mr. Hungry. Try it like this.
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.OleDb;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn;
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\your_path_here\Northwind.mdb");
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"INSERT INTO MyExcelTable([Fname], [Lname], [Address])VALUES('" + textBox1.Text + "', '" + textBox2.Text + "','" + textBox3.Text + "')";
cmd.ExecuteNonQuery();
conn.Close();
}
public OleDbConnection myCon { get; set; }
private void button2_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind.mdb";
string fstName = textBox1.Text.Trim();
string lstName = textBox2.Text.Trim();
string adres = textBox3.Text.Trim();
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO MyExcelTable (FName, LName, Address) VALUES (#FName, #LName, #Address)")
{
Connection = conn
};
conn.Open();
if (conn.State == ConnectionState.Open)
{
// you should always use parameterized queries to avoid SQL Injection
cmd.Parameters.Add("#FName", OleDbType.VarChar).Value = fstName;
cmd.Parameters.Add("#LName", OleDbType.VarChar).Value = lstName;
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = adres;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show(#"Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source + "\n" + ex.Message);
conn.Close();
}
}
else
{
MessageBox.Show(#"Connection Failed");
}
}
}
}
try this it will work if you are using access as your database
try
{
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO REPORT (patientName,tel,hostel,id no,department,diagnose,gender) values(#patientName,#tel,#hostel,#id no,#department,#diagnose,#gender)";
connection.Open();
command.Parameters.AddWithValue("#patientName", textBox1.Text);
command.Parameters.AddWithValue("#tel", textBox2.Text);
command.Parameters.AddWithValue("#hostel", textBox3.Text);
command.Parameters.AddWithValue("#id no", textBox4.Text);
command.Parameters.AddWithValue("#department", textBox5.Text);
command.Parameters.AddWithValue("#diagnose", richTextBox1.Text);
command.Parameters.AddWithValue("#gender", textBox6.Text);
command.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Patient record Have been save successfully....");
}
catch (Exception ex)
{
MessageBox.Show("error" + ex);
}

Error- Connection String property has not been initialized (C# Database)?

Error:
The error says:- The ConnectionString Property has not been
initialized at system.data.OledbOledConnection.PermissionDemand().
I am unable to figure out the error. Can someone explain what does it mean and how to solve it?
C# 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.OleDb;//microsoft database
namespace AccessLoginApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\admin\Documents\Book Database.accdb;
Persist Security Info=False;";
}
catch (Exception ex)
{
MessageBox.Show("Error"+ ex);
}
}
private void button1_Click(object sender, EventArgs e)
{
try{
OleDbConnection connection = new OleDbConnection();
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = " Insert into Book Name(Book Name,Book Number,Publisher) values('" + bookName.Text + "','" + bookNumber.Text + "','" + publisher.Text + "')";
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
}
}
The variable connection in the form load and the button1_Click event are different instance of the class OleDbConnection(obviously they are different) and you have not initialized the connection variable with connection string in the button1_Click event(It causing the error as well). If you do that means your code will works just fine, If you replace the concatenated queries with Parameterized queries means your code will works great. And the introduction of using statements will makes your code perfect. You can try the following:
string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\admin\Documents\Book Database.accdb;Persist Security Info=False;";
// This will be the connection string
private void Form1_Load(object sender, EventArgs e)
{
// Need not to do anything regarding connection
// some other statements if needed
}
private void button1_Click(object sender, EventArgs e)
{
try
{
using (OleDbConnection connection = new OleDbConnection(conString)) // Create and initialize connection object
{
connection.Open();
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = connection;
command.CommandText = " Insert into Book(Book_Name,Book_Number,Publisher) values(#BookName,#BookNumber,#Publisher)";
command.Parameters.Add("#BookName", OleDbType.VarChar).Value = bookName.Text;
command.Parameters.Add("#BookNumber", OleDbType.Integer).Value = bookNumber.Text;
command.Parameters.Add("#Publisher", OleDbType.VarChar).Value = publisher.Text;
command.ExecuteNonQuery();
}
}
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}

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

Categories