Unable to find OLEDB provider in data source list - c#

I am trying to add an ADO.net Entity Data Model in my project. I am having accdb file. When I am trying to add this in the data source, unable to get the OLEDB provider on the list.
I am already having Microsoft Access engine provider. What I am missing on my system. Please help me. Any help would be greatly appreciated.

I am not sure if this will give you the connection as a drop down item, but these code samples show you a couple ways to connect to MS Access.
using System;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
OleDbConnection oledbCnn ;
OleDbDataAdapter oledbAdapter ;
DataSet ds = new DataSet();
string sql = null;
int i = 0;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";
sql = "Your SQL Statement Here like Select * from product";
oledbCnn = new OleDbConnection(connetionString);
try
{
oledbCnn.Open();
oledbAdapter = new OleDbDataAdapter(sql, oledbCnn);
oledbAdapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[0] + " -- " + ds.Tables[0].Rows[i].ItemArray[1]);
}
oledbAdapter.Dispose();
oledbCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
OR
using System;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
OleDbConnection oledbCnn ;
OleDbCommand oledbCmd ;
string sql = null;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";
sql = "Your SQL Statement Here like Select * from product";
oledbCnn = new OleDbConnection(connetionString);
try
{
oledbCnn.Open();
oledbCmd = new OleDbCommand(sql, oledbCnn);
OleDbDataReader oledbReader = oledbCmd.ExecuteReader();
while (oledbReader.Read ())
{
MessageBox.Show(oledbReader.GetValue(0) + " - " + oledbReader.GetValue(1) + " - " + oledbReader.GetValue(2));
}
oledbReader.Close();
oledbCmd.Dispose();
oledbCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

Related

How to fix Error in argument exception system

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 WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
pwnew.PasswordChar = '*';
pwtxt.PasswordChar = '*';
signup.Visible = false;
}
private void signupbtn_Click(object sender, EventArgs e)
{
signup.Visible = true;
}
private void button1_Click(object sender, EventArgs e)
{
if (unnew.Text != null && pwnew.Text != null)
{
try
{
Connect obj = new Connect();
obj.conn.ConnectionString = obj.locate;
obj.conn.Open();
string insertuser = "insert into userTable('" + unnew.Text + "', '" + pwnew.Text + "')";
obj.cmd.Connection = obj.conn;
obj.cmd.CommandText = insertuser;
obj.conn.Close();
MessageBox.Show("Signup has been completed");
signup.Visible = false;
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
else
{
MessageBox.Show("Error");
}
}
private void loginbtn_Click(object sender, EventArgs e)
{
if (untxt.Text != null && pwtxt.Text != null)
{
try
{
Connect obj = new Connect();
obj.conn.ConnectionString = obj.locate;
obj.conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT COUNT (*) FROM userTable where username = '" + untxt.Text + "' and password '" + pwtxt.Text + "'", obj.conn);
DataTable dt = new DataTable();
adapter.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
Form2 meLoad = new Form2();
meLoad.Visible = true;
this.Hide();
MessageBox.Show("Success");
}
else
{
MessageBox.Show("Username or Password is incorrect");
}
obj.conn.Close();
MessageBox.Show("Successfully Login");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("No empty fields are allowed");
}
{
}
}
}
}
Hi, I am completely new to c#, im having this error whenever i click sign up. It tells me to check the line 44 which is
try
{
Connect obj = new Connect();
obj.conn.ConnectionString = obj.locate;
obj.conn.Open();
string insertuser = "insert into userTable('" + unnew.Text + "', '" + pwnew.Text + "')";
obj.cmd.Connection = obj.conn;
obj.cmd.CommandText = insertuser;
obj.conn.Close();
MessageBox.Show("Signup has been completed");
signup.Visible = false;
}
Im a student, adn dont have enough background in programming, i'd appreciate someone's help. I really want to learn this programming language, and im currentlty having troubles.enter image description here Thank u so much.
I use this for Connection
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace WindowsFormsApp1
{
class Connect
{
public SqlConnection conn = new SqlConnection();
public SqlCommand cmd = new SqlCommand();
public string locate = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\hp\source\repos\WindowsFormsApp1\WindowsFormsApp1\UserDB.mdf;'Integrated Security=True";
}
}
It seems something is breaking to connect your database.
Please double check your connection string,If you need help for connection string, you may visit https://www.connectionstrings.com/
This tutorial may be helpful for you to connect database using c#.
https://www.guru99.com/c-sharp-access-database.html

Populate DataGrid from Mysql Database

First of all I'm new with C# and Visual Studio.
I followed a tutorial on how to populate DataGridView from MySql table.
I checked multiple times for copying mistakes but I didn't find any.
The code is this:
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 MySql.Data.MySqlClient;
namespace DataGridMain
{
public partial class Form1 : Form
{
private string server;
private string database;
private string uid;
private string password;
private MySqlConnection connection;
private MySqlDataAdapter mySqlDataAdapter;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
server = "localhost";
database = "elphoapp";
uid = "username";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
if (this.OpenConnection() == true)
{
mySqlDataAdapter = new MySqlDataAdapter("select * from users", connection);
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];
this.CloseConnection();
}
}
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;
default:
MessageBox.Show(ex.Message);
break;
}
return false;
}
}
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
}
}
I can't seem to find a problem and no error is displaying.
As you are new to Visual Studio, my advice is the first thing you must learn is debugging. It will save you a lot of times. In this case, put a breakpoint in your form_load and run the code step by step. You can that way see what is happening, and inspect all the variables. I'm saying this because i can't see any error in your code, so probably you are not even connecting to the database. Debugging your code you may see why
Ok i figured it out!
All i had to do was to call Form1_Load from inside the Form1() function.
Everything seems to be working fine at the moment.
Thanks, C# is full of damn surprises....

Unable to insert row into table using an Oracle Connection

I would like to know what's the problem, or your advice to connect to Oracle. I'm trying with this but when I try to insert values, it doesn't work.
I'm using the Visual Web Developer 2008 and when I add a database on Database Explorer connections, it's working. But when I try to connect via this connection string, it doesn't work. What am I missing?
I don't get an exception, so apparently it's working well. But this code apparently doesn't insert! The id column is a varchar(45). I created the table "test" just for testing purposes.
using System.Data;
using System.Data.OracleClient;
public partial class _Default : System.Web.UI.Page
{
//string oradb = "Data Source=localhost;User ID=root;Password=jesua;Unicode=True;";
String oracle = "User ID=root;Password=jesua;Unicode=True;Data Source=localhost;";
OracleConnection con = new OracleConnection();
public void Conectar() {
try
{
con.Close();
con.ConnectionString = oracle;
con.Open();
}
catch(Exception ex){
throw new Exception("No Conecto " + ex);
}
}
public void desconectar() {
// con.ConnectionString = oracle;
con.Close();
}
public void agregar() {
this.Conectar();
OracleCommand query = new OracleCommand("INSERT INTO testing (id) VALUES ('testing')");
query.ExecuteNonQuery();
desconectar();
}
protected void Button1_Click(object sender, EventArgs e)
{
try {
agregar();
}
catch(Exception ex){
Console.Write("No agrego " + ex);
}
TextBox1.Text = "Conected";
}
}
--------------------------UPDATE------------------
So,
i found the way to do that,
i hope anyone here can use this code in a future...
This code creates the connection betwen Oracle and asp.net C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Oracle.DataAccess.Client; // ODP.NET Oracle managed provider
using Oracle.DataAccess.Types;
namespace proyecto
{
public partial class WebForm1 : System.Web.UI.Page
{
public void dbconnect() {
string oradb = "Data Source=localhost;User ID={Yoir ID};Password={Your Password};";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO TESTING(id) VALUES ('valor')";
int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated == 0)
Console.Write("Record not inserted");
else
Console.Write("Success!");
conn.Dispose();
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
this.dbconnect();
}
}
}
Good Luck!
The connection string that works for me is
connectionString="Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1522))
(CONNECT_DATA=(SERVICE_NAME=XE)));User Id=system;Password=pass;"
providerName="Oracle.DataAccess.Client"/>
It seems that you are missing the Service Name and Provider Name. You can find the service name in tnsnames.ora file which will be in your installation directory. Also make sure you have installed ODP.NET for Oracle 11g correctly, added reference to the Oracle.DataAccess.dll into your project and add the Provider Name in the connection string.

Insert records in oracle database using c# odbc

I am messing around in C# trying to understand how to insert records into a database using C# ODBC. I have learned how to read in records to a DGV, but now I am getting stuck on inserting.
The quick overview of what my code is doing, its reading in 20 rows from a table into a DGV, then after that it should insert the same rows into a different table.
I am using VS 2012 and SQL Developer (Oracle).
Here is the code in my Form:
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 WindowsFormsApplication13
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
for (int rows = 0; rows < 20; rows++)
{
dataGridView1.Rows.Add(); // adding needed amount of rows
for (int cols = 0; cols < 13; cols++)
{
this.dataGridView1[cols, rows].Value = getNumberOfThreads(rows, cols);
}
}
StringBuilder sql = new StringBuilder();
sql.AppendLine("insert into chsarp_test_table");
sql.AppendLine("SELECT *");
sql.AppendLine("FROM legal_transactions");
sql.AppendLine("WHERE rownum between 1 and 25");
//using (DataTable dt = Database.GetData(sql.ToString()))
// if (dt.Rows.Count > 0)
// Database dt = new Database.SetData(sql.ToString());
Database.SetData(sql.ToString());
}
public static string getNumberOfThreads(int i, int j)
{
StringBuilder sql = new StringBuilder();
sql.AppendLine("SELECT *");
sql.AppendLine("FROM legal_transactions");
sql.AppendLine("WHERE rownum between 1 and 25");
using (DataTable dt = Database.GetData(sql.ToString()))
if (dt.Rows.Count > 0)
return dt.Rows[i][j].Equals(DBNull.Value) ? "null" : dt.Rows[i][j].ToString();
return "null";
}
}
}
Here is the code from my Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Odbc; //used for the ODBC stuff
using System.Data; // Used for public static datatable
using System.Windows.Forms;
namespace WindowsFormsApplication13
{
class Database
{
private const string connOdbc = "dsn=atlas32;uid=NAME;pwd=XXXX";
private const string cnnOLE = "provider =XXXX;User ID = NAME;password = XXXX; Data Source = XXX Properties=;Persist Security Info=False";
public static DataTable GetData(string Sql)
{
DataTable dt = new DataTable();
try
{
OdbcConnection cnn = GetConnection();
using (OdbcDataAdapter da = new OdbcDataAdapter(Sql, cnn))
{
da.SelectCommand.CommandTimeout = 0;
da.Fill(dt);
}
CloseConnection(cnn);
}
catch (Exception ex)
{
//Queries.LogErrors(ex.Message, Sql);
MessageBox.Show("Error 1");
}
return dt;
}
public static void SetData(string sql)
{
try
{
OdbcConnection cnn = GetConnection();
using (OdbcCommand cmd = new OdbcCommand(sql, cnn))
cmd.ExecuteNonQuery();
CloseConnection(cnn);
}
catch (Exception ex)
{
//Queries.LogErrors(ex.Message, sql);
MessageBox.Show("Error 2");
}
}
private static OdbcConnection GetConnection()
{
try
{
OdbcConnection cnn = new OdbcConnection() { ConnectionString = connOdbc };
cnn.Open();
return cnn;
}
catch (Exception ex)
{
//throw ex;
}
return null;
}
private static void CloseConnection(OdbcConnection Connection)
{
try
{
if (Connection.State == ConnectionState.Open)
Connection.Close();
Connection.Dispose();
}
catch (Exception ex)
{
//throw ex;
}
Connection = null;
}
}
}
I tried to step through the code and it goes down in the SetData Method on the ExecuteNonQuery. I tried to look into this but couldnt mind any information that helped me, any push in the right direction would be greatly appreciated.
I was missing the Schema on the table I was inserting on. found this out with the help of #stuartd in the comment section of the question.

trying to update values in a SQL Server database

Currently I am having issues with updating values in a SQL Server database.
I am working on a project that stores students names, dates of birth and genders in a database and is able to be edited and updated via windows forms. Browsing the data so far works fine, however when a value is changed on the form and the update button is clicked the program crashes with a
NullReferenceException was unhandled. Object reference not set to an instance of an object.
error and I am currently at a loss as to what is causing it.
Currently I have a DBConnector class which opens up the connection to the database and the dataset and passes it to the windows form which contains textboxes to show the values and navigational buttons to browse the data. (Below is the code for both the class and the windows form, I hope that can explain things better than I have).
The DBConnector.cs class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace StudentRecords
{
public class DBConnector
{
//Properties
//connection object
private System.Data.SqlClient.SqlConnection Conn;
//dataset object
private StudentsDataSet Ds1;
//dataadapter object
private System.Data.SqlClient.SqlDataAdapter Da;
//constructors
public DBConnector()
{
//call initialisation
init();
}
//Methods
//initialisation method
public void init()
{
//create the memory space for the connection object
Conn = new System.Data.SqlClient.SqlConnection();
//create the memory space for the dataset
Ds1 = new StudentsDataSet();
//set the connection string to the location of our database file
Conn.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Students.mdf;Integrated Security=True;User Instance=True";
//open the conenction
Conn.Open();
//create a query to get all the records from the table
string query = "SELECT * from Studentstbl";
//create the data adapter for the database
Da = new System.Data.SqlClient.SqlDataAdapter(query, Conn);
//use it to fill the dataset as the first parameter the second is a name for the table we use later on
Da.Fill(Ds1, "Students");
//close the connection
Conn.Close();
System.Windows.Forms.MessageBox.Show("Database connection Open", "Success");
}
public StudentsDataSet DBDataSet
{
get
{
return Ds1;
}
}
//update method
public void UpdateDB(DataSet ds, string table)
{
//create a command builder to reconnect to the database
System.Data.SqlClient.SqlCommandBuilder cb;
//set the comamnd builder to be our existing dataadapter
cb = new System.Data.SqlClient.SqlCommandBuilder(Da);
Da.Update(ds, table);
}
}
}
The studentdetails.cs Windows Form
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;
namespace StudentRecords
{
public partial class studentdetails : Form
{
DataSet StudentDataSet;
//set variables for limit
int Limit = 0;
int current = 0;
public studentdetails()
{
InitializeComponent();
}
public studentdetails(DataSet ds)
: this()
{
StudentDataSet = ds;
//set the limit of records we can navigate
Limit = StudentDataSet.Tables["Students"].Rows.Count;
NavigateRecords();
}
public studentdetails(DBConnector db) : this()
{ }
public studentdetails(DBConnector db, int sRow) : this(db)
{
current = sRow;
NavigateRecords();
//turn on editing
plEdit.Visible = true;
//set our local dataset object to point to the passed in one
DBConnection = db;
StudentDataSet = db.DBDataSet;
Limit = StudentDataSet.Tables["Students"].Rows.Count;
NavigateRecords();
}
//navigate records function to move through the records
public void NavigateRecords()
{ //create a datarow object and set it to be the first row in the dataset
DataRow dRow = StudentDataSet.Tables["Students"].Rows[current];
//set the form text to add the current record number
this.Text += " for record " + dRow.ItemArray.GetValue(0).ToString();
//fill the text boxes with the database values
txtFirstName.Text = dRow.ItemArray.GetValue(1).ToString();
txtMiddleName.Text = dRow.ItemArray.GetValue(2).ToString();
txtLastName.Text = dRow.ItemArray.GetValue(3).ToString();
txtDOB.Text = dRow.ItemArray.GetValue(4).ToString();
txtgender.Text = dRow.ItemArray.GetValue(5).ToString();
}
//update the label for the dtatbase
private void UpdateCount()
{
txtCount.Text = (current + 1).ToString() + " of " + Limit.ToString();
}
private void btn_next_Click(object sender, EventArgs e)
{
if (current != Limit - 1)
{
current++;
NavigateRecords();
}
else
{
MessageBox.Show("Last Record", "Information", 0, MessageBoxIcon.Information);
}
}
private void btn_prev_Click(object sender, EventArgs e)
{
if (current > 0)
{
current--;
NavigateRecords();
}
else
{
MessageBox.Show("First Record", "Information", 0, MessageBoxIcon.Information);
}
}
private void btn_Last_Click(object sender, EventArgs e)
{
if (current != Limit - 1)
{
current = Limit - 1;
NavigateRecords();
}
}
private void btn_first_Click(object sender, EventArgs e)
{
if (current != 0)
{
current = 0;
NavigateRecords();
}
}
public DBConnector DBConnection { get; set; }
private void btn_save_Click(object sender, EventArgs e)
{
{
//create a new datarow
DataRow dRow = StudentDataSet.Tables["Students"].NewRow();
//set the data to be the values from the text boxes
dRow[1] = txtFirstName.Text;
dRow[2] = txtMiddleName.Text;
dRow[3] = txtLastName.Text;
dRow[4] = txtDOB.Text;
dRow[5] = txtgender.Text;
//add the row to our dataset
StudentDataSet.Tables["Studentstbl"].Rows.Add(dRow);
//increase the limit as we have a new record
Limit++;
//move to the newly entered Student
current = Limit - 1;
DBConnection.UpdateDB(StudentDataSet, "Students");
MessageBox.Show("Record Saved", "Information", 0, MessageBoxIcon.Information);
NavigateRecords();
}
}
private void btn_update_Click(object sender, EventArgs e)
{
{ //get the current row
DataRow dRow = StudentDataSet.Tables["Students"].Rows[current];
//set the dataset values to those in the textboxes
dRow[1] = txtFirstName.Text;
dRow[2] = txtMiddleName.Text;
dRow[3] = txtLastName.Text;
dRow[4] = txtDOB.Text;
dRow[5] = txtgender.Text;
//call the update method in our DB connector class
DBConnection.UpdateDB(StudentDataSet, "Students");
//display a message box
MessageBox.Show("Record updated", "Information", 0, MessageBoxIcon.Information);
NavigateRecords();
}
}
}
}
The database is called Students.mdf and the table is called Studentstbl, the error is thrown on line:
DBConnection.UpdateDB(StudentDataSet, "Students");
I know its probably something stupid I have missed out but I am fairly new with C# coding so forgive me if this is the case :)
Edit: I should also point out that studentdetails is a secondary form with the main form simply containing a button which opens that form in it, it simple contains 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;
namespace Coursework3
{
public partial class Form1 : Form
{
DBConnector Students;
public Form1()
{
InitializeComponent();
//intansiate the object in memory
Students = new DBConnector();
}
private void btnstudentdetails_Click(object sender, EventArgs e)
{
new studentdetails(Students.DBDataSet).ShowDialog();
}
}
}

Categories