How to connect to InterBase database using c# - c#

I have a need to connect to a report Interbase server and pull data from a table.
I have the following code, I am trying several options to make a successful connection to the server, however not able to do so. Could you please let me know what's wrong with my code. Or please point me to any article which shows a step by step approach to successfully connect to an Interbase server and pull data.
using System;
using System.Data;
using System.Data.Common;
using InterBaseSql.Data.InterBaseClient;
string connectionString = "server=remoteserver_ip_address;dataBase=C:\\test\\interbasedb\\database.gdb;User_Name=myusername;Password=mypassword;";
using (var connection = new IBConnection(connectionString))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
using (var command = new IBCommand("select * from table rows 1", connection, transaction))
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var values = new object[reader.FieldCount];
reader.GetValues(values);
Console.WriteLine(string.Join("|", values));
}
}
}
}
}
I suspect the issue is with the connection string. I tried changing the connection string several ways, but getting different error every time.
All errors below.
Client library - ibclient64 not found (I copied ibclient64.dll into the project folder, and this error was resolved)
Your user name and password are not defined. Ask your database administrator to set up a InterBase login.
connection rejected by remote interface
Unable to complete network request to host "remoteserver_ip_address". Failed to locate host machine. Undefined service gds_db/tcp.
I am able to connect to the same server using IBConsole application, Which I believe is a client software to connect to Interbase server (Like Management Studio for SQL Server, and WorkBench for MySQL and PGAdmin for PostgresSQL)
The Parameters I am using to connect to the Interbase Server using IBConsole are same as that of I am using in the C# code.
Report Server IP: remoteserver_ip_address
DataBase: C:\test\interbasedb\database.gdb
User Name: myusername
Password: mypassword
Partial breakthrough for above issue.
After several hours of trial and error, I was finally able to connect to the interbase server successfully using Embarcadero drivers.
I had to change the connectionstring to look as below for a successful connection.
server=remoteserver_ip_address;database=C:\test\interbasedb\database.gdb;user=myusername;password=mypassword
But now I am stuck with another issue. When I use a query like select * from some_table_which_doesnot_exists, I clearly receive a message that the Table is not found.
And when I use a query like Select * from a table_that_exists_in_the_db, I always get follow error.
Dynamic SQL Error
SQL error code - 804
SQLDA error (I believe SQLDA = SQL DataAdapter, because thats where the code it throwing error)
I went to the Embarcadero Error Codes List to see more information on this error and found the reason to be SQLDA missing or incorrect version, or incorrect number/type of variables.. I am stuck here not sure how to proceed further. Please help.

I think you are missing "PORT" details for connection to the interbase server instance.
You can try the below solution for the connection string. This has worked for me in my local machine.
static void Main(string[] args)
{
var cs = BuildConnectionStringBuilder().ToString();
try
{
using (var connection = new IBConnection(cs))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
using (var command = new IBCommand("select * from employee rows 1", connection, transaction))
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var values = new object[reader.FieldCount];
reader.GetValues(values);
Console.WriteLine(string.Join("|", values));
}
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
private static IBConnectionStringBuilder BuildConnectionStringBuilder()
{
var builder = new IBConnectionStringBuilder();
builder.UserID = "SYSDBA";
builder.Password = "masterkey";
builder.DataSource = "localhost";
builder.Database = AppDomain.CurrentDomain.BaseDirectory + "test-employee.ib";
builder.Port = 3050;
return builder;
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormsApp1_3grupa
{
public partial class Form1 : Form
{
SqlConnection konekcija = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename;Integrated Security=True;Connect Timeout=30");
public Form1()
{
InitializeComponent();
}
private void tabPage1_Click(object sender, EventArgs e)
{
}
private void buttonIzadji_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
string sqlUpit = "select * from Citalac";
try
{
SqlCommand komanda = new SqlCommand(sqlUpit, konekcija);
SqlDataAdapter da = new SqlDataAdapter(komanda);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
foreach (DataRow row in dt.Rows)
{
ListViewItem listItem = new ListViewItem(row["HotelID"].ToString());
listItem.SubItems.Add(row["Naziv"].ToString());
listItem.SubItems.Add(row["Adresa"].ToString());
listItem.SubItems.Add(row["Telefon"].ToString());
listItem.SubItems.Add(row["Grad"].ToString());
listView1.Items.Add(listItem); // Dodaje red u ListView
}
}
catch (Exception)
{
//MessageBox.Show("Greska");
}
}
private void buttonPrikazDGV_Click(object sender, EventArgs e)
{
SqlParameter param = new SqlParameter();
param.ParameterName = "#param1";
param.Value = numericUpDown1.Value;
string sqlUpit = "select * from Hotel where HotelID=#param1";
SqlCommand komanda = new SqlCommand(sqlUpit, konekcija);
komanda.Parameters.Add(param);
try
{
konekcija.Open();
SqlDataReader dr = komanda.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataGridView2.DataSource = dt;
}
catch (Exception)
{
MessageBox.Show("Greska");
}
finally
{
konekcija.Close();
}
}
private void buttonPrikazLV_Click(object sender, EventArgs e)
{
string sqlUpit = "select * from Hotel";
try
{
SqlCommand komanda = new SqlCommand(sqlUpit, konekcija);
SqlDataAdapter da = new SqlDataAdapter(komanda);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
foreach (DataRow row in dt.Rows)
{
ListViewItem listItem = new ListViewItem(row["HotelID"].ToString());
listItem.SubItems.Add(row["Naziv"].ToString());
listItem.SubItems.Add(row["Adresa"].ToString());
listItem.SubItems.Add(row["Telefon"].ToString());
listItem.SubItems.Add(row["Grad"].ToString());
listItem.SubItems.Add(row["Drzava"].ToString());
listItem.SubItems.Add(row["Kategorija"].ToString());
listView1.Items.Add(listItem); // Dodaje red u ListView
}
}
catch (Exception)
{
MessageBox.Show("Greska");
}
}
private void buttonIzadji2_Click(object sender, EventArgs e)
{
this.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}

Related

Error when editing a datagridview with a connected MySQL database. An error appears when trying to save

When trying to edit the datagridview, an error appears "The CommandText property has not been properly initialized.". I read that some other stored procedure is needed, which as input parameters it takes the first name, last name and patronymic and phone number of the user and returns his id, if so, how to implement it on mysql link to the source: https://metanit.com/sharp/adonet/2.11.php , https://metanit.com/sharp/adonet/3.5.php
Program code:
using MySql.Data.MySqlClient;
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 SD = System.Data;
namespace DBredaction
{
public partial class Form1 : Form
{
DataSet ds;
MySqlDataAdapter adapter;
MySqlCommandBuilder commandBuilder;
string connectionString = "Server=localhost;Database=catalog;Uid=root;pwd=;charset=utf8;";
string sql = "SELECT * FROM employee";
public Form1()
{
InitializeComponent();
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.AllowUserToAddRows = false;
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
adapter = new MySqlDataAdapter(sql, connection);
ds = new DataSet();
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
// делаем недоступным столбец id для изменения
dataGridView1.Columns["Id"].ReadOnly = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
//public MySqlConnection mycon;
//public MySqlCommand mycom;
//public string connect = "Server=localhost;Database=catalog;Uid=root;pwd=;charset=utf8;";
//public SD.DataSet ds;
//public MySqlCommand mycon2;otchestvo
private void button1_Click(object sender, EventArgs e)
{
try {
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
adapter = new MySqlDataAdapter(sql, connection);
commandBuilder = new MySqlCommandBuilder(adapter);
adapter.InsertCommand = new MySqlCommand("", connection);
adapter.InsertCommand.CommandType = CommandType.StoredProcedure;
adapter.InsertCommand.Parameters.Add(new MySqlParameter("#imia", MySqlDbType.VarChar, 50, "Имя"));
adapter.InsertCommand.Parameters.Add(new MySqlParameter("#familia", MySqlDbType.VarChar, 50, "Фамилия"));
adapter.InsertCommand.Parameters.Add(new MySqlParameter("#otchestvo", MySqlDbType.VarChar, 50, "Отчество"));
adapter.InsertCommand.Parameters.Add(new MySqlParameter("#telephon", MySqlDbType.VarChar, 11, "Телефон"));
MySqlParameter parameter = adapter.InsertCommand.Parameters.Add("#id", MySqlDbType.Int16, 0, "Id");
parameter.Direction = ParameterDirection.Output;
adapter.Update(ds);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button4_Click(object sender, EventArgs e)
{
try
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MessageBox.Show("DB CONNECT");
connection.Close();
}
}
catch
{
MessageBox.Show("Connection lost");
}
}
private void button3_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
dataGridView1.Rows.Remove(row);
}
}
private void button5_Click(object sender, EventArgs e)
{
DataRow row = ds.Tables[0].NewRow();
ds.Tables[0].Rows.Add(row);
}
}
}
It doesn't work quite like that; if you're assigning a command builder to an adapter you don't then also set the XxxCommand DML properties yourself; the command builder does that from looking at the SelectCommand, working out the table schema and writing the queries.
I'd have the adapter at class level in a dedicated repository class, where the select, connstr and command builder are set:
//in the constructor of the repo class
_myDataAdapter = new MySqlDataAdapter("SELECT here", "connstr here");
_commandBuilder = new MySqlCommandBuilder(_myDataAdapter);
the fill code runs:
//in a GetData method of the repo class
DatTable dt = new DataTable();
_myDataAdapter.Fill(dt);
return dt;
and the relevant I/U/D commands can be triggered:
//in a SaveChanges(DataTable) method of the repo class
_myDataAdapter.Update(dt);
See https://www.devart.com/dotconnect/mysql/docs/Devart.Data.MySql~Devart.Data.MySql.MySqlCommandBuilder.html for more background info on the CB; their example code is based on a complete programmatic "fill, change, save" workflow so it's all in one method, but your workflow is essentially interrupted by the user needing to do the changes in the grid, hence breaking it up.
If you want to do it in one method, you can make your adapter, make your command builder and then set the I/U/D commands on the adapter by calling the relevant GetXxx on the command builder
Note that the command builder doesn't use stored procedures; that thing you've read about needing to make a stored procedure to update/insert data isn't the only way to save data to a db, and if you have created a sproc and are hoping to use it, forget a command builder; you'll have to do the command setup yourself

Is there a better way to connect my DB to my Form?

I'm trying to connect my DB to my ListView, and I'm trying to find a better way than what's in the book. I looked at a couple forums and a lot of them have the same thing like what's in my code down below.
We didn't have a lot of time to go over databases in class, so a lot of my knowledge with connection strings come from the internet and a small chapter in the book.My Database name is GameStoreLibrary.
using System.Data;
using System.Data.SqlServerCe;
public partial class DisplayGameStoreTable : Form
{
//WHAT THE C# FORUMS SAY TO DO
public SqlCeConnection cn = new SqlCeConnection(#"
Data Source=.;
Initial Catalog=DB GameStoreLibrary;
Integrated Security=True;
MultipleActiveResultSets=True");
private void DisplayGameStoreTable_Load(object sender, EventArgs e)
{
try
{
cn.Open();
}
catch(SqlCeException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
}
private void NewGameBttn_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
SqlCeCommand cm = new SqlCeCommand("SELECT * FROM newGames ORDER BY gametitle ASC", cn);
try
{
SqlCeDataAdapter da = new SqlCeDataAdapter(cm);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
ListViewItem item = new ListViewItem(dr["gametitle"].ToString());
item.SubItems.Add(dr["releasedate"].ToString());
item.SubItems.Add(dr["console"].ToString());
item.SubItems.Add(dr["company"].ToString());
item.SubItems.Add(dr["gameprice"].ToString());
item.SubItems.Add(dr["quantity"].ToString());
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Small Tip :
Try to use a DBConnect class instead of typing connection string every single time and closing the connection.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace InventoryManagementSystem
{
class DBConnect : IDisposable
{
private static String connectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\Private\InventoryManagementSystem\InventoryManagementSystem\InventoryDB.mdf;Integrated Security=True";
public SqlConnection con = new SqlConnection(connectionString);
public DBConnect()
{
try
{
con.Open();
Console.WriteLine("Database connected");
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
Console.WriteLine("Database Connection Failed");
throw new Exception();
}
}
public void Dispose()
{
con.Close();
}
}
}
After you have this in your project you just have to create an object whenever you want to access the database.
public void getData(){
using(DBConnect db = new DBConnect()){
String q = "select * from TestTable";
SqlCommand cmd = new SqlCommand(q,db.con);
SqlDatareader r = cmd.ExcecuteReader();
}
}
This will automatically close the connections too.
To add on to Gihan's answer, it's also an accepted practice to create the App.Config file and put the connection string in there so it's not inside your source code. Then it's easier to change without recompiling anything.
Use the ConnectionStrings section of the App.Config and then you can get the connection string using the code:
System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;

AutoComplete with MS Access database

I want to make my txtSearch textbox in Visual Studio autocomplete.
I have searched around for a long time, for some explanations and tutorials,
but the most are about SQL databases. I have a MS Access database in my application.
I want to make autocomplete suggests from my Titel colon in my database (appData/Film)
First of all, can a textbox do the job, or is a rich textbox necessary to do the job?
I don't expect code from you, but maybe an explanation or a tutorial, you know somewhere?
Thanks. And oops. Important info: My application is based on C#, and coded in Visual Studio.
Try it this way.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Collections;
namespace WinAutoComplete
{
public partial class Form1 : Form
{
AutoCompleteStringCollection ProductList = new
AutoCompleteStringCollection();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//declare connection string
string cnString = #"Data Source=EXCEL-PC\SQLEXPRESS; Initial Catalog=NORTHWND;" +
"Trusted_Connection = True";
/*use following if you use standard security
string cnString = #"Data Source=(local);Initial
Catalog=northwind; Integrated Security=SSPI"; */
//declare Connection, command and other related objects
SqlConnection conGetData = new SqlConnection(cnString);
SqlCommand cmdGetData = new SqlCommand();
SqlDataReader drGetData;
try
{
//open connection
conGetData.Open();
//prepare connection object to get the data through
//reader and populate into dataset
cmdGetData.CommandType = CommandType.Text;
cmdGetData.Connection = conGetData;
cmdGetData.CommandText = "Select ProductName From Products";
//read data from command object
drGetData = cmdGetData.ExecuteReader();
if (drGetData.HasRows == true)
{
while (drGetData.Read())
ProductList.Add(drGetData["ProductName"].ToString());
}
else
MessageBox.Show("No data found in Products tables");
//close reader and connection
drGetData.Close();
conGetData.Close();
//set the default pattern to SuggestAppend
//comboBoxPattern.SelectedIndex = 1;
txtProductID.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txtProductID.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtProductID.AutoCompleteCustomSource = ProductList;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
//check if connection is still open then attempt to close it
if (conGetData.State == ConnectionState.Open)
{
conGetData.Close();
}
}
}
private void comboBoxPattern_SelectedIndexChanged(object sender, EventArgs e)
{
//switch (comboBoxPattern.Text)
//{
// case "Suggest":
// txtProductID.AutoCompleteMode = AutoCompleteMode.Suggest;
// break;
// case "Append":
// txtProductID.AutoCompleteMode = AutoCompleteMode.Append;
// break;
// case "SuggestAppend":
// txtProductID.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
// break;
//}
}
}
}
This definitely works, as you can see in the screen shot below.
Also, check this out when you have a chance.
https://www.connectionstrings.com/

Connect Telerik in C# to PostgreSql db

I want to make a connection from my project that using Telerik to the PostgreSql database. After that i will make the CRUD, but i always failed to make the connection. I had already try the telerik docs but it still failed. I'm using visual studio 2012 and Npgsql as the driver. And i want to make connection with entity data model. Please anyone help me. I need the real tutorial with this. I makes web project
Using system.configuration you can try to call the app.config file.
Try this one:
http://docs.telerik.com/data-access/deprecated/quick-start-scenarios/asp.net-mvc/quickstart-mvc-conn-string
How about this one:
App.config file:
configuration>
connectionStrings>
add name="npgsql" connectionString="User >ID=npg_username;Password=npg_password;Server=server_Ip_or_localhost;Database=np>g_dbname;timeout=1000;Pooling=False;
Pooling=false;INTEGRATED >SECURITY=False; CommandTimeout=120" providerName="Npgsql"/>
/connectionStrings>
/configuration>
Note: Add references npgdll to your project
TO YOUR CODE BEHIND:
using System.Configuration;
using Npgsql;
using System.Data;
private static DataSet GetTData(ref string msg)
{
String Query = Query = #"select column1,column2 from table1";
String connstr = ConfigurationManager.ConnectionStrings["npgsql"].ToString();
NpgsqlConnection cnn = new NpgsqlConnection(connstr);
NpgsqlDataAdapter adp = new NpgsqlDataAdapter(Query, cnn);
DataSet ds = new DataSet();
try
{
adp.Fill(ds);
msg = String.Empty;
return ds;
}
catch (Exception e)
{
msg = e.Message;
return ds;
}
finally
{
ds.Dispose();
if (cnn != null)
{
cnn.Close();
cnn.Dispose();
adp.Dispose();
}
}
}
To use this:
private void form_Load(object sender, EventArgs e)
{
String error = string.empty
DataSet ds = new Dataset();
ds= GetTData(ref error);
if(error!=string.empty )
{
MessageBox.Show(error);
return;
}
}

Datagridview cell value change update database

I have retrieved data from Mysql database into a DataGridView1. Let us suppose I am in Row 0. When I change the contents of Row 0, Cell 1 and press enter key or a button, the Update query should modify that row, but I am unable to modify the value of the cell. The cell maintains its previous value when i reload data and the database is not modified. For example, if I change the contents of a cell under column Client_Name from "Acs" to "Gmt", how can I change the value of the cell from "Acs" to "Gmt"? and to have it updated into Mysql database, I am using c# in Vs 2012. below is my code that retrieves my database into datagridview1 any help is welcomed thanks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Data.SqlClient;
namespace PI.Gen
{
public partial class frmMain : Form
{
MySqlConnection Conn;
public frmMain()
{
InitializeComponent();
btnDisconnect.Enabled = true;
btnLoadData.Enabled = false;
btnLoadClients.Enabled = false;
}
private void btnConnect_Click(object sender, EventArgs e)
{
string strConnect = "server=" + txtServer.Text + ";uid=" + txtUsername.Text + ";pwd=" + txtPassword.Text + ";database=" + txtDatabase.Text;
try
{
if (txtServer.TextLength <= 0 || txtUsername.TextLength <= 0 || txtDatabase.TextLength <= 0)
{
MessageBox.Show("You have an empty database connection field. Please supply a valid value.");
return;
}
Conn = new MySqlConnection(strConnect);
Conn.Open();
if (Conn.State.ToString() != "Open")
{
MessageBox.Show("Could not open database connection");
return;
}
btnDisconnect.Enabled = true;
btnConnect.Enabled = false;
btnLoadData.Enabled = true;
btnLoadClients.Enabled = true;
// btnSubmitClient.Enabled = true;
}
catch (Exception ex) // catch on general exceptions, not specific
{
MessageBox.Show(ex.Message);
return;
}
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
if (Conn != null)
{
Conn.Close();
}
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
try
{
Conn.Close();
Conn = null;
btnDisconnect.Enabled = false;
btnConnect.Enabled = true;
btnLoadData.Enabled = false;
btnLoadClients.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
private void btnLoadData_Click(object sender, EventArgs e)
{
try
{
string CmdString = "SELECT * FROM t_receipients";
MySqlDataAdapter sda = new MySqlDataAdapter(CmdString, Conn);
DataSet ds = new DataSet();
sda.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
private void btnLoadClients_Click(object sender, EventArgs e)
{
try
{
string CmdString = "SELECT * FROM t_clients";
MySqlDataAdapter sda = new MySqlDataAdapter(CmdString, Conn);
DataSet ds = new DataSet();
sda.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
After series of trials and error, i finally found what i was looking for, thus being able to update database from datagridview below is my worked around code which works 100% hope it helps someone in future, and thanks #RageComplex for helping out, but one more thing does anyone know how to implement that i mean instead of hitting the enter button to take changes in the datagridview you rather click on a button ty
private void dataGridView1_RowValidated(object sender, DataGridViewCellEventArgs e)
{
try
{
DataTable changes = ((DataTable)dataGridView1.DataSource).GetChanges();
if (changes != null)
{
MySqlCommandBuilder mcb = new MySqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.UpdateCommand = mcb.GetUpdateCommand();
mySqlDataAdapter.Update(changes);
((DataTable)dataGridView1.DataSource).AcceptChanges();
MessageBox.Show("Cell Updated");
return;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You are not updateing your changes to the database. While you keep your connection open doesn't mean that this will automatically update your data.
First of all, don't keep your connection open. In your app you have a connect button which is good for testing but not for really keeping the connection open, not with databases in my opinion.
The way you load data is correct.
You give the datagridview an DataSource which is a table from your DataSet. So changes made in the datagridview ARE saved to your DataSet but not to your database.
This is how you update your database
public void UpdateTable(DataSet ds)
{
using (MySqlConnection connect = new MySqlConnection(ConnString))
{
connect.Open();
MySqlDataAdapter adapt = new MySqlDataAdapter();
MySqlCommandBuilder commbuilder = new MySqlCommandBuilder(adapt);
adapt.SelectCommand = new MySqlCommand("SELECT * FROM t_receipients", connect);
adapt.Update(ds.Tables[0]);
}
}
Make sure, before you Update your database, you use datagridview1.EndEdit()
Also, you using, this will ensure a connection is closed again after completing that code, best is to always have it in a try-except.
You had struggles with connecting the database as it appears to be in the commends.
I've also forgot to include MySqlDataAdapter above, I used an adapter globally in that case.
I didn't want to report this question as duplicated, but now it kinda does look like this answer.
I would like to give code which I have tested in my application.I used it for button click event.
private void button3_Click(object sender, EventArgs e)
{
string StrQuery;
try
{
string MyConnection2 = "server=localhost;user id=root;password=;database=k";
using (MySqlConnection conn = new MySqlConnection(MyConnection2))
{
using (MySqlCommand comm = new MySqlCommand())
{
comm.Connection = conn;
conn.Open();
for (int i = 0; i < dataGridView3.Rows.Count; i++)
{
StrQuery = #"update s set Quantity='" + dataGridView3.Rows[i].Cells["Quantity"].Value.ToString() + "' where No='" + dataGridView3.Rows[i].Cells["Item No"].Value.ToString() + "';";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
catch
{
}
}
I think it may help you

Categories

Resources