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";
Related
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'm trying to fill a datagridview with SQL Server table data and I get an error:
ExecuteReader: Connection property has not been initialized.
How do I fix this ?
private void BlackListLoad()
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
BindingSource bs = new BindingSource();
var table = dt;
var connection =
#"Data Source=someone-someone\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
using (var con = new SqlConnection { ConnectionString = connection })
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
try
{
cmd.CommandText = #"SELECT * FROM [dbo].[Blacklist1]";
table.Load(cmd.ExecuteReader());
bs.DataSource = table;
ListGrid.ReadOnly = true;
ListGrid.DataSource = bs;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message + " sql query error.");
}
}
}
You haven't given your SqlCommand a connection! As it states you need to do this. You can fix this by doing:
cmd.Connection = con; just before you execute the reader.
Read here for more information: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.connection(v=vs.110).aspx
It also looks like you're not opening your connection, which can be fixed with:
con.Open();
With a new connection object, you do not need to check whether it's open, because it won't be.
Try it this way.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Authors";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Authors_table");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
}
}
}
This is what I have so far:
static void Main(string[] args)
{
DataTable t = new DataTable();
string connetionString = null;
SqlConnection cnn ;
connetionString = "Data Source=local.url;Initial Catalog=databasename;User ID=username;Password=password";
cnn = new SqlConnection(connetionString);
string sql = "SELECT * FROM shiplabels";
SqlDataAdapter a = new SqlDataAdapter(sql, cnn);
try
{
cnn.Open();
a.Fill(t);
cnn.Close();
}
catch (Exception ex)
{
Console.WriteLine ("Can not open connection ! ");
}
}
I want to connect to this Microsoft DB and pull data from it. I am having trouble just getting this to work! When I use this code datatable t has 0 rows where it should come back with a few hundred. I'm clearly missing something simple here?
DataTable dt = new DataTable();
SqlDataAdapter sqlAdtp = new SqlDataAdapter();
string connectionString = "Data Source=local.url;Initial Catalog=databasename;User ID=username;Password=password";
string sql = "SELECT * FROM shiplabels";
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.CommandType = CommandType.Text;
try
{
sqlAdtp.SelectCommand = cmd;
sqlAdtp.Fill(dt);
}
catch (Exception ex)
{
}
}
}
First, you don't need to open the connection when using SqlDataAdapter.
Also, you forgot the CommandType.
This should work fine for you.
using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection sqlCnn ;
SqlCommand sqlCmd ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Select * from product";
sqlCnn = new SqlConnection(connetionString);
try
{
sqlCnn.Open();
sqlCmd = new SqlCommand(sql, sqlCnn);
adapter.SelectCommand = sqlCmd;
adapter.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]);
}
adapter.Dispose();
sqlCmd.Dispose();
sqlCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
I am new in C-Sharp, i am trying to access my Database from C-Sharp, i have written the following code, and i dont know what to write next to view data. I have searched this on net but didnt get much. Kindly tell me this in easy code.
string connection = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Database3.accdb";
OleDbConnection conn = new OleDbConnection(connection);
conn.Open();
OleDbCommand cmd = new OleDbCommand("Select * from score", conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.SelectCommand = cmd;
Refer following code:
string strProvider = "#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Database3.accdb";
string strSql = "Select * from score";
OleDbConnection con = new OleDbConnection(strProvider);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable scores = new DataTable();
da.Fill(scores);
dataGridView1.DataSource = scores;
Hope its helpful.
Try this
try
{
Dataset myDataSet=new Dataset();
string connection = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Database3.accdb";
OleDbCommand cmd = new OleDbCommand("Select * from score", conn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(cmd );
connection .Open();
myDataAdapter.Fill(myDataSet,"TableName");
}
catch (Exception ex)
{
Console.WriteLine("Error: Failed to retrieve the required data from the DataBase.\n{0}", ex.Message);
return;
}
finally
{
connection .Close();
}
Remember for good coding practice ,always connection should be open in Try Block
and closed in Finally Block
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.