how to manupilate database through data grid - c#

guys here is what i have come up with I cant figure out what is the prob that is not allowing me to update the tables in the database
guys I need ur help I need to update my data base through data grid using c# as of yet all that I am able to do is that I am able to see the values that are inside the sql server that I put directly.`
string sConnectionString = "Data Source=localhost;Initial Catalog=ScratchCardSystem2;Integrated Security=True;pooling=true";
SqlConnection objConn = new SqlConnection(sConnectionString);
objConn.Open();
string query = "SELECT * FROM store_adj_note_detail_1";
SqlDataAdapter dAdapter = new SqlDataAdapter(query,objConn);
//dAdapter.SelectCommand= new SqlCommand(query, objConn);
SqlCommandBuilder cBuilder = new SqlCommandBuilder(dAdapter);
DataTable dTable = new DataTable();
//fill the DataTable
dAdapter.Fill(dTable);
dataGridView1.DataSource = dTable;
dAdapter.Update(dTable);

OleDbCommandBuilder commandBuilder = new OleDbCommandBuilder(dAdapter);
Is missing.
MSDN says:
//Without the OleDbCommandBuilder this line would fail.
dAdapter.Update(dTable);

You are missing something that binds your datagridview to your datatable. The trick here is that you need a BindingSource.
Add the following before your '//fille the datatble' line
BindingSource bindSrc = new BindingSource();
Then change your datasource of your datagridview and add a source to your bindingsource as well, like this:
dataGridView1.DataSource = bindSrc;
bindSrc.DataSource = dTable;
EDIT: I forgot to mention a tiny thing: to update, you now have to refer to the datatable that is the source of your bindingSrouce, this is how I did it:
dAdapter.Update((DataTable)bindSrc.DataSource);
Might be possible just with the regular update(dTable), but if it doesn't, this probably fixes it

So this is basically what I used for my own form. On establish connection the connection opens and it fills up my datagridview1 with the data from store_adj_note_detail_1.
Notice I never declare my bindingSource... I don't know the reason either, but I tried declaring it with the rest of them (globally) and locally, both made the code break :/
The declaration of your BindingSource happens on the Design view of your form - just drag it from the toolbox on top of your form and it will show up with an icon like FileDialogs and Menustrips do. I personally only changed the Name property and didn't add any events.
It should give you the overview of everything you need to open a connection, use the bindingsource to link your datagridview and your dataTable, and update your database.
I got this code by editing my own code that I used for an access database, but SQL databases seem to work exactly the same way, just with different entities (sqlDataAdapter and the likes instead of OleDb...).
hope this helps you!
public partial class FrmDatabaseConnection : Form
{
// Connection, Adapter, DataTable, CommandBuilder, Bindingsource and command
private SqlDataAdapter adap;
private DataTable dataTable;
private SqlCommandBuilder commandBuilder;
private string sqlCommand = "SELECT * FROM store_adj_note_detail_1";
private SqlConnection conDB = new SqlConnection();
//To open connection and fill datagridview1
private void establishConnection()
{
try
{
conDB.ConnectionString = "Data Source=localhost;Initial Catalog=ScratchCardSystem2;Integrated Security=True;pooling=true";
conDB.Open();
// Set adapter, commandbuilder, datatable and bindingsource
adap = new SqlDataAdapter(sqlCommand, conDB.ConnectionString);
commandBuilder = new SqlCommandBuilder(adap);
bindSrc = new BindingSource();
dataTable = new DataTable();
// Fill it!
adap.Fill(dataTable);
dataGridView1.DataSource = bindSrc;
bindSrc.DataSource = dataTable;
}
catch (Exception ex)
{
MessageBox.Show("Unable to Open database, " + ex.Message,);
conDB.Close();
}
}
private bool saveToDatabase()
{
try
{
adap.Update((DataTable)bindSrc.DataSource);
}
catch (Exception ex)
{
MessageBox.Show("Unable to Update database, " + ex.Message);
return false;
}
}
}

Related

c# get datasource of a datagridview from another source

I have 2 form in my application Form1 and summary. I have a button in form1 onclick I will choose a mdb file then it gets connected to mdb. I have a datagridview in summary.
What I need is once I connect the mdb file I need to update the data (in other words set datagrid.DataSource = ds from Form1) so that the data from mdb shows on datagridview of summary Form
Before selecting my question as duplicate or -1 plzz make clear that database will be connected in form1 which needs to be show in summary form. I had tried all the ways shown in google but no result.
Your help will be appreciated.
got it make another constructor in summary form that have paramater like that
public summary(dataset ds){
initializecomponent();// there
// here bind the DataSet with grid of summary
}
call from form1
summary obj = new summary (ds);
obj.show();
I think you're talking about changing the connection string, like:
private SqlConnection getConn(string Initial_Catalog_Name_Of_Database)
{
return new SqlConnection(#"Data Source=DESKTOP-JHHHN0A\MLSQLSRVR16;Initial Catalog="+Initial_Catalog_Name_Of_Database+";Integrated Security=True;Connection Timeout=9600");
}
Then
private void non_Query(string sql)
{
using (SqlConnection conn = getConn())
{
conn.Open();
using (SqlCommand com = conn.CreateCommand())
{
com.CommandTimeout = 900;
com.CommandText = sql;
com.ExecuteNonQuery();
}
conn.Close();
}
}
If that's not your question, please post your code and be more specific about what you need.
On the Summary Form Load, Query DB and populate your DataGridView.
Use the below sample code on your Form Load.
string connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=your .mdb file;";
string sql = "SELECT * FROM Authors";
OleDbConnection connection = new OleDbConnection(connetionString);
OleDbDataAdapter dataadapter = new OleDbDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Authors_table");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";

How to compose proper insert/update/delete commands to update linked tables in source access database?

I have to use MS Access.
I have database with this structure (don't mind strange names - it barely translated for this question):
My program display one of this tables (in WinForms). User can change data in it. To send changed data I use button.
Here is problem. If I use OleDbCommandBuilder to generate commands I get error after pressing save button (if something was changed in table).
So, if I change something in desease table: DataTable "table" does not include DataColumn "patient ID" for this SourceColumn "patient ID" (error text is translated so may look a bit different).
If I change something in visits table: syntax error INSERT INTO. And so on about UPDATE and DELETE.
Looks like I have to compose commands manually. But I don't get how to do it. MSDN example don't really help.
So, please, help me to compose right commands for tables "visits" and "desease". Or at least discribe how to compose it.
In case if something is not clear without code of my form:
protected string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db.mdb";
protected OleDbConnection connection = new OleDbConnection();
protected OleDbDataAdapter adapter;
protected OleDbCommandBuilder cBuilder;
DataSet dataSet;
public Form1() {
InitializeComponent();
connection.ConnectionString = conStr;
adapter = new OleDbDataAdapter("SELECT * FROM TABLE_NAME", connection);
dataSet = new DataSet();
cBuilder = new OleDbCommandBuilder(adapter);
adapter.Fill(dataSet);
connection.Open();
adapter.UpdateCommand = cBuilder.GetUpdateCommand(true);
adapter.InsertCommand = cBuilder.GetInsertCommand(true);
adapter.DeleteCommand = cBuilder.GetDeleteCommand(true);
connection.Close();
}
private void saveButton_Click(object sender, EventArgs e) {
adapter.Update(dataSet); //this method send data to database and return error
}
Guess, load code is not needed.
This idea is probably mistake. Better to look for some alternative for MS Access.

Update the datatable without using DataAdapter.Fill 2 times

I am writing a program to manage a office. (Getting rid of Excels XD).
I have a DAL class with the following variables:
private MySqlConnection connection;
private DataSet ds;
private Hashtable adapters;
There is this method:
public bool AddTable(string tableName, string sqlStat)
{
if (!ds.Tables.Contains(tableName))
{
MySqlDataAdapter adapter = new MySqlDataAdapter(sqlStat, connection);
MySqlCommandBuilder builder = new MySqlCommandBuilder(adapter);
adapter.InsertCommand = builder.GetInsertCommand();
adapter.UpdateCommand = builder.GetUpdateCommand();
adapter.DeleteCommand = builder.GetDeleteCommand();
adapter.Fill(ds, tableName);
adapters.Add(tableName, adapter);
return true;
}
return false;
}
The program will be connected to a server with MySQL database.
I need to make sure that when one client changes something in the database another client will see the new data, but this is not happening.
You need to read up on optimistic concurrency, which helps solve the problem of multiple users reading and updating the same data at the same time.
I suggest you start here:
http://msdn.microsoft.com/en-us/library/aa0416cz%28v=vs.110%29.aspx
http://www.codeproject.com/Articles/114262/6-ways-of-doing-locking-in-NET-Pessimistic-and-opt

C# Winforms control - DataGridView - Update Database

The programs I am using are WAMP server (and its mysql feature in particular) and MS Visual Studio 2010 and I am programming in C#
Basically, here is what I need and can currently do with my application.
I have several datagridview's throughout the project and the first is simple, it loads all data from a specific table in the database at the push of a button. I have another form which I can insert records and have somehow managed to make a delete function which asks the user for 2 fields (first name and last name) and then it places these into a query and carries out the command.
What do I need to do?
I need to be able to implement some way for the form to update the database. I have chosen to do this through a datagridview control so the user can see what they are editting whilst they edit it.
I have the following code which I have tried to update the database based on the data in the datagridview control.
string connString = "server=localhost;User Id=root;database=collegelist;";
MySqlConnection conn = new MySqlConnection(connString);
string selectSQL = "SELECT * FROM collegeemployee";
conn.Open();
MySqlDataAdapter da = new MySqlDataAdapter(selectSQL, conn);
MySqlCommandBuilder builder = new MySqlCommandBuilder(da);
DataTable table = new DataTable();
try
{
dgView2.Rows.RemoveAt(dgView2.CurrentRow.Index);
da.Update(table);
}
catch (Exception exceptionObj)
{
MessageBox.Show(exceptionObj.Message.ToString());
}
the problem with this code (listed in a method obviously) is that while the grid is able to be modified, it is unable to pass the data back to the database.
Instead of updating your database with the empty table what you should do is.
i.Get the datasource . like
ii. Update/synchronize the data source and data adapter
Here is the code it should work, if it doesn't please comment and tell me the problem.
string connString = "server=localhost;User Id=root;database=collegelist;";
MySqlConnection conn = new MySqlConnection(connString);
string selectSQL = "SELECT * FROM collegeemployee";
conn.Open();
MySqlDataAdapter da = new MySqlDataAdapter(selectSQL, conn);
MySqlCommandBuilder builder = new MySqlCommandBuilder(da);
BindingSource BindingSourceToUpdate = (BindingSource)dgView2.DataSource; // because direct casting to data table was failing in VS2o1o
try
{
dgView2.Rows.RemoveAt(dgView2.CurrentRow.Index);
da.Update((DataTable)BindingSourceToUpdate.DataSource);
}
catch(exception)
{
}
conn.close();

What is the best way to connect to a local database that will be used by two apps?

I'm writting an application in C# that connects to a database that is used by other application. I'm coding the class that access the database like this:
class conexionBD
{
string connString;
protected void miConexion(string ruta)
{
connString = String.Concat("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=", ruta);
}
protected DataTable misEmpleados()
{
string query = "SELECT Fiel1, Field2 FROM Table1";
DataTable dTable = miDatatable(query);
return dTable;
}
protected DataColumn misDptos()
{
DataTable dTable = miDatatable("SELECT OtherField from OtherTable");
return dTable.Columns[0];
}
private DataTable miDatatable(string sqlQuery)
{
OleDbDataAdapter dAdapter = new OleDbDataAdapter(sqlQuery, connString);
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
DataTable dTable = new DataTable();
dAdapter.Fill(dTable);
return dTable;
}
}
The app firts calls the method "miConexion" to set the path to the database in the hard disc. Then the app connects and disconnects each time I want to get the data stored in "Table1" and "OtherTable".
The database is likely to be accessed and modified by both apps at the same time. "Connecting and disconnecting" is the best way to access the database in this case?
there are 3 improvements you can make:
abstract the specific database adapter to the configuration file.
dispose of ado.net objects when you are finished with them
use transaction when reading and writing to/from the db.
The database is likely to be accessed and modified by both apps at the
same time.
Then you would need to use transactions.
Also check that you open and close connection and the connection remains open for the shortest possible time. OleDb stack is really old if this is a new application consider moving to ORM or at least ADO.NET.
Use an ORM like Entity Framework (EF) or NHibernate to manage the state of the object (if both applications are .Net)
I would recommend NHibernate as you are using OLE data adapter (but see if there are any connectors for the database you are using for EF as it is far easier to setup)..
This is the modification of the method "miDatatable", it connects to an Access Database:
private DataTable miDatatable(string sqlQuery)
{
using (OleDbConnection connDB = new OleDbConnection(connString))
{
OleDbDataAdapter dAdapter;
OleDbCommandBuilder cBuilder;
OleDbCommand command = new OleDbCommand();
DataTable dTable = new DataTable();
OleDbTransaction trans = null;
try
{
connDB.Open();
trans = connDB.BeginTransaction(IsolationLevel.ReadCommitted);
command.Connection = connDB;
command.Transaction = trans;
command.CommandText = sqlQuery;
dAdapter = new OleDbDataAdapter(sqlQuery, connDB);
cBuilder = new OleDbCommandBuilder(dAdapter);
dAdapter.SelectCommand.Transaction = trans;
dAdapter.Fill(dTable);
trans.Commit();
}
catch
{
try
{
trans.Rollback();
}
catch { }
}
return dTable;
}
}

Categories

Resources