C# ASP.NET MVC

  1. Download Visual Studio?
  2. Login Instructions
  3. CRUD Operation using Ajax/Json Code
  4. Read Data from database and Show in HTML Table using Ajax/JSON
  5. Select2 ComboBox
  6. Show Current Date in Input Type date when view is loaded
  7. Assign Date to Html Input Type Date return from database usign Ajax/JSON
  8. Show Date in HTML return from database usign Ajax/JSON
  9. Bootstrap Model
  10. Cache in Asp.net MVC
  11. Print Report
  12. Master Page
  13. LogOut (when Cache is used)

2. Login Code and Instructions

Keep this code in web.config just after this code:
 <authentication mode="Forms">
                        <forms loginurl="Home/Login1" defaulturl="~/" timeout="30" slidingexpiration="true"></forms>
                    </authentication>    

Login View
@using (Html.BeginForm("Login", "Admin", new { returnUrl = Request.QueryString["returnUrl"] }, FormMethod.Post))
{ --Html Design here }

Code When click on Login Button
 if (db.AccountManagements.Any(x => x.userName1 == username1 && x.password1 == PWrod && x.active == "Yes") == true)
                {
                    //return Role
                    FormsAuthentication.SetAuthCookie(username1, false);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        //goto menu
                        return RedirectToAction("", "");

                    }
                }
                else
                {
                    ViewBag.messag = "Invalid Username | Password Or Temporarily ";
                    return View();
                }

3. Create / Read / Update / Delete data using Jquery/Ajax/Json

View Code
 $.get("/FeesC/Delete_InvoiceNo", { Invo: $("#InvoiceNo5").val() }, function (data) 
    {           
                $("#messageSF").text(data);            
        });
Controller Code
 public JsonResult ReturnData(int Invo)
        {           
var a=db.FeesSaveds.Find(Invo);
                return Json(a, JsonRequestBehavior.AllowGet);
                              
        }

4. Read Data from database and Show in HTML Table using Ajax/JSON

HTML Code

<div style="overflow-y:auto;width:100%;">
    <p id="totalrecord" style="margin:0px;" class="float-end"></p>
    <table class="table table-bordered" id="mytable" cellpadding="0" cellspacing="0">
        <thead style="padding:0px;">
            <tr style="padding: 0px; text-align: center; background-color: #80dfff; border: 1px solid black;">
                <th style="padding:0px;">S.No</th>
                <th style="padding:0px;">Type</th>
                <th style="padding:0px;">Account Title</th>
                <th style="padding:0px;">Code</th>
                
                <th style="padding:0px;">Actions</th>
                <th style="padding:0px;">SMS</th>
            </tr>
        </thead>
    </table>
</div>
JQuery Code
 $("#mytable tr:gt(0)").remove();
            $.get("/AdminJson/loadaccounts", { option: txt, search: search1 }, function (data) {

                var RowCount = 0;
                var row;
                $.each(data, function (i, v1) {
                    RowCount += 1;
                    row += "<tr style='padding:0px; margin:0px;text-align:center;border:1px solid black;'><td style='padding:0px; margin:0px;border:1px solid black;'> " + RowCount + " </td> <td style='padding:0px; margin:0px;border:1px solid black;'>" + v1.typee + "</td> <td style='padding:0px; margin:0px;border:1px solid black;'>" + v1.name + "</td> <td style='padding:0px; margin:0px;border:1px solid black;'>" + v1.code + "</td><td style='padding:0px; margin:0px;border:1px solid black;'>" + v1.AdminId + "</td><td style='padding:0px; margin:0px;border:1px solid black;'> <> <a title='Edit Record' style=' font-size:18px;margin-left:10px;' onclick=Edit2(" + v1.id + ") ><span class='fa fa-edit'></span></a>  <a title='Delete Record' style='margin-left:10px;  font-size:18px;' onclick=Delete1(" + v1.id + ") ><span class='fa fa-trash'></span></a> </td><td>< ></td ></tr > ";
                });
                $("#mytable").append("<tbody style='margin:0px; padding:0px;'> " + row + "</tbody>");
                $("#totalrecord").text("Total Accounts : " + RowCount);
                $("#divLoader1").hide();
            });
Controller Code
 public JsonResult loadaccounts(string option,string search)
        {
 var a = db.accounts.Where(x => x.AdminId == AdminId && x.BranchId == branchId).OrderByDescending(x => x.dte).Take(50).ToList();
return Json(a, JsonRequestBehavior.AllowGet);
}

5. Select2, Searchable ComboBox

1. First Download Library
Download Select2 Library
Note: Consider only dist folder (ignore other files)

2. Reference Library in your project
Reference these three files in the view page, but make sure the JQuery file must be referenced once, if you reference JQuery file in master page then the Select2 will not work keep these three files in every view page, where you need to use Select2

<script src="~/Scripts/jquery-1.8.0.min.js"></script>
<link href="~/Scripts/SmartCombo/css/select2.min.css" rel="stylesheet" />
<script src="~/Scripts/SmartCombo/js/select2.min.js"></script>

3. HTML Code
<select class="js-example-basic-single" id="bcategorycombo" style="width: 100%; ">                    
                </select>

4. Jquery Code (to load items to combobox from database)


<script>
    $(document).ready(function () {
      
        LoadCategory();        
        $("#bcategorycombo").select2({ theme: "classic" });               
        $("#bcategorycombo").css({ "font-size": "40px" });

    });

 function LoadCategory() {

        $.get("/COmboJson/loadCategory", {}, function (data) {
            var itemZ = "";
            $.each(data, function (i, v1) {
                
                itemZ += '<option value="' + v1.category + '">' + v1.category + '</option>';
            });
            $("#bcategorycombo").append(itemZ);
        });
    }
</script>

5. Controller Code
/controller code
 public JsonResult loadCategory()
        {
            int AdminId = rt.Return_MainID(User.Identity.Name);
            int branchid = rt.Return_BranchId(User.Identity.Name);           
            var ab = db.category1.Where(x => x.AdminId == AdminId && x.BranchId == branchid).ToList();
            return Json(ab, JsonRequestBehavior.AllowGet);
        }

6. Show Current Date in Input Type date when view is loaded

HTML Code
<input type="date" id="bdate2" class="form-control" value=@ViewBag.dateCurrent />

Controller Code
Publick ActionResult index()
{
ViewBag.dateCurrent = rt.Return_DateHTML(DateTime.Now);

}

string mm3, dd3;
        public string Return_DateHTML(DateTime dt)
        {

            if (dt.Month < 10)
            {
                mm3 = "0" + dt.Month;
            }
            else
            {
                mm3 = dt.Month.ToString();
            }
            if (dt.Day < 10)
            {
                dd3 = "0" + dt.Day;
            }
            else
            {
                dd3 = dt.Day.ToString();
            }

            return (dt.Year + "-" + mm3 + "-" + dd3); //
        }

7. Assign Date to Html Input Type Date return from database usign Ajax/JSON

Create Function in Jquery and use the last line to assign the value
JQuery Code
//Jquery Code
   function dateFormatHtml(d) {
        console.log(d);
        return d.getFullYear()+ "-"
        + ((d.getMonth() + 1) + "").padStart(2, "0")
            + "-" + (d.getDate() + "").padStart(2, "0");
    }
                

$("#ToDate").val(dateFormatHtml(new Date(parseInt((v1.ToDate).match(/\d+/)[0]))));

8. Show Date in HTML return from database usign Ajax/JSON

JQuery Code
function dateFormat(d) {
        console.log(d);
        return (
            (d.getDate() + "").padStart(2, "0")
            + "/" + (d.getMonth() + 1) + "").padStart(2, "0")
            + "/" + d.getFullYear();
    }



dateFormat(new Date(parseInt((v1.datee).match(/\d+/)[0])))

9. Show a Model in Asp.net MVC

HTML Code
<div class="modal fade" id="myModelListInvoices30" role="dialog">
        <div class="modal-dialog" style="max-width: 70%!important;" role="document">

            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Last 50 Saved Invoices</h4>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">

                    

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
            
        </div>
    </div>
JQuery Code (open model from JQuery)
new bootstrap.Modal($('#myModelListInvoices30')).show();
OR
$('#myModal').modal('show')

10. Show a Model in Asp.net MVC

Waht is Cache? It prevent the application to retreive all the html/images etc from server again and again, it saves the data in client browser, and when it is required, the data is retrieved from the client browser, This process increase the application performance

Keep this line above controller, all views of the controller will be cached

Keep this line above view, that view will be cached


Controller Code
[OutputCache(Duration = 10800, Location = System.Web.UI.OutputCacheLocation.Client, VaryByParam = "TempData['user']", VaryByContentEncoding = "none")]

To Disable Cache for a view, Use this Code

Controller Code
[System.Web.Mvc.OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] //no cache for this page

11. LogOut

1) Create a view in any controller, call this view, when logout button is clicked

HTML Code (call logout view)

<li><a href=@Url.Action("LogOut", "AdminMenu") <span class="fa fa-book" ></span>LogOut</a></li>

Controller Code
public ActionResult LogOut()
        {

            FormsAuthentication.SignOut();
            Session.Clear();
            Session.Abandon();
            Session.RemoveAll();
            return RedirectToActionPermanent("Login", "Account");
        }

2) Keep this code in every Json Result Function

Controller Code

 if (User.Identity.IsAuthenticated == false)
                {
                    return Json(null, JsonRequestBehavior.AllowGet);

                }

3. Keep this code in every Action Result View

Controller Code
if (User.Identity.IsAuthenticated == false)
            {
                return RedirectToAction("Login", "Account");
            }

3) In every view page, keep this JQuery Code, this code will call to a function in controller

JQuer Code
<script>
    CheckUser();
    function CheckUser() {
        $.get("/JsonUserRoles/UserCheck", {}, function (data) {
            if (data == "Login") {
                window.location.href = "/Account/Login";
            }
        });
    }

</script>

Controller Code (this function will be called)
 [System.Web.Mvc.OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]  // this is required
        public JsonResult UserCheck()
        {

            if(User.Identity.IsAuthenticated==false)
            {

                //redirect to loginpage
                return Json("Login", JsonRequestBehavior.AllowGet);
            }
            else
            {
                //dont redirect to LoginPage
                return Json("", JsonRequestBehavior.AllowGet);
            }
        }

Print Report using Jquery

HTML Code
 <input type="button" name="Save" value="Print" onclick="print()" class="button3 btn-info" />
<div style="overflow:auto; ">
    <table id="ttable" class="table table-bordered table-sm" style="overflow:auto;border-color:black;padding:0px;font-size:medium;width:100%; " cellspacing="0">
        <thead>

            <tr style="padding:0px; text-align:center;">
                <th style="width: 10%; padding: 0px;" colspan="5">
                    @*~/SavedImages/asanicalogo.png*@
                    <img src="" style="height:100px; width:100px;float:left;margin-top:13px;" id="shoplogo" />
                    <div class="" style="float:left;margin-left:10px; margin-top:4px;">
                        <h1 style="text-align:left;margin:0px; margin-top:10px;" id="shopname"></h1>
                        <h5 style="text-align:left;margin:0px;" id="shopaddress"></h5>
                        <h5 style="text-align:left;margin:0px;" id="emailaddress"></h5>
                        <h5 style="text-align:left;margin:0px;" id="shopcontact"></h5>
                    </div>
                </th>

            </tr>

</thead>
</table>
</div>
JQuery Code
 function print() {
            var divToPrint = document.getElementById("ttable");
            newWin = window.open("PRINT");
            newWin.document.write(divToPrint.outerHTML);

            setTimeout(function () {
                newWin.print();
            }, 500)
        }

Master Page

1) Right Click on View Folder > New Item > View , Name view
_ViewStart

2) Paste this code insdide view (Clear it first)

@{
    Layout = "~/Views/Shared/_layoutPage.cshtml";
}

3) Right Click on View Folder > New > Add Folder (and name it Shared)

4) Right Click on This Shared Folder inside View Folder Select Add New > View > (name it _LayoutPage)

5) Keep this code in _LayoutPage view (where you want the child view will be showing
@RenderBody()

C# Windows Form






2. First Project with SQLite, SQLite Configuration in Visual Studio

Step-1: Download two files, click Download Files
Step-2: In step-1, you have download two files, first install sqlite-netFx40-setup-bundle-x86-2010-1.0.106.0.exe in your PC
This Setup installation is required in Pc/Laptop where Visual Studio is Installed, this setup will introduce the SQLite to Visual Studio, it will appear in every in visual studio
Step-3: Open your Visual Studio Project > Goto Solution Explorer > Right Click on Reference > Select Add Reference > Browse > Select System.Data.SQLite.dll >Click Ok
Now you have successfully configured SQLite with Visual Studio Project

3. SQLite Table Structure

To create a table in SQLite, just change the structure of the following format accroding to your needs
SQLite Code

            create table awardList(
            id integer primary key AUTOINCREMENT,
            awardname varchar(50),
            awardlimit float,
            prize varchar(100)
            );
            

4. How to Create SQLite Database


Step1: You can keep the database generation code any where in project, if you want the user click on the database button, then the database will be created, just copy the code and paste in button click event.

Note: The tables in Create_Database() function will be replace by your project tables
C# Code
          public void createDatabase()
        {
            SaveFileDialog ob1 = new SaveFileDialog();
            if (ob1.ShowDialog() == DialogResult.OK)
            {

                string path = ob1.FileName + ".db";

                string conection = "Data Source=" + path + "; Version=3;";

                //create database
                SQLiteConnection.CreateFile(path);

                //Save Database COnnection to file
                StreamWriter ob2 = new StreamWriter("C:\\ProgramData\\" + Return_Folder() + "\\databasepath.bin");
                ob2.WriteLine(conection);
                ob2.Close();


                StreamWriter ob3 = new StreamWriter("C:\\ProgramData\\" + Return_Folder() + "\\databasepathOnly.bin");
                ob3.WriteLine(path);
                ob3.Close();

                Create_Tables(conection);

                MessageBox.Show("Database Created Successfully..", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
        }


        public string Return_Folder()
        {
            return "OpticalShop";
        }
        public void Create_Tables(string connection)
        {

            SQLiteConnection cn = new SQLiteConnection(connection);
            cn.Open();
            SQLiteCommand cmd = new SQLiteCommand("create table Accounts (id integer primary key AUTOINCREMENT, name varchar(50) not null, contact varchar(20), cnic varchar(40),addresss varchar(100), dte datetime)", cn);
            cmd.ExecuteNonQuery();
            cn.Close();

            cn.Open();
            SQLiteCommand cmd2 = new SQLiteCommand("create table awardList(id integer primary key AUTOINCREMENT,awardname varchar(50),awardlimit float,prize varchar(100));", cn);
            cmd2.ExecuteNonQuery();
            cn.Close();

        }

            
        
5. Create Direcotry/Folder

How to create a folder from C#

C# Code
            if(!Directory.Exists("C:\\ProgramData\\MyProjectName"))
                {
                    //create director
                    Directory.CreateDirectory("C:\\ProgramData\\MyProjectName");
                }
            
6. Save Data to File (StreamWriter)

How to save data to file

C# Code
           StreamWriter ob2 = new StreamWriter("C:\\ProgramData\\MyProjectName\\FileName.bin");
           ob2.WriteLine("Text Data here");
           ob2.Close();
            
7. Read Data from File (StreamReader)

How to Read data from folder in C#

C# Code
           StreamReader ob1 = new StreamReader("C:\\ProgramData\\MyProjectName\\FileName.bin");
           string data= ob1.ReadLine();
           ob1.Close();
            
8. Go from one page to another in C#

Click on a button and goto another page in C#

C# Code
           MainMenu ob1 = new MainMenu();
           ob1.Show();
           this.Hide();
            
9. Show MessageBox in C#

Click on a button and goto another page in C#

C# Code
         MessageBox.Show("Sorry! Litters is required", "Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            
10. Date Format for SQLite in C#

When saving a Date value to SQLite database, send the datetimepicker value to the given function and save the return value to database in format: yyyy-mm-dd

C# Code
           public string Return_Date(DateTime dtt)
        {
            if (dtt.Month < 10)
            {
                aa = "0" + dtt.Month;
            }
            else
            {
                aa = dtt.Month.ToString();
            }
            if (dtt.Day < 10)
            {
                bb = "0" + dtt.Day;
            }
            else
            {
                bb = dtt.Day.ToString();
            }
            
            DteReturn = dtt.Year + "-" + aa + "-" + bb;            
        }

            
11. Create MDF Hash from String in C#

For Security reason, password should not be stored in Plain Text in Database, Best practice is to convert the password into Hash and then store the Hash in the Database

C# Code
           public static string CreateMD5(string input)
        {
            // Use input string to calculate MD5 hash
            using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
            {
                byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
                byte[] hashBytes = md5.ComputeHash(inputBytes);

                // Convert the byte array to hexadecimal string
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < hashBytes.Length; i++)
                {
                    sb.Append(hashBytes[i].ToString("X2"));
                }
                return sb.ToString();
            }
        }
            
12. Browse Image to PictureBox in C#

Step-1: Drag a PictureBox from Toolbox into C# Windows Form, then drag a button, click on button to generate Button Click Event
Step-2: Copy the code and paste in button click event

C# Code
          OpenFileDialog open = new OpenFileDialog() { Filter = "Image Files(*.jpeg;*.bmp;*.png;*.jpg)|*.jpeg;*.bmp;*.png;*.jpg" };
            if (open.ShowDialog() == DialogResult.OK)
            {
                pictureBox3.Image = Image.FromFile(open.FileName);
            }
            
13. Save Image to a Folder from PictureBox in C#

Step-1: Drag a PictureBox from Toolbox into C# Windows Form, then drag a button, click on button to generate Button Click Event
Step-2: Copy the code and paste in button click event

C# Code
        if (Directory.Exists("C:\\ProgramData\\MyProjectName"))      //if directory exist then Create logo
                {
                    pictureBox3.Image.Save("C:\\ProgramData\\Laboratory Management System\\Logo.png");
                    MessageBox.Show("Logo Saved", "Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {  //if directory not exist first create it then save logo

                    Directory.CreateDirectory("C:\\ProgramData\\MyProjectName");

                    pictureBox3.Image.Save("C:\\ProgramData\\MyProjectName\\Logo.png");
                    MessageBox.Show("Logo Saved", "Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            
14. Insert data to SQLite Database Table

Step-1: Drag some Textboxes into C# Window Form and Drag A Button, then click on button to generate Button Click Event, Note: Database table is already created by you
Step-2: Copy the code and paste in button click event, change the textboxes names

C# Code
                
            //conection is your database connection
                SQLiteConnection cn = new SQLiteConnection(conection);
                cn.Open();
                SQLiteCommand cmdda = new SQLiteCommand("insert into expensis(expensisDetail,cost,head) values('"+bExpensis.Text+"',"+bCost.Text+",'"+bhead.Text+"')", cn);
                cmdda.ExecuteNonQuery();
                cn.Close();
            
15. Read data from SQLite Database Table

Step-1: To read a value from Database Table Copy the Code and Change as per your needs

C# Code
                
           SQLiteConnection cn = new SQLiteConnection(Return_Connection());
            cn.Open();
            SQLiteCommand cmdChecka = new SQLiteCommand("select expensisDetail as 'Expensis Details'  from expensis", cn);
            SQLiteDataReader sqlChecka = cmdChecka.ExecuteReader();
            if (sqlChecka.HasRows)
            {
                //here you get expensisDetail value
               string value = sqlChecka.GetValue(0).ToString();                              
            }            
            cn.Close();
            
16. Delete data from SQLite Database Table

Step-1: To delete a row from database table, just change the query as per your needs

C# Code
                
           SQLiteConnection cn = new SQLiteConnection(Return_Connection());
            cn.Open();
            SQLiteCommand cmd = new SQLiteCommand("delete from table1 where id=1", cn);
            cmd.ExecuteNonQuery();
            cn.Close();
            
17. Update data in SQLite Database Table

Step-1: To update row in database table, just change the query as per your needs

C# Code
                
           SQLiteConnection cn = new SQLiteConnection(Return_Connection());
            cn.Open();
            SQLiteCommand cmd = new SQLiteCommand("update table1 set username='abcde' where id=1", cn);
            cmd.ExecuteNonQuery();
            cn.Close();
            
18. Load data to Comboxbox from SQLite Database Table

Step-1: If you have already inserted data into database table, now you want to populate combobox with those values, drag a combobox into C# windows form
Step-2: paste the following code in Formload or Button Click event where you want to return all the values

C# Code
                
            SQLiteConnection cn = new SQLiteConnection(Return_Connection());
            cn.Open();
            SQLiteCommand cmddaa = new SQLiteCommand("select usernames from logintable", cn);
            SQLiteDataReader SQLiteda = cmddaa.ExecuteReader();
            while (SQLiteda.Read())
            {
                if (SQLiteda.HasRows)
                {
		            ComboBoxName1.Items.Add(SQLiteda.GetValue(0).ToString());
                }
            }
            cn.Close();
            
19. Load data to Gridview from SQLite Database Table

Step-1: If you have already inserted data into database table, now you want to show all the data from database table into datagrid view, drag datagrid view from toolbox into C# windows form
Step-2: Copy the code and paste.

C# Code (Method-1)
                
        BindingSource bs = new BindingSource();
        DataSet ds = new DataSet();
        public void Load_RecentLabs()
        {                
            bs = null;  //bindingSource object
            ds = null; //Dataset object which are initialized bofore
            dataGridView1.DataSource = null;  //Datagridveiw            
            bs = new BindingSource();
            ds = new DataSet();
            
            conection = Return_Connection();

            SQLiteConnection cn = new SQLiteConnection(conection);
            cn.Open();
            SQLiteDataAdapter SQLited = new SQLiteDataAdapter("Select ID, Name, Contact from table1", cn);
            SQLited.Fill(ds, "patient_info");
            cn.Close();
            dataGridView1.DataSource = ds.Tables[0];
            cn.Close();
                    

        }
            

C# Code (Method-2)
                
            SqlConnection cn = new SqlConnection(connection);
            cn.Open();
            SqlCommand cmdd = new SqlCommand("select id,name,grade,class from table1", cn);
            SqlDataReader sqldd = cmdd.ExecuteReader();
            while (sqldd.Read())
            {
                

                   int id = sqldd.GetValue(0).ToString();
                   string name = sqldd.GetValue(1).ToString();
                   string postion = sqldd.GetValue(2).ToString();
                   string classs = sqldd.GetValue(3).ToString();

		   int b = dataGridView1.Rows.Add();

            		dataGridView1.Rows[b].Cells[0].Value = id.ToString();
	            dataGridView1.Rows[b].Cells[1].Value = name;
            dataGridView1.Rows[b].Cells[2].Value = position;
            dataGridView1.Rows[b].Cells[3].Value = class1;
            dataGridView1.Refresh();
                
            }
            cn.Close();

        }
            
20. Get Specific Cell value from DataGrid View in C#

Step-1: If you want to click on button in datagridview and when click on that button, the row will be deleted from the Database table
Step-2: Drag datagrid view, and load the data into datagridview as shown in Section-19
Step-3: Goto the properties of datagridview and click on CellClick event, the event will be generated
Step-4: Paste the following code in the above event.

C# Code
           if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
            {
                MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
            }
            
21. Delete Row From DataGrid View

Step-1: If you want to click on button in datagridview and when click on that button, the row will be deleted from the Database table
Step-2: Drag datagrid view, and load the data into datagridview as shown in Section-19, but before loading data add a button column into datagridview
Step-3: Goto the properties of datagridview and click on CellClick event, the event will be generated
Step-4: Paste the following code in the above event.

C# Code
                if (e.ColumnIndex == dataGridView1.Columns["Delete"].Index && e.RowIndex >= 0)      //this row is clicked
            {

               string ID = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();    //get the first cell value             		
                dataGridView1.Rows.RemoveAt(e.RowIndex); //remove the row from the grid


		    //now delete the record from database table
	        SQLiteConnection cn = new SQLiteConnection(Return_Connection());
            cn.Open();
            SQLiteCommand cmd = new SQLiteCommand("delete from table1 where id=1", cn);
            cmd.ExecuteNonQuery();
            cn.Close();

            //show message to user, Row is deleted
                MessageBox.Show("Row Deleted");                                                
            }