Changes to the DataGridView does not save on the database - c#

I have a datagridview with an update button. When I press the update button after making a change in the datagridview, I get this error:
"Dynamic SQL generation is not supported against a select-command that does not return any base table information"
I've searched around for answers but cannot find any. Some of you experts will probably find this easy. Sorry About the format guys. I can't get it to display properly on here.
public partial class Form1 : Form
{
MySqlConnection con;
MySqlDataAdapter adap;
DataSet ds;
MySqlCommandBuilder cmdbl;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
con = new MySqlConnection();
con.ConnectionString = #"server=localhost; Database=database; username=username; password=";
con.Open();
adap = new MySqlDataAdapter("select * from employer",con);
ds = new System.Data.DataSet();
adap.Fill(ds, "emp_id");
dataGridView1.DataSource = ds.Tables[0];
con.Close();
}
catch(Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error");
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
cmdbl = new MySqlCommandBuilder(adap);
adap.Update(ds, "emp_id");
MessageBox.Show("Information Updated");
}
catch(Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

Related

C# data to datagridview does not reloaded

Am trying to reload data to datagridview when i click on refresh button but data is not refreshed after click. Am using MySQL database and when i start program i go in database manager SQLYog and manually make changes in that row. After that i switch to my app and press refresh button to se does app work but nothing is happening. I dont know what i do wrong and whay data in grid is not refreshed...
Here is my code:
class MainWindow : Form
{
private MySqlDataAdapter adapter;
private MySqlCommandBuilder cmd;
private BindingSource bs = new BindingSource();
private DataGridView dataGridView1;
private DataTable dt = new DataTable();
// Constructor
public MainWindow()
{
this.InitializeComponent();
}
// Get data
public void GetData(string sql)
{
using (var conn = new MySqlConnection(Properties.Settings.Default.connString))
{
try
{
conn.Open();
adapter = new MySqlDataAdapter(sql, conn);
cmd = new MySqlCommandBuilder(adapter);
adapter.Fill(dt);
bs.DataSource = dt;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
}
// Load
private void MainWindow_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = bs;
GetData("SELECT * FROM grupe_artikala");
}
// Reload click
private void reload_Click(object sender, EventArgs e)
{
GetData(adapter.SelectCommand.CommandText);
}
}
Try this:
class MainWindow : Form
{
private MySqlDataAdapter adapter;
private MySqlCommandBuilder cmd;
private BindingSource bs = new BindingSource();
private DataGridView dataGridView1;
private DataTable dt = new DataTable();
String sql = "SELECT * FROM grupe_artikala";
// Constructor
public MainWindow()
{
this.InitializeComponent();
}
// Get data
public void GetData(string sql)
{
using (var conn = new MySqlConnection(Properties.Settings.Default.connString))
{
try
{
conn.Open();
adapter = new MySqlDataAdapter(sql, conn);
cmd = new MySqlCommandBuilder(adapter);
adapter.Fill(dt);
bs.DataSource = dt;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
}
// Load
private void MainWindow_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = bs;
GetData(sql);
}
// Reload click
private void reload_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = null;
dataGridView1.DataSource = bs;
GetData(sql);
datagridview1.update();
datagridview1.refresh();
}
}
You should write this. This might solve your problem
class MainWindow : Form
{
private MySqlDataAdapter adapter;
private MySqlCommandBuilder cmd;
private BindingSource bs = new BindingSource();
private DataGridView dataGridView1;
private DataTable dt = new DataTable();
// Constructor
public MainWindow()
{
this.InitializeComponent();
}
// Get data
public void GetData(string sql)
{
using (var conn = new MySqlConnection(Properties.Settings.Default.connString))
{
try
{
conn.Open();
adapter = new MySqlDataAdapter(sql, conn);
cmd = new MySqlCommandBuilder(adapter);
adapter.Fill(dt);
bs.DataSource = dt;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
}
// Load
private void MainWindow_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = bs;
String sql = "SELECT * FROM grupe_artikala";
}
// Reload click
private void reload_Click(object sender, EventArgs e)
{
GetData(sql);
}
}

Gridview click header row doesn't select data for update or delete

I've found a curious situation working with gridview.
Selecting one header row on the gridview, supposedly should select the data fields and pass them to the Winform fields that allow editing to Update the record or Delete the record.
Apparently the same code produces different results.
Any idea what's happening and how to correct the situation?
Thank you.
The working code:
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace InsertUpdateDeleteDemo
{
public partial class frmMain : Form
{
string cs = "Data Source=.;Initial Catalog=Sample;Integrated Security=true;";
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");
SqlCommand cmd;
SqlDataAdapter adapt;
//ID variable used in Updating and Deleting Record
int ID = 0;
DataTable dt;
public frmMain()
{
InitializeComponent();
DisplayData();
}
private void txt_SearchName_TextChanged(object sender, EventArgs e)
{
con = new SqlConnection(cs);
con.Open();
adapt = new SqlDataAdapter("select * from tbl_Employee where FirstName like '" + txt_SearchName.Text + "%'", con);
dt = new DataTable();
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
ClearData();
}
//Insert Data
private void btn_Insert_Click(object sender, EventArgs e)
{
if (txt_First_Name.Text != "" && txt_Last_Name.Text != "" && txt_State.Text != "")
{
txt_SearchName.Text = "";
cmd = new SqlCommand("insert into tbl_Employee(FirstName,LastName,State) values(#FirstName,#state)", con);
con.Open();
cmd.Parameters.AddWithValue("#FirstName", txt_First_Name.Text);
cmd.Parameters.AddWithValue("#LastName", txt_Last_Name.Text);
cmd.Parameters.AddWithValue("#state", txt_State.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted Successfully");
ClearData();
DisplayData();
}
else
{
MessageBox.Show("Please Provide Details!");
}
}
//Display Data in DataGridView
private void DisplayData()
{
con.Open();
DataTable dt=new DataTable();
adapt=new SqlDataAdapter("select * from tbl_Employee",con);
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
//Clear Data
private void ClearData()
{
txt_First_Name.Text = "";
txt_Last_Name.Text = "";
txt_State.Text = "";
ID = 0;
}
//dataGridView1 RowHeaderMouseClick Event
private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
txt_First_Name.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
txt_Last_Name.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
txt_State.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
}
//Update Record
private void btn_Update_Click(object sender, EventArgs e)
{
if (txt_First_Name.Text != "" && txt_State.Text != "")
{
cmd = new SqlCommand("update tbl_Employee set FirstName=#FirstName,LastName=#LastName,State=#state where ID=#id", con);
con.Open();
cmd.Parameters.AddWithValue("#id", ID);
cmd.Parameters.AddWithValue("#FirstName", txt_First_Name.Text);
cmd.Parameters.AddWithValue("#LastName", txt_Last_Name.Text);
cmd.Parameters.AddWithValue("#state", txt_State.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
con.Close();
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Please Select Record to Update");
}
}
//Delete Record
private void btn_Delete_Click(object sender, EventArgs e)
{
if(ID!=0)
{
cmd = new SqlCommand("delete tbl_Employee where ID=#id",con);
con.Open();
cmd.Parameters.AddWithValue("#id",ID);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Deleted Successfully!");
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Please Select Record to Delete");
}
}
private void frmMain_Load(object sender, EventArgs e)
{
con = new SqlConnection(cs);
con.Open();
adapt = new SqlDataAdapter("select * from tbl_Employee", con);
dt = new DataTable();
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
private void txt_First_Name_TextChanged(object sender, EventArgs e)
{
}
private void txt_Last_Name_TextChanged(object sender, EventArgs e)
{
}
private void txt_State_TextChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
Two pieces of similar code. In first view, one works, the other doesn't.
When clicking gridview header row, the data is not selected and passed to the Winform fields.
Any hint why?
The non-working code:
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Banco_de_Imagens_Beatriz
{
public partial class EcranDiagnostico : Form
{
string cs = "Data Source=Posto0;Initial Catalog=Banco_Imagens;Persist Security Info=True;User ID=sa;Password=12QWaszx";
SqlConnection con = new SqlConnection("Data Source=Posto0;Initial Catalog=Banco_Imagens;Persist Security Info=True;User ID=sa;Password=12QWaszx");
SqlCommand cmd;
SqlDataAdapter adapt;
//ID variable used in Updating and Deleting Record
int iddiag = 0;
DataTable dt;
public EcranDiagnostico()
{
InitializeComponent();
DisplayData();
}
private void txt_SearchName_TextChanged(object sender, EventArgs e)
{
con = new SqlConnection(cs);
con.Open();
adapt = new SqlDataAdapter("select * from tb_diag where nome_diag like '" + txt_SearchName.Text + "%'", con);
dt = new DataTable();
adapt.Fill(dt);
DataGridView1.DataSource = dt;
con.Close();
ClearData();
}
//Insert Data
private void btn_Insert_Click(object sender, EventArgs e)
{
if (txt_NomeDiag.Text != "" && txt_DescrDiag.Text != "")
{
txt_SearchName.Text = "";
cmd = new SqlCommand("insert into tb_diag(nome_diag,descr_diag) values(#nome_diag,#descr_diag)", con);
con.Open();
cmd.Parameters.AddWithValue("#nome_diag", txt_NomeDiag.Text);
cmd.Parameters.AddWithValue("#descr_diag", txt_DescrDiag.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Registo inserido com sucesso.");
ClearData();
DisplayData();
}
else
{
MessageBox.Show("Não introduziu dados. Introduza os dados que pretende.");
}
}
//Display Data in DataGridView
private void DisplayData()
{
con.Open();
DataTable dt = new DataTable();
adapt = new SqlDataAdapter("select * from tb_diag", con);
adapt.Fill(dt);
DataGridView1.DataSource = dt;
con.Close();
}
//Clear Data
private void ClearData()
{
txt_NomeDiag.Text = "";
txt_DescrDiag.Text = "";
iddiag = 0;
}
//dataGridView1 RowHeaderMouseClick Event
private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
iddiag = Convert.ToInt32(DataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
txt_NomeDiag.Text = DataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
txt_DescrDiag.Text = DataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
}
//Update Record
private void btn_Update_Click(object sender, EventArgs e)
{
if (txt_NomeDiag.Text != "" && txt_DescrDiag.Text != "")
{
cmd = new SqlCommand("update tb_diag set nome_diag=#nome_diag,descr_diag=#descr_diag where iddiag=#iddiag", con);
con.Open();
cmd.Parameters.AddWithValue("#iddiag", iddiag);
cmd.Parameters.AddWithValue("#nome_diag", txt_NomeDiag.Text);
cmd.Parameters.AddWithValue("#descr_diag", txt_DescrDiag.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Registo actualizado com sucesso.");
con.Close();
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Não seleccionou nenhum registo. Seleccione o registo a actualizarr.");
}
}
//Delete Record
private void btn_Delete_Click(object sender, EventArgs e)
{
if (iddiag != 0)
{
cmd = new SqlCommand("delete tb_diag where iddiag=#iddiag", con);
con.Open();
cmd.Parameters.AddWithValue("#iddiag", iddiag);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Registo eliminado com sucesso.");
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Não seleccionou nenhum registo. Seleccione o registo a eliminar");
}
}
private void EcranDiagnostico_Load(object sender, EventArgs e)
{
// TODO: esta linha de código carrega dados na tabela 'dataSet_Tabela_Diagnostico.tb_diag'. Você pode movê-la ou removê-la conforme necessário.
//this.tb_diagTableAdapter.Fill(this.dataSet_Tabela_Diagnostico.tb_diag);
con = new SqlConnection(cs);
con.Open();
adapt = new SqlDataAdapter("select * from tb_diag", con);
dt = new DataTable();
adapt.Fill(dt);
DataGridView1.DataSource = dt;
con.Close();
}
private void txt_NomeDiag_TextChanged(object sender, EventArgs e)
{
}
private void txt_DescrDiag_TextChanged(object sender, EventArgs e)
{
}
}
}

some thing went wrong When i Edit User Information in MysqlDB && C#

hey guys am working in a simple Education Center Manager
so when i starts to edit any user info all the Users saved in Database (MySQL Database ) changes to the same name , age , time , class Except the Address
Like this Screen shots
Screen shot 1
Screen shot 2 the result
and here is my code
Form1.cs
public partial class Form1 : Form
{
DateTime datetime = DateTime.Now;
Students st = new Students();
public Form1()
{
InitializeComponent();
FILLDGV();
}
public void FILLDGV() {
dataGridView1.DataSource = st.ShowData();
dataGridView1.Columns[0].HeaderText = "ID";
dataGridView1.Columns[1].HeaderText = "Name";
dataGridView1.Columns[2].HeaderText = "Age";
dataGridView1.Columns[3].HeaderText = "Address";
dataGridView1.Columns[4].HeaderText = "Class";
dataGridView1.Columns[5].HeaderText = "Inserted Time";
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
private void button3_Click(object sender, EventArgs e) { //Button to Insert Data
try
{
st.AddStudent(textBox1.Text,Convert.ToInt32(textBox2.Text), textBox3.Text, textBox4.Text, datetime.ToString());
FILLDGV();
MessageBox.Show("Data Inserted Successfully");
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox1.Focus();
}
catch (Exception) { MessageBox.Show("Oops , Something went Wrong", "Error", MessageBoxButtons.OK,MessageBoxIcon.Error ); }
}
private void button2_Click(object sender, EventArgs e) //button to Edit Data
{
try
{
st.EditStudent(textBox1.Text, Convert.ToInt32(textBox2.Text), textBox3.Text, textBox4.Text,dataGridView1.CurrentRow.Cells[5].Value.ToString(), Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value));
FILLDGV();
MessageBox.Show("Edit Successfully");
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox1.Focus();
}
catch (Exception)
{
MessageBox.Show("Oops , Something went Wrong", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void dataGridView1_MouseDoubleClick(object sender, MouseEventArgs e) // data grid view to Display data
{
textBox1.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
textBox2.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
textBox3.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString();
textBox4.Text = dataGridView1.CurrentRow.Cells[4].Value.ToString();
}
private void تسجيلخروجToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e) // this Button to Delete Data
{
try
{
st.DelStudent(Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value));
FILLDGV();
MessageBox.Show("Delete Successfully");
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox1.Focus();
}
catch (Exception) { MessageBox.Show("Oops , Something went Wrong", "Error", MessageBoxButtons.OK,MessageBoxIcon.Information); }
}
}
Student.cs
class Students
{
MySqlConnection con = new MySqlConnection(#"Server=localhost;Database=stu_info;uid=root;pwd=root;");
public DataTable ShowData()
{
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM firstc", con);
da.Fill(dt);
return dt;
}
public void AddStudent(string name, int age, string address, string sclass,string date)
{
MySqlCommand cmd = new MySqlCommand("insert into firstc(sname,sage,saddress,sclass,DateT) values(#sname,#sage,#saddress,#sclass,#DateT)", con);
cmd.Parameters.AddWithValue("#sname", name);
cmd.Parameters.AddWithValue("#sage", age);
cmd.Parameters.AddWithValue("#saddress", address);
cmd.Parameters.AddWithValue("#sclass", sclass);
cmd.Parameters.AddWithValue("#DateT",date);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
public void EditStudent(string name, int age, string address, string sclass,string date, int id)
{
MySqlCommand cmd = new MySqlCommand("update firstc set sname=#sname,sage=#sage,sclass=#sclass where #sid", con);
cmd.Parameters.AddWithValue("#sname", name);
cmd.Parameters.AddWithValue("#sage", age);
cmd.Parameters.AddWithValue("#saddress", address);
cmd.Parameters.AddWithValue("#sclass", sclass);
cmd.Parameters.AddWithValue("#DateT", date);
cmd.Parameters.AddWithValue("#sid", id);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
public void DelStudent(int id)
{
MySqlCommand cmd = new MySqlCommand("Delete from firstc where firstc.sid=#sid", con);
cmd.Parameters.AddWithValue("#sid", id);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
The update statement's where clause is incorrect, since it does not contain any field name, only a value. This way all records are updated. Based on the delete statement, you need to add firstc.sid= to the where clause:
update firstc set sname=#sname,sage=#sage,sclass=#sclass where firstc.sid=#sid"

Updating value in combobox from another form after inserted to database

Can i know why am i getting weird output whereby the combobox does not refresh and show new values when a value is added to database from another form. Below my sample code
This is form code where the combobox need to be updated
public partial class Form1 : Form
{
OleDbConnection con = new OleDbConnection("Provider=MSDAORA;Data Source=orcl;User ID=nareen1093;Password=nareen1093;Unicode=True");
public Form1()
{
InitializeComponent();
loadButton();
}
public void loadButton ()
{
con.Open();
OleDbDataAdapter oda = new OleDbDataAdapter("select serial_number from fingerprint_device where serial_number like '%'", con);
DataTable dt = new DataTable();
oda.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "serial_number";
comboBox1.SelectedIndex = -1;
con.Close();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.ShowDialog();
}
}
this is form2 where the insert into database takes place.
public partial class Form2 : Form
{
OleDbConnection con = new OleDbConnection("Provider=MSDAORA;Data Source=orcl;User ID=nareen1093;Password=nareen1093;Unicode=True");
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
try
{
OleDbCommand cmd = new OleDbCommand("insert into fingerprint_device values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Registration Success", "Status", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
Form1 form1 = new Form1();
form1.loadButton();
}
catch (Exception ex)
{
MessageBox.Show(ex + "", "Status", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
con.Close();
}
}
}
You are doing couple of things that cause the problem.
First Problem
In your Form2 button click you create a NEW form, call loadButton of this INSTANCE and close Form2. So, any changes made to Form2 is gone now. This happens as execution of form2.ShowDialog(); finishes.
So, you have updated your comboBox, but update happened on a new instance of Form1, and it is disposed without showing the result.
Second Problem
You are adding new values to DB on Form2, but you haven't updated your combo in Form1. Since new instance of Form1 created in Form2 is disposed(refer to First Problem), again, comboBox control in current instance of Form1 is not updated.
Solution
Remove Form1 form1 = new Form1(); and form1.loadButton(); from Form2 button1_Click. Now add loadButton() after form2.ShowDialog();
Now, when Form2 is closed your loadButton() will execute and update combo.
public partial class Form1 : Form
{
OleDbConnection con = new OleDbConnection("Provider=MSDAORA;Data Source=orcl;User ID=nareen1093;Password=nareen1093;Unicode=True");
public Form1()
{
InitializeComponent();
loadButton();
}
public void loadButton ()
{
con.Open();
OleDbDataAdapter oda = new OleDbDataAdapter("select serial_number from fingerprint_device where serial_number like '%'", con);
DataTable dt = new DataTable();
oda.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "serial_number";
comboBox1.SelectedIndex = -1;
con.Close();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.ShowDialog();
loadButton();
}
}
public partial class Form2 : Form
{
OleDbConnection con = new OleDbConnection("Provider=MSDAORA;Data Source=orcl;User ID=nareen1093;Password=nareen1093;Unicode=True");
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
try
{
OleDbCommand cmd = new OleDbCommand("insert into fingerprint_device values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Registration Success", "Status", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex + "", "Status", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
con.Close();
}
}
}

How to update .mdb files with a C# web application?

I am writing a app that must have the ability to :
GUI should be seen on a web interface (Thus I'm using C# Web Application)
Be able to select .mdb files
Add rows
Delete rows
Edit rows
Save everything back to the .mdb file.
I have googled for ages.
I have written a similar application in a normal C# windows form application, I used OLEdb to do everything and it worked fine, it wasn't restricted to only one .mdb file.
In the C# Windows Form app I used Gridview control.
As the Web Application doesn't have Gridview, I used a datagrid.
Here is the code is have so far :
public partial class _Default : System.Web.UI.Page
{
string databasePath = "____________.mdb";
DataTable userTable = new DataTable();
OleDbDataAdapter adapter;
OleDbConnection connection;
OleDbCommand command;
OleDbCommandBuilder builder;
DataSet ds;
DataSet tempDs;
public string DatabaseName = null;
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=";
protected void Page_Load(object sender, EventArgs e)
{
tbDatabasePath.Text = databasePath;
}
protected void btnLoadData_Click(object sender, EventArgs e)
{
ReadRecords();
}
protected void btnGetTables_Click(object sender, EventArgs e)
{
try
{
ddTables.Items.Clear();
ddTables.Text = null;
getTables();
}
catch (Exception ex)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Could not retrieve the Tables');", true);
}
}
private void getTables()
{
string tempstring = "";
string getTConnection = connectionString + databasePath; ;
OleDbConnection myConnection = new OleDbConnection(getTConnection);
myConnection.Open();
DataTable datT = myConnection.GetSchema("Tables");
for (int i = 0; i < datT.Rows.Count; i++)
{
tempstring = datT.Rows[i][2].ToString();
if (tempstring.Contains("MSys"))
{
}
else
{
ddTables.Items.Add(datT.Rows[i][2].ToString());
}
}
myConnection.Close();
}
private void ReadRecords()
{
datagrid.DataSource = null;
OleDbDataReader reader = null;
try
{
connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; " + "Data Source=" + databasePath);
OleDbCommand cmd = new OleDbCommand("Select * FROM " + ddTables.Text, connection);
adapter = new OleDbDataAdapter(cmd);
builder = new OleDbCommandBuilder(adapter);
ds = new DataSet("MainDataSet");
tempDs = new DataSet("TempDataSet");
connection.Open();
adapter.Fill(tempDs);
tempDs.Clear();
tempDs.Dispose();
adapter.Fill(ds, ddTables.Text);
userTable = ds.Tables[ddTables.Text];
}
catch
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Could not load the data');", true);
}
finally
{
if (reader != null) reader.Close();
//if (connection != null) connection.Close();
datagrid.ShowFooter = true;
}
CreateTempTable(0, 10);
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('DONE');", true);
}
private void ReadRecords2()
{
// datagrid.DataSource = null;
OleDbDataReader reader = null;
try
{
connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; " + "Data Source=" + databasePath);
OleDbCommand cmd = new OleDbCommand("Select * FROM " + ddTables.Text, connection);
adapter = new OleDbDataAdapter(cmd);
builder = new OleDbCommandBuilder(adapter);
ds = new DataSet("MainDataSet");
tempDs = new DataSet("TempDataSet");
connection.Open();
adapter.Fill(tempDs);
tempDs.Clear();
tempDs.Dispose();
adapter.Fill(ds, ddTables.Text);
userTable = ds.Tables[ddTables.Text];
}
catch
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Could not load the data');", true);
}
finally
{
if (reader != null) reader.Close();
//if (connection != null) connection.Close();
}
CreateTempTable(0, 10);
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('DONE');", true);
}
private void CreateTempTable(int startRecord, int noOfRecords)
{
try
{
userTable.Rows.Clear();
adapter.Fill(ds, "");
userTable = ds.Tables[""];
}
catch (Exception ex)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Could not load the data in CreateTempTable');", true);
}
datagrid.DataSource = userTable.DefaultView;
datagrid.DataBind();
}
protected void datagrid_RowEditing(object sender, GridViewEditEventArgs e)
{
datagrid.EditIndex = e.NewEditIndex;
ReadRecords();
}
protected void datagrid_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void datagrid_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
adapter.Update(userTable);
}
protected void datagrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
adapter.Update(userTable);
ReadRecords();
}
protected void datagrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
datagrid.EditIndex = -1;
ReadRecords();
}
protected void datagrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int rowToDelete = e.RowIndex;
datagrid.DeleteRow(rowToDelete);
adapter.Update(userTable);
ReadRecords();
}
}
}
It can :
get the .mdb file
get the tables in the file and display it
read the data out of the selected table and display it in the gridview
add the edit delete buttons
Now when I click the edit button, it makes the selected row editable.
But when I click the update button I get "Object reference not set to an instance of an object."
The code worked in the Forms application..
Is there any way the adapter.Update(userTable); will be able to work the same it worked in the forms application?
Can anybody please help me see my problem. If I can only get it to save the changes back to the .mdb file I would be extremely glad.
The behavior of private variables is different in web applications vs WinForms.
In short:
You should initialize the variables (Specifically the adapter) in the the Page_Load method. It will then be not-null and you can use it.
Note: You will also need to store what changes were made in your dataset...
I recommend reading a little more about how it all works...
You can use the Session object for instance, or better yet, check the ViewState
Understanding ASP.NET View State:
http://msdn.microsoft.com/en-us/library/ms972976.aspx
IsPostBack:
http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx

Resources