Hi guys, hope someone can look for some mistakes I made in my coding. I made a winform application containing a datagrid and 3 buttons.
I need to be able to insert new rows, edit and delete and save to the gridview and also the database. It doesn't work a 100%.
Anyone has some advice?
Thanks
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;
using System.Data.OleDb;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
OleDbConnection con = new OleDbConnection();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\\Northwind 2007.accdb";
con.Open();
ds.Tables.Add(dt);
da = new OleDbDataAdapter("SELECT * from Customers", con);
da.Fill(dt);
dg.DataSource = dt.DefaultView;
}
catch (Exception error)
{
MessageBox.Show("FOUT:" + error.Message);
}
}
private void butUpdate_Click(object sender, EventArgs e)
{
try
{
da.UpdateCommand = new OleDbCommand("UPDATE Customers SET Company='test' WHERE ID = 1;", con);
con.Open();
da.UpdateCommand.ExecuteNonQuery();
}
catch (Exception error)
{
MessageBox.Show("FOUT:" + error.Message);
}
}
private void butDelete_Click(object sender, EventArgs e)
{
try
{
da.DeleteCommand = new OleDbCommand("DELETE from Customers where Id=3;", con);
con.Open();
da.DeleteCommand.ExecuteNonQuery();
}
catch (Exception error)
{
MessageBox.Show("FOUT:" + error.Message);
}
}
private void butInsert_Click(object sender, EventArgs e)
{
try
{
da.InsertCommand = new OleDbCommand("INSERT INTO Customers (Company, Last Name) VALUES 'Test','TestName';", con);
con.Open();
da.InsertCommand.ExecuteNonQuery();
//string Insertstring = "";
//OleDbCommand InsertCMD = new OleDbCommand(Insertstring);
//InsertCMD.ExecuteNonQuery();
}
catch (Exception error)
{
MessageBox.Show("FOUT:" + error.Message);
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
con.Close();
}
}
}