C# tutorial: add, delete, and edit rows in DataGridView


Using Entity Framework and DataGridView to add, delete, and edit rows of a table in SQL Server Express database

In the previous page, you learnt to use the ADO.NET Framework and DataGridView control to display the Book table stored in the BookStoreDB database of SQL Server Express. In this tutorial, you will learn to use the Framework and DataGridview to add, delete, and edit records of the Book table.

Now let's start creating a new Windows Application project in Visual Studio C# 2010 Express. Then you need to connect to the BookStoreDB database and create ADO.NET Data Model as you did in the page Entity Framework. Then drag and drop a DataGridView control on the form. This DataGridView will be used to display the records, add a new record to the Book table, delete, and edit a record in the Book table.

In the Form1_Load procedure, the initData method is called. The initData method gets records from the Book table, displays the records in the DataGridView, and add button column (delete buttons) to the DataGridView.

private void initData()
{
  var context = new BookStoreDBEntities();
  BindingSource bi = new BindingSource();
  bi.DataSource = context.Books;
  dataGridView1.DataSource = bi;
  dataGridView1.Columns[4].Visible = false; //hide navigation column
  dataGridView1.Columns[0].ReadOnly = true; //make the id column read only

  //add new button column to the DataGridView
  //This column displays a delete icon in each row
  DataGridViewImageColumn delbut = new DataGridViewImageColumn();
  delbut.Image = Image.FromFile(Environment.CurrentDirectory + "/images/delicon.png");
  delbut.Width = 20;
  delbut.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
  dataGridView1.Columns.Add(delbut);

}

datagridview to add, delete, and edit rows of a table

 

The save icon displays instead of the delete icon when the user clicks the header of the new row or clicks the star symbol (*). The save button can be clicked to save the new row to the Book table. Below code is placed in the dataGridView1_RowHeaderMouseClick procedure to change from delete icon to save icon when the user click the stars symbol to add a new row.

if (e.RowIndex == dataGridView1.NewRowIndex)
{
  dataGridView1.Columns[0].ReadOnly = false; //enable id column
  newrow = true; //this flag indicates that the user clicks to add a row in the DataGridView
  //change icon of the new row from delete to save icon
  dataGridView1.Rows[e.RowIndex].Cells[5].Value = Image.FromFile(Environment.CurrentDirectory + "/images/saveicon.png");

}

The code below is placed in the dataGridView1_CellClick procedure to make the delete and save icon buttons workable.

if (e.ColumnIndex == 5 && e.RowIndex >= 0 && newrow != true) //delete icon button is clicked
{
  int bid = int.Parse(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
  DialogResult result = MessageBox.Show("Do you want to delete this record?", "Confirmation", MessageBoxButtons.OKCancel);
if (result == DialogResult.OK)
{
  deleteBook(bid); //delete the record from the Book table
  dataGridView1.Rows.RemoveAt(e.RowIndex); //delete the row from the DataGridView
}

}
else if (e.ColumnIndex == 5 && newrow) //save icon button is clicked
{
  try
{
  int bid = int.Parse(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
  String btitle = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
  String bauthor = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
  int bsupplier = int.Parse(dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString());
  if (bid != 0)
  {
    addBook(bid, btitle, bauthor, bsupplier); //add the new row to the Book table
    newrow = false;
    dataGridView1.Columns[0].ReadOnly = true;
    dataGridView1.Rows[e.RowIndex].Cells[5].Value = Image.FromFile(Environment.CurrentDirectory + "/images/delicon.png");

}
  else
    MessageBox.Show("ID can not be zero or blank", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

}
catch(Exception ex){
    MessageBox.Show("Unable to save the record. The problem might come from the following:\n1. Blank fields\n2. Duplicate record","Error",MessageBoxButtons.OK,MessageBoxIcon.Error );
  }
}

The deleteBook method is called when the user clicks the OK button on the message dialog to confirm that he/she really wants to delete the record.

private void deleteBook(int bid)
{
using (var context = new BookStoreDBEntities())
{
  var bookToDelete = from b in context.Books
    where b.id == bid
    select b;
  foreach (var book in bookToDelete)
    context.DeleteObject(book);
  context.SaveChanges();

}
}

The addBook method is called when the user click the save icon button to add a new record or row to the Book table in BookStoreDB database. Below is the code of the addBook method.

private void addBook(int bid, String btitle, String bauthor, int bsupplier)
{

using (var context = new BookStoreDBEntities())
{

//create Book object

Book bookToAdd = new Book();

  //assign its properties
  bookToAdd.id = bid;
  bookToAdd.title = btitle;
  bookToAdd.author = bauthor;
  bookToAdd.suppplier = bsupplier;
  //add the Book to the object set Books
  context.Books.AddObject(bookToAdd);
  //save change to the database
  context.SaveChanges();

}

}

The DataGridView also allows you to edit data in a row and save change to the record in the Book table. To accomplish this functionality, the below code is written in the dataGridView1_CellValueChanged procedure.

if (!newrow)
{

try
{
  int bid = int.Parse(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
  String btitle = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
  String bauthor = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
  int bsupplier = int.Parse(dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString());
  updateBook(bid, btitle, bauthor, bsupplier);//save change to the Book table

}
catch(Exception ex) {
MessageBox.Show("Unable to save the record. There might be a blank cell. ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

}
}

This is the code of the updateBook method that is called from the code above to make change to the Book table.

private void updateBook(int bid, String btitle, String bautor, int bsupplier)
{
  using (var context = new BookStoreDBEntities())
  {
      //get the book to update
    var bookToUpdate = from b in context.Books
        where b.id == bid
        select b;
  //change the supplier of the book
  foreach (var book in bookToUpdate)
  {
    book.title = btitle;
    book.author = bautor;
    book.suppplier = bsupplier;
}
  //save change to the database
  context.SaveChanges();

}
}

If you like this project and want to download the source code and other related files, click here.

 

 



Comments

lorretadt comment

 lorretadt

you can go here regarding http://www.rasteredge.com/how-to/vb-net-imaging/pdf-redact-text/ .This site has helped me a lot during my vb.net blacking out text in pdf course


2016-05-25
lorretadt comment

 lorretadt

Here is the link for you to vb.net add and delete pages from pdf. Hope this gives you a start on rasteredge page http://www.rasteredge.com/how-to/vb-net-imaging/pdf-delete/


2016-05-20
lorretadt comment

 lorretadt


You can download and try this interesting high quality page for c# how to remove watermark from pdf image on http://www.rasteredge.com/how-to/csharp-imaging/pdf-image-remove/


2016-04-20
lorretadt comment

 lorretadt

You can also read an interesting c# acrobat remove text from pdf on this page http://www.rasteredge.com/how-to/csharp-imaging/pdf-text-edit-delete/


2016-04-20
lorretadt comment

 lorretadt

c# add and remove pages from pdf file online on page http://www.rasteredge.com/how-to/csharp-imaging/pdf-extract-pages/


2016-04-14
c# add and delete pages from p comment

 c# add and delete pages from p

c# add and delete pages from pdf on this page http://www.rasteredge.com/how-to/csharp-imaging/pdf-delete/


2016-04-13
lorretadt comment

 lorretadt

c# add and delete pages from pdf on this page http://www.rasteredge.com/how-to/csharp-imaging/pdf-delete/


2016-04-13
c# add and delete pages from p comment

 c# add and delete pages from p

c# add and delete pages from pdf on this page http://www.rasteredge.com/how-to/csharp-imaging/pdf-delete/


2016-04-13
seo comment

 seo

Hello Web Admin, I noticed that your On-Page SEO is is missing a few factors, for one you do not use all three H tags in your post, also I notice that you are not using bold or italics properly in your SEO optimization. On-Page SEO means more now than ever since the new Google update: Panda. No longer are backlinks and simply pinging or sending out a RSS feed the key to getting Google PageRank or Alexa Rankings, You now NEED On-Page SEO. So what is good On-Page SEO?First your keyword must appear in the title.Then it must appear in the URL.You have to optimize your keyword and make sure that it has a nice keyword density of 3-5% in your article with relevant LSI (Latent Semantic Indexing). Then you should spread all H1,H2,H3 tags in your article.Your Keyword should appear in your first paragraph and in the last sentence of the page. You should have relevant usage of Bold and italics of your keyword.There should be one internal link to a page on your blog and you should have one image with an alt tag that has your keyword....wait there's even more Now what if i told you there was a simple Wordpress plugin that does all the On-Page SEO, and automatically for you? That's right AUTOMATICALLY, just watch this 4minute video for more information at. <a href="http://www.SEORankingLinks.com">Seo Plugin</a>
seo http://www.SEORankingLinks.com/


2016-03-24
dfdff comment

 dfdff

hjjjjjjj


2016-01-02
john comment

 john

what is BookStoreDBEntities()
is deletebook part?


2015-03-06
Ninguno comment

 Ninguno

ninguno


2015-03-02
chandran comment

 chandran

Hi
can we use combo box inside datagridview
by clicking combo box I want to get selected value
Thanks and Regards
Chandran


2014-07-15
Anong comment

 Anong

Thank and Regard


2014-03-03
Dara comment

 Dara

You should use Visual Studio C# 2010 Express or Visual Studio 2010 instead of Visual Studio 2008.
The error "not implicitly convert type string to int" indicates that the type of a variable used in the code does not match the type of the column in SQL Server database.


2014-03-01
Anong comment

 Anong

hi sir I try it with visual studio 2008 and SQL SERVER 2008 R2 but it missing
-.AddObject
- bookToAdd.id = bid; and bookToAdd.supplier = bsupplier;
it show can not implicitly convert type string to int. could you help to resolve me please?


2014-02-28
CAPTCHA image




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.