SQL will only search inside of program folder - c#

this same code has worked for several other programs, however i can not get it to function with this program for some reason. what is happening is i select a file location on my desktop to read from, but the program keeps trying to open the file from inside the program files of where i have this program saved.
MessageBox.Show(PATHTEXTBOX.Text);
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath;
string query = "select * from Vendors";
OleDbConnection connect = new OleDbConnection(connString);
OleDbCommand command = new OleDbCommand(query, connect);
connect.Open();
OleDbDataReader reader = command.ExecuteReader();
DataTable dataTable = new DataTable();
dataTable.Load(reader);
dataGridView1.DataSource = dataTable.DefaultView;
connect.Close();

Querying the database using the "SqlDataAdapter" object was successful. I made a case to reproduce your problem and realized the query to the database.
UI page:
Vendors table data:
Test Results:
Code logic:
Query the database by clicking the test button.
Bind the DataGridView control by using code.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connStr = #"Data Source=(localdb)\ProjectModels;Initial Catalog=Test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
//Create an instance of SqlConnection
SqlConnection conn = null;
try
{
conn = new SqlConnection(connStr);
//open database
conn.Open();
string sql = "select * from Vendors";
//Create an object of the SqlDataAdapter class
SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
//Create an object of the DataSet class
DataSet ds = new DataSet();
//Use the SqlDataAdapter object sda to fill the new lookup results into the DataSet object ds
sda.Fill(ds);
//Set the DataSource property of the table control
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show("An error occurred!" + ex.Message);
}
finally
{
if (conn != null)
{
//Close the database connection
conn.Close();
}
}
}
}
It may be helpful to check your database connection string. Hope that helps you.

Related

update command C# DataGridView to SQL

I'm attempting to update a SQL table from C# project datagridview "Work_Table". However when I attempt to make the update I get this error
"Update unable to find TableMapping ['Work_Table'] or DataTable 'Work_Table'"
Any ideas?
Here is my code below:
try
{
using (SqlConnection conn = new SqlConnection(connString))
{
string query = #"Select * from person.addresstype";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter dAdapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dAdapter.Update(ds, "Work_Table");
MessageBox.Show("Saved");
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
You need to retrieve the DataTable from the .DataSource property of the grid. This will have the information on what was added, updated and deleted.
You can skip the command and pass the select string and connection string directly to the DataAdapter constructor.
Create a CommandBuilder to provide the Insert, Update and Delete text for the DataAdapter.Update. Pass the DataAdapter to the constructor of the CommandBuilder.
private string connString = "Your connection string";
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)dataGridView1.DataSource;
try
{
using (SqlDataAdapter dAdapter = new SqlDataAdapter("Select * from person.addresstype", connString))
using (SqlCommandBuilder cb = new SqlCommandBuilder(dAdapter))
{
dAdapter.Update(dt);
}
MessageBox.Show("Saved");
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
}

Transfer data of a table from one database, to the same table of another database, using C# dataAdapter.Fill() and dataAdapter.Update()

I need to transfer the table's content to the same table located in another database, and I write this simple code using the C# dataAdapter.Fill() and dataAdapter.Update(), but it's seems not working like I supposed.
SqlConnection sqlConnection = new SqlConnection(strSqlConnectionString);
SqlConnection sqlConnection2 = new SqlConnection(strSqlConnectionString2);
sqlConnection.Open();
sqlConnection2.Open();
DataSet CustomerDataSet = new DataSet();
SqlDataAdapter sqlDA;
SqlDataAdapter sql2DA;
SqlCommandBuilder sqlCmdBuilder;
SqlCommandBuilder sqlCmdBuilder2;
sqlDA = new SqlDataAdapter("SELECT * FROM Articolo;", sqlConnection);
sqlDA2 = new SqlDataAdapter("SELECT * FROM Articolo;", sqlConnection2);
sqlCmdBuilder = new SqlCommandBuilder(sqlDA);
sqlCmdBuilder2 = new SqlCommandBuilder(sqlDA2);
sqlDA.Fill(CustomerDataSet, "Articolo");
sqlDA2.Fill(CustomerDataSet, "Articolo");
sqlDA2.Update(CustomerDataSet, "Articolo");`
What I want to do is to have the second db(string connection: strSqlConnectionString2) with updated data, taken from the first db, exploiting the functionality of dataAdapter.Fill() + dataAdapter.Update().
Is this possible? And can I do the same things but with Access db as a second db?
Can you try it this way?
using System;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
string connetionString;
OleDbConnection connection;
OleDbDataAdapter oledbAdapter;
OleDbCommandBuilder oledbCmdBuilder;
DataSet ds = new DataSet();
DataSet changes;
int i;
string Sql;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";
connection = new OleDbConnection(connetionString);
Sql = "select * from tblUsers";
try
{
connection.Open();
oledbAdapter = new OleDbDataAdapter(Sql, connection);
oledbAdapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
oledbCmdBuilder = new OleDbCommandBuilder(oledbAdapter);
changes = ds.GetChanges();
if (changes != null)
{
oledbAdapter.Update(ds.Tables[0]);
}
ds.AcceptChanges();
MessageBox.Show("Save changes");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

Export to Excel From 2 DataGridView

I have Form like this
And I have a Class Connect to connect to my database. Here is the code:
class Connect
{
SqlConnection con;
public Connect()
{
String connectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=" + Application.StartupPath + #"\Database1.mdf;Integrated Security=True;User Instance=True";
con = new SqlConnection(connectionString);
}
public DataTable executeSelect(String query)
{
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
adapter.Fill(dt);
con.Close();
return dt;
}
public void execute(String query)
{
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
}
}
I want to export to Excel from these DataGridView. In Excel file, I want the data position in rows and columns like this(for example): Data from these DataGridView are got from two Tables in Database.
How to code this one? I'm already confused. Thank you before
This is already resolved here and here. Try it and if you still can't, ask a question, there's a difference between asking for help and asking for code

How I Reload Datagridview data while insert or update data in .net form application and database is in access database?

I have a desktop application project. In entry page a datagridview shows the existing items in database. Now when I entry new Item I want to insert it directly in datagridview. That mean I want to reload/refresh datagridview. My database is in MS Access.
private DataTable GetData()
{
DataTable dt = new DataTable();
//using (SqlConnection con = new SqlConnection(conn))
using (OleDbConnection con=new OleDbConnection(conn))
{
OleDbCommand cmd = new OleDbCommand("Select ID,Name from GroupDetails where comID='" + label1.Text + "'", con);
//SqlCommand cmd = new SqlCommand("Select ID,Name from GroupDetails where comID='" + label1.Text + "'", con);
con.Open();
//SqlDataAdapter ad = new SqlDataAdapter(cmd);
OleDbDataAdapter ad = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
ad.Fill(ds);
dt = ds.Tables[0];
return dt;
}
}
private void btnSave_Click(object sender, EventArgs e)
{
//SqlConnection con = new SqlConnection(conn);
OleDbConnection con = new OleDbConnection(conn);
con.Open();
//SqlCommand cmd;
try
{
string query = "insert into GroupDetails (ID,Name) values(#ID,#Name)";
// cmd = new SqlCommand(query,con);
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.AddWithValue("#ID",txtID.Text);
cmd.Parameters.AddWithValue("#Name",txtName.Text);
int i = cmd.ExecuteNonQuery();
if(i!=0)
{
dataGridGroup.DataSource = GetData();
}
}
catch (Exception ex)
{
ex.Message.ToString();
}
finally
{
con.Close();
}
}
[Note: When I use sql database then it works fine.]
The dbDataAdapterClass (the one that OleDbDataAdapter inherits from) has a SelectCommand, UpdateCommand and InsertCommand. These are responsible for select, update, and insert when you explicit call any of the methods (for example update ;) ). Since in your code, you never provide the command that explain how to do the update, the dataadapter doesn't know how to do it.
so fulfill the requirements, adding an update command to the adapter.
dataadapter = new OleDbDataAdapter(sql, connection);
Add below code after above line, OleDbCommandBuilder will generate commands for you.
OleDbCommandBuilder cb = new OleDbCommandBuilder(dataadapter);
This tutorial should help you out.

Saving Dataset to database

I am trying to save a dataset to a database. I got a dataset from another class, Now changes will be made on the form by a user on a datagridview, then the changed Dataset needs to be saved in the database.
I am using the below code; Its not generating any errors, but the data is not being saved in the database.
public class myForm
{
DataSet myDataSet = new DataSet();
public void PouplateGridView()
{
try
{
SqlService sql = new SqlService(connectionString); // Valid Connection String, No Errors
myDataSet = sql.ExecuteSqlDataSet("SELECT * FROM Qualification"); // Returns a DataSet
myDataGridView.DataSource = myDataSet.Tables[0];
myDataGridView.AutoGenerateColumns = true;
myDataGridView.AutoResizeColumns();
}
catch (Exception ex)
{
MessageBox.Show(ex.InnerException + Environment.NewLine + ex.Message, "Error");
this.Close();
}
}
private void btnSave_Click(object sender, EventArgs e)
{
//myDataSet.AcceptChanges();EDIT:Don't know why, but this line wasn't letting the chane in db happen.
SqlCommand sc = new SqlCommand("SELECT * FROM Qualification", sql.Connection); //ADDED after Replies
SqlDataAdapter da = new SqlDataAdapter();
SqlCommandBuilder scb = new SqlCommandBuilder(da); //ADDED after replies
da.Update(myDataSet.Tables[0]);
}
}
public class mySqlService
{
public DataSet ExecuteSqlDataSet(string sql)
{
SqlCommand cmd = new SqlCommand();
this.Connect();
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
cmd.CommandTimeout = this.CommandTimeout;
cmd.Connection = _connection;
if (_transaction != null) cmd.Transaction = _transaction;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
da.Fill(ds);
da.Dispose();
cmd.Dispose();
if (this.AutoCloseConnection) this.Disconnect();
return ds;
}
}
What am I doing wrong here? There are ways on the web to save the dataset, if the datset is created, edited and saved in the same class etc., BUT I would like to have the select dataset method in the mySqlService class. How should I, now can save the dataset to the database?
EDIT:
I have commented the three lines that were required to make the code work. The code works now.
In order to run Update method of SqlDataAdapter you must have to configure InsertCommand, DeleteCommand and UpdateCommand properties along with SelectCommand of SqlDataAdapter or construct the SqlCommandBuilder object which configure these commands implicitly.
Hey try following this tutorial here http://support.microsoft.com/kb/308507 first and then adapt it to your needs.

Categories

Resources