Currently I am having issues with updating values in a SQL Server database.
I am working on a project that stores students names, dates of birth and genders in a database and is able to be edited and updated via windows forms. Browsing the data so far works fine, however when a value is changed on the form and the update button is clicked the program crashes with a
NullReferenceException was unhandled. Object reference not set to an instance of an object.
error and I am currently at a loss as to what is causing it.
Currently I have a DBConnector class which opens up the connection to the database and the dataset and passes it to the windows form which contains textboxes to show the values and navigational buttons to browse the data. (Below is the code for both the class and the windows form, I hope that can explain things better than I have).
The DBConnector.cs class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace StudentRecords
{
public class DBConnector
{
//Properties
//connection object
private System.Data.SqlClient.SqlConnection Conn;
//dataset object
private StudentsDataSet Ds1;
//dataadapter object
private System.Data.SqlClient.SqlDataAdapter Da;
//constructors
public DBConnector()
{
//call initialisation
init();
}
//Methods
//initialisation method
public void init()
{
//create the memory space for the connection object
Conn = new System.Data.SqlClient.SqlConnection();
//create the memory space for the dataset
Ds1 = new StudentsDataSet();
//set the connection string to the location of our database file
Conn.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Students.mdf;Integrated Security=True;User Instance=True";
//open the conenction
Conn.Open();
//create a query to get all the records from the table
string query = "SELECT * from Studentstbl";
//create the data adapter for the database
Da = new System.Data.SqlClient.SqlDataAdapter(query, Conn);
//use it to fill the dataset as the first parameter the second is a name for the table we use later on
Da.Fill(Ds1, "Students");
//close the connection
Conn.Close();
System.Windows.Forms.MessageBox.Show("Database connection Open", "Success");
}
public StudentsDataSet DBDataSet
{
get
{
return Ds1;
}
}
//update method
public void UpdateDB(DataSet ds, string table)
{
//create a command builder to reconnect to the database
System.Data.SqlClient.SqlCommandBuilder cb;
//set the comamnd builder to be our existing dataadapter
cb = new System.Data.SqlClient.SqlCommandBuilder(Da);
Da.Update(ds, table);
}
}
}
The studentdetails.cs Windows Form
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;
namespace StudentRecords
{
public partial class studentdetails : Form
{
DataSet StudentDataSet;
//set variables for limit
int Limit = 0;
int current = 0;
public studentdetails()
{
InitializeComponent();
}
public studentdetails(DataSet ds)
: this()
{
StudentDataSet = ds;
//set the limit of records we can navigate
Limit = StudentDataSet.Tables["Students"].Rows.Count;
NavigateRecords();
}
public studentdetails(DBConnector db) : this()
{ }
public studentdetails(DBConnector db, int sRow) : this(db)
{
current = sRow;
NavigateRecords();
//turn on editing
plEdit.Visible = true;
//set our local dataset object to point to the passed in one
DBConnection = db;
StudentDataSet = db.DBDataSet;
Limit = StudentDataSet.Tables["Students"].Rows.Count;
NavigateRecords();
}
//navigate records function to move through the records
public void NavigateRecords()
{ //create a datarow object and set it to be the first row in the dataset
DataRow dRow = StudentDataSet.Tables["Students"].Rows[current];
//set the form text to add the current record number
this.Text += " for record " + dRow.ItemArray.GetValue(0).ToString();
//fill the text boxes with the database values
txtFirstName.Text = dRow.ItemArray.GetValue(1).ToString();
txtMiddleName.Text = dRow.ItemArray.GetValue(2).ToString();
txtLastName.Text = dRow.ItemArray.GetValue(3).ToString();
txtDOB.Text = dRow.ItemArray.GetValue(4).ToString();
txtgender.Text = dRow.ItemArray.GetValue(5).ToString();
}
//update the label for the dtatbase
private void UpdateCount()
{
txtCount.Text = (current + 1).ToString() + " of " + Limit.ToString();
}
private void btn_next_Click(object sender, EventArgs e)
{
if (current != Limit - 1)
{
current++;
NavigateRecords();
}
else
{
MessageBox.Show("Last Record", "Information", 0, MessageBoxIcon.Information);
}
}
private void btn_prev_Click(object sender, EventArgs e)
{
if (current > 0)
{
current--;
NavigateRecords();
}
else
{
MessageBox.Show("First Record", "Information", 0, MessageBoxIcon.Information);
}
}
private void btn_Last_Click(object sender, EventArgs e)
{
if (current != Limit - 1)
{
current = Limit - 1;
NavigateRecords();
}
}
private void btn_first_Click(object sender, EventArgs e)
{
if (current != 0)
{
current = 0;
NavigateRecords();
}
}
public DBConnector DBConnection { get; set; }
private void btn_save_Click(object sender, EventArgs e)
{
{
//create a new datarow
DataRow dRow = StudentDataSet.Tables["Students"].NewRow();
//set the data to be the values from the text boxes
dRow[1] = txtFirstName.Text;
dRow[2] = txtMiddleName.Text;
dRow[3] = txtLastName.Text;
dRow[4] = txtDOB.Text;
dRow[5] = txtgender.Text;
//add the row to our dataset
StudentDataSet.Tables["Studentstbl"].Rows.Add(dRow);
//increase the limit as we have a new record
Limit++;
//move to the newly entered Student
current = Limit - 1;
DBConnection.UpdateDB(StudentDataSet, "Students");
MessageBox.Show("Record Saved", "Information", 0, MessageBoxIcon.Information);
NavigateRecords();
}
}
private void btn_update_Click(object sender, EventArgs e)
{
{ //get the current row
DataRow dRow = StudentDataSet.Tables["Students"].Rows[current];
//set the dataset values to those in the textboxes
dRow[1] = txtFirstName.Text;
dRow[2] = txtMiddleName.Text;
dRow[3] = txtLastName.Text;
dRow[4] = txtDOB.Text;
dRow[5] = txtgender.Text;
//call the update method in our DB connector class
DBConnection.UpdateDB(StudentDataSet, "Students");
//display a message box
MessageBox.Show("Record updated", "Information", 0, MessageBoxIcon.Information);
NavigateRecords();
}
}
}
}
The database is called Students.mdf and the table is called Studentstbl, the error is thrown on line:
DBConnection.UpdateDB(StudentDataSet, "Students");
I know its probably something stupid I have missed out but I am fairly new with C# coding so forgive me if this is the case :)
Edit: I should also point out that studentdetails is a secondary form with the main form simply containing a button which opens that form in it, it simple contains the code:
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;
namespace Coursework3
{
public partial class Form1 : Form
{
DBConnector Students;
public Form1()
{
InitializeComponent();
//intansiate the object in memory
Students = new DBConnector();
}
private void btnstudentdetails_Click(object sender, EventArgs e)
{
new studentdetails(Students.DBDataSet).ShowDialog();
}
}
}
Related
im trying to learn c# and sql server and i have some problems with them in n-th layer projects.
so i created a 3-layer project:
1-DataAccessLayer
2-CodeLayer
3-UILayer
i connect all layers with references.
in DataAccessLayer there is a class with this code below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace DataAccessLayer
{
public class DataContent
{
SqlConnection cnn;
SqlCommand cmd;
SqlDataAdapter sa;
DataTable dt;
public DataContent()
{
cnn = new SqlConnection();
cmd = new SqlCommand();
sa = new SqlDataAdapter();
cmd.Connection = cnn;
sa.SelectCommand = cmd;
}
public void connect()
{
cnn.ConnectionString = "Data Source=.;Initial Catalog=testDB;Integrated Security=True";
cnn.Open();
}
public void disConnect()
{
cnn.Close();
}
public void runCommend(string query)
{
cmd.CommandText = query;
cmd.ExecuteNonQuery();
}
public DataTable SELECT(string query)
{
cmd.CommandText = query;
dt = new DataTable();
sa.Fill(dt);
return dt;
}
}
}
in CodeLayer there is a class whit this code below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using DataAccessLayer;
namespace codeLayer
{
public class Data : DataContent
{
public string userName;
public string userPass;
public string uName;
public string uFamily;
public string uTell;
public DataTable validation()
{
base.connect();
string query = "select * from tblData where userName = '{0}' and userPass = '{1}'";
query = String.Format(query, userName, userPass);
DataTable dt = base.SELECT(query);
base.disConnect();
return dt;
}
public void updateTable()
{
base.connect();
string query = "update tblData set userPass = '{0}', uName = N'{1}', uFamily = N'{2}', uTell = '{3}' where userName = '{4}'";
query = String.Format(query, userPass, uName, uFamily, uTell, userName);
base.runCommend(query);
base.disConnect();
}
}
}
my form in UILayer like this:
enter image description here
and i have table with one record that i add manually like this:
enter image description here
and i set all fields in table to not null
there is 2 click event in form:
1-btnSearch_click :
private void btnSearch_Click(object sender, EventArgs e)
{
Data a = new Data();
a.userName = txtUserNameSearch.Text;
a.userPass = txtPassWordSearch.Text;
DataTable newDT = a.validation();
if (newDT != null && newDT.Rows.Count > 0)
{
txtName.Text = newDT.Rows[0]["uName"].ToString();
txtFamily.Text = newDT.Rows[0]["uFamily"].ToString();
txtUserName.Text = newDT.Rows[0]["userName"].ToString();
txtPassWord.Text = newDT.Rows[0]["userPass"].ToString();
txtTell.Text = newDT.Rows[0]["uTell"].ToString();
}
else
{
MessageBox.Show("sorry...! cant finde user with inserted info.", "user not found", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
2-btnEdit_Click:
private void btnEdit_Click(object sender, EventArgs e)
{
Data a = new Data();
a.userName = txtUserName.Text;
a.userPass = txtPassWord.Text;
a.uName = txtName.Text;
a.uFamily = txtFamily.Text;
a.uTell = txtTell.Text;
try
{
a.updateTable();
MessageBox.Show("edit information was success.", "successfull", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("failed to update information", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
so when i run it for test, search function is works and get data from table and puts them in text boxes.
but problem is when i try to edit. after search i clear one of the text boxes and click edit and its just work. Should not i get some exeptions here???
after that i check the table and the field that i cleared before is empty in table like picture below:
enter image description here
whats happning here?? am i doing something wrong?? what did I missed??
please help me to solve this problem.
ps: im sorry for my bad english.
I am storing data from MS Access database in DataTable and then displaying it on DataGridView.
All the columns are showing except the image column. I have stored the image in the database as "OLE Object". I want to display image in the last column, though when the form loads I get error:
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 ShowDataInDatagridviewFromAccessDatabase
{
public partial class Form1 : Form
{
OleDbConnection acceddDatabaseConnection = null;
string connectionSttring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Authentic\Documents\Database1.accdb";
string sqlQuery = "SELECT * FROM Table1";
public Form1()
{
acceddDatabaseConnection = new OleDbConnection(connectionSttring);
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
acceddDatabaseConnection.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(sqlQuery, acceddDatabaseConnection);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
dataGridView1.DataSource = dataTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (acceddDatabaseConnection != null)
{
acceddDatabaseConnection.Close();
}
}
}
}
}
//Function for retrieving data from ms access database and displaying it on DataGridView
public void populateDataGridView()
{
//First, clear all rows before populating datagridview with data from MS Access Database. Check if datagridview rows are empty before clearing.
if (dataGridView1.Rows.Count > 0)
{
dataGridView1.Rows.Clear();
}
try
{
accessDatabaseConnection.Open();
//OleDbDataAdapter adapter = new OleDbDataAdapter(sqlQuery, acceddDatabaseConnection);
OleDbCommand command = new OleDbCommand(selectDataFromMSAccessDatabaseQuery, accessDatabaseConnection);
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[8].GetType());
dataGridView1.Rows.Add(reader[0].ToString(), reader[1].ToString(), reader[2].ToString(), reader[3].ToString(), reader[4].ToString(), reader[5].ToString(), reader[6].ToString(), reader[7].ToString(), (byte[])reader[8]);
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
finally
{
//Finally Close MS Access Database Connection
if (accessDatabaseConnection != null)
{
accessDatabaseConnection.Close();
}
}
}
Source :
http://mauricemuteti.info/how-to-connect-to-access-database-and-display-data-and-images-in-datagridview-in-c-sharp-windows-application/
I want to allow user to add rows but the blank row must be in he first position to let the user enter data without scroll down each time to insert a new row ?!
This is how I add the rows in the datagridview :
using System;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Windows.Forms;
namespace Parc_Automobile
{
public class SqlHelper
{
private const string ConnectionString =
"Data Source=KIM;Initial Catalog=TestingBlank;Integrated Security=True";
private readonly DataGridView _dgv;
private BindingSource _bindingSource;
private DataTable _dataTable;
private string _selectQueryString;
private SqlConnection _sqlConnection;
private SqlDataAdapter _sqlDataAdapter;
protected SqlHelper(DataGridView dgv)
{
_dgv = dgv;
}
//display a table in datagridview
public void ShowTable(String tableName)
{
_sqlConnection = new SqlConnection(ConnectionString);
_sqlConnection.Open();
_selectQueryString = "SELECT * FROM " + tableName;
_sqlDataAdapter = new SqlDataAdapter(_selectQueryString, _sqlConnection);
var sqlCommandBuilder = new SqlCommandBuilder(_sqlDataAdapter);
_dataTable = new DataTable();
_sqlDataAdapter.Fill(_dataTable);
_bindingSource = new BindingSource {DataSource = _dataTable};
var tempRow = this._dataTable.NewRow();
this._dataTable.Rows.InsertAt(tempRow, 0);
_dgv.DataSource = _bindingSource;
_sqlConnection.Close();
}
//Search In datagridview using input of users
public void SearchTable(String SearchText, String columnNameToSearch, int type)
{
try
{
var filterBuilder = "";
switch (type)
{
case TEXT_COLUMN:
filterBuilder = columnNameToSearch + " LIKE '" + SearchText + "%'";
break;
case NUMERIC_COLUMN:
filterBuilder = columnNameToSearch + " = '" + SearchText + "'";
break;
}
var bs = new BindingSource
{
DataSource = _dgv.DataSource,
Filter = filterBuilder
};
_dgv.DataSource = bs;
}
catch (Exception e)
{
// ignored
}
}
public void DeleteRow()
{
if (_dgv.CurrentRow != null) _dgv.Rows.RemoveAt(_dgv.CurrentRow.Index);
_sqlDataAdapter.Update(_dataTable);
}
public void SaveChanges(Label label)
{
try
{
_sqlDataAdapter.Update(_dataTable);
label.Text = "Changement a été effectué avec succès.";
}
catch (Exception e)
{
MessageBox.Show("" + e);
}
}
}
}
When you add a new row use the Insert method instead of Add. Insert allows to specify the index for the new row. Set the index to 0:
this.dataGridView1.Rows.Insert(0,new DataGridViewRow());
EDIT I
Adjusting the answer to your comment: if you are using a binding to a data source you have to create a new row using the data source. Then you insert it at specified position. Let's say that you have myDataSet data source with a Log table in it. This code will create a new row and insert it as the first row:
var tempRow = this.myDataSet.Log.NewRow();
this.myDataSet.Log.Rows.InsertAt(tempRow, 0);
Your DataGridView will be updated appropriately.
EDIT II
You will get exception if you try, for instance, to assign data type different than a column type in your table. Say the ID column is int but you try to add string. To handle data errors you have to handle the DataError event. Below an example using your code.
protected SqlHelper(DataGridView dgv)
{
_dgv = dgv;
_dgv.DataError += _dgv_DataError;
}
void _dgv_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
if (e.Exception != null)
{
MessageBox.Show(string.Format("Incorrect data: {0}", e.Exception.Message) );
e.Cancel = false;
// handle the exception
}
}
I have a form (customersForm) displaying a datagridview with customer information. And a second form (viewForm) which allows the user to view, edit,delete and update selected datagridview row. When I click update, or delete i'd like the datagridview on the customerForm to refresh displaying the updated data. How can I do this from a button click?
This is the viewForms complete code:
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.SqlServerCe;
namespace Lewis_Warby_Airbrushing
{
public partial class viewForm : Form
{
DataRowView Data = null;
public viewForm(DataRowView dr)
{
InitializeComponent();
Data = dr;
}
private void closeBTN_Click(object sender, EventArgs e)
{
this.Close();
}
private void viewForm_Load(object sender, EventArgs e)
{
refTxt.Text = Data["Reference"].ToString().Trim();
firstTxt.Text = Data["First Name"].ToString().Trim();
surenameTxt.Text = Data["Surename"].ToString().Trim();
address1Txt.Text = Data["Address Line 1"].ToString().Trim();
address2Txt.Text = Data["Address Line 2"].ToString().Trim();
countyTxt.Text = Data["County"].ToString().Trim();
postTxt.Text = Data["Post Code"].ToString().Trim();
contactTxt.Text = Data["Contact Number"].ToString().Trim();
emailTxt.Text = Data["Email Address"].ToString().Trim();
}
private void deleteBTN_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Customer information will be perminantly deteled. Do you with to continue? ", "Confirm Delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
string constring = #"Data Source=|DataDirectory|\LWADataBase.sdf";
string Query = "delete from customersTBL where Reference ='" + this.refTxt.Text + "';";
SqlCeConnection conDataBase = new SqlCeConnection(constring);
SqlCeCommand cmdDataBase = new SqlCeCommand(Query, conDataBase);
SqlCeDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("Customer information has been deleted", "Deleted Sucessfully");
while (myReader.Read())
{
}
MessageBox.Show("Please exit the Customers window and re-open to update the table");
this.Close();
//displays a system error message if a problem is found
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void editBTN_Click(object sender, EventArgs e)
{
bool notEditable = true;
if (editBTN.Text == "Update")
{
int UserID = Convert.ToInt32(refTxt.Text);
UpdateDataBase( UserID );
editBTN.Text = "Edit";
deleteBTN.Visible = true;
notEditable = true;
}
else
{
deleteBTN.Visible = false;
editBTN.Text = "Update";
deleteBTN.Visible = false;
notEditable = false;
}
firstTxt.ReadOnly = notEditable;
surenameTxt.ReadOnly = notEditable;
address1Txt.ReadOnly = notEditable;
address2Txt.ReadOnly = notEditable;
countyTxt.ReadOnly = notEditable;
contactTxt.ReadOnly = notEditable;
emailTxt.ReadOnly = notEditable;
postTxt.ReadOnly = notEditable;
}
private void UpdateDataBase(int customerID)
{
if (MessageBox.Show("Customer information will be updated. This change cannot be undone. Are you sure you want to continue? ", "Confirm Edit", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
string constring = #"Data Source=|DataDirectory|\LWADataBase.sdf";
string Query = #"update customersTBL set [First Name] = #fname,
surename = #sur, [Address Line 1] = #addr1,
[Address Line 2] = #addr2, County = #county,
[Post Code] = #pcode, [Email Address] = #mail, [Contact Number] = #ctNo
WHERE Reference = #id";
using (SqlCeConnection conDataBase = new SqlCeConnection(constring))
using (SqlCeCommand cmdDataBase = new SqlCeCommand(Query, conDataBase))
{
try
{
conDataBase.Open();
cmdDataBase.Parameters.AddWithValue("#fname", this.firstTxt.Text);
cmdDataBase.Parameters.AddWithValue("#sur", this.surenameTxt.Text);
cmdDataBase.Parameters.AddWithValue("#addr1", this.address1Txt.Text);
cmdDataBase.Parameters.AddWithValue("#addr2", this.address2Txt.Text);
cmdDataBase.Parameters.AddWithValue("#county", this.countyTxt.Text);
cmdDataBase.Parameters.AddWithValue("#pcode", this.postTxt.Text);
cmdDataBase.Parameters.AddWithValue("#mail", this.emailTxt.Text);
cmdDataBase.Parameters.AddWithValue("#ctNo", this.contactTxt.Text);
cmdDataBase.Parameters.AddWithValue("#id", customerID);
int rowsUpdated = cmdDataBase.ExecuteNonQuery();
if (rowsUpdated == 0)
MessageBox.Show("No customer found to update");
MessageBox.Show("Customer information sucessfully updated", "Update Sucessfull");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
The complete code for customerForm:
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.SqlServerCe;
namespace Lewis_Warby_Airbrushing
{
public partial class customerForm : Form
{
public customerForm()
{
InitializeComponent();
}
public void customerForm_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'lWADataBaseDataSet.customersTBL' table. You can move, or remove it, as needed.
timer1.Start();
this.lWADataBaseDataSet.EnforceConstraints = false;
this.customersTBLTableAdapter.Fill(this.lWADataBaseDataSet.customersTBL);
}
private void viewBTN_Click(object sender, EventArgs e)
{
int selectedRowIndex = customersTBLDataGridView.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = customersTBLDataGridView.Rows[selectedRowIndex];
viewForm frm2 = new viewForm((DataRowView)selectedRow.DataBoundItem);
frm2.ShowDialog();
}
addForm addForm = new addForm();
private void addBTN_Click(object sender, EventArgs e)
{
if (addForm == null || addForm.IsDisposed == true)
addForm = new addForm();
addForm.ShowDialog();
this.customersTBLTableAdapter.Fill(this.lWADataBaseDataSet.customersTBL);
}
int count = 0;
private void timer1_Tick(object sender, EventArgs e)
{
count = customersTBLBindingSource.Count;
statusLBL.Text = "You currently have "+count.ToString()+" customer(s) stored in this database";
}
searchForm searchForm = new searchForm();
private void searchBTN_Click(object sender, EventArgs e)
{
if (searchForm == null || searchForm.IsDisposed == true);
searchForm = new searchForm();
searchForm.ShowDialog();
}
}
}
There is a lot you don't specify in your question, but let's assume this scenario:
When customerView is shown, you call the database to fill a DataGridView with customer details. At some point you either dbl-click on a DGV row, or you select a row and click a button, and then show viewForm, passing in the data in the currently selected row. Again, you don't specify how this is done, but let's assume you pass in a Data Transfer Object of some kind.
Once done editing, you click a button, save the changes to the database, then close viewForm.
According to your comments this is the general workflow you have in your application now.
In this case, you can simply re-fetch the data, as you did when first showing customerView when the viewForm.ShowDialog() method returns.
Unless there is something else I don't get, this can be easily done like this:
//customerForm
private void button1_Click(object sender, EventArgs e)
{
ViewFormClass viewForm = new ViewFormClass();
viewForm.SetCustomerData(dataObject);
viewForm.ShowDialog(); // will stop here waiting for viewForm to close
this.FetchCustomerData();
}
where FetchCustomerData() is the same method you called when opening customerView. In there you would typically fetch the data and bind it to controls.
Cheers
EDIT:
As per your own code, with a simple modification:
private void viewBTN_Click(object sender, EventArgs e)
{
int selectedRowIndex = customersTBLDataGridView.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = customersTBLDataGridView.Rows[selectedRowIndex];
viewForm frm2 = new viewForm((DataRowView)selectedRow.DataBoundItem);
frm2.ShowDialog();
this.customersTBLTableAdapter.Fill(this.lWADataBaseDataSet.customersTBL);
}
i want to delete the row of data from the database, currently i can delete the row of data by clicking on the delete button, but the database Table is not updated, how do i do so?
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;
namespace project
{
public partial class frmTestPrint : Form
{
public frmTestPrint()
{
InitializeComponent();
}
private void frmTestPrint_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'usersDataSet1.Booking' table. You can move, or remove it, as needed.
this.bookingTableAdapter.Fill(this.usersDataSet1.Booking);
}
private void btnDelete_Click(object sender, EventArgs e)
{
dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
}
}
}
private void Delete()
{
int i = 0;
con1 = getConnection();
con1.Open();
SqlCommand storedProcedureCommand = con1.CreateCommand();
storedProcedureCommand.CommandType = CommandType.Text;
storedProcedureCommand.CommandText = "DELETE FROM name of your table WHERE pkeyID = #pkeyID";
SqlParameter inparam2 = new SqlParameter("#pkeyID", SqlDbType.Int);
inparam2.Direction = ParameterDirection.Input;
inparam2.Value = Convert.ToInt32(dataGridView2.Rows[i].Cells[0].Value);
storedProcedureCommand.Parameters.Add(inparam2);
storedProcedureCommand.ExecuteNonQuery();
}
This is only to delete one at a time. I am still working on multiple deletes.
if (MessageBox.Show("Sure you wanna delete?", "Warning", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
{
//get the index from the dataGridView
int rowIndex = table1DataGridView.CurrentCell.RowIndex;
//Remove from both the actual database & datagridview
table1BindingSource.RemoveAt(rowIndex);
//update table 1
this.table1TableAdapter.Update(this.maquinasDataSet.Table1);
//load table 1
this.table1TableAdapter.Fill(this.maquinasDataSet.Table1);
}
You're not actually impacting the database at all. Perhaps this will help:
How to delete a selected DataGridViewRow and update a connected database table?
Have you explored the .Update method you get with the TableAdapter? I think that should cover what you're after. http://msdn.microsoft.com/en-us/library/bz9tthwx(v=vs.100).aspx
Does this work:
private void btnDelete_Click(object sender, EventArgs e)
{
dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
this.bookingTableAdapter.Update(this.usersDataSet1.Booking);
}
if that doesn't work, you're going to have to come back w/ an error message or hopefully someone who knows what they're doing can come bail me out...
Delete a value from the data grid using DataGridviewBUttonColumn
private void delete_record()
{
if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
{
try
{
//am taking connection string using a class called "sqlconnection_imventory()"
SqlConnection conn = Connection.sqlconnection_imventory();
//Cell[0] is my button column & Cell[1] is SID coumn
string a = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
string sql = "DELETE FROM grades WHERE SID='" + a + "'";
conn.Open();
SqlCommand delcmd = new SqlCommand(sql, conn);
delcmd.Connection = conn;
delcmd.ExecuteNonQuery();
conn.Close();
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
MessageBox.Show("deleted");
}
catch (Exception)
{
throw;
}
}
}