CRUD Operations Using LINQ To SQL In ASP.NET #mesameergaikwad

 

CRUD Operations Using LINQ To SQL In ASP.NET

LINQ

LINQ Stands For Language Integrated Query, It is a common programming model that can be used to query all types of data such as database, dataset, XML, and many other types of data.

First Open SQL Server and Create a Table name tblDetails which include three fields:

create table tblDetails (

Id int Primary Key,

Name varchar(50),

ImgPath varchar(100)

)

Open Visual Studio and Create a New Web Application. File-New Project-Asp.Net Web Application Name it as LINQ Application.

Right, Click on Application And Create New Folder Name it as Images to Store the Path of the Images which will be Uploaded.

Right Click on Application and Add New Item Web Form Name it as Details.aspx.

Add two textboxes text search, txtName, two buttons btnSubmit and btnSearch, and a Grid View to display Data. Take two Hidden Fields one for storing Id which is the primary key that will be required for updating and Deleting Record. Another for storing image Path. Take a File Upload Control for Image Upload. Just write the following code on aspx page.

  1. <%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Details.aspx.cs” Inherits=”LINQApplication.Details” %>
  2. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns=”http://www.w3.org/1999/xhtml">
  4. <head runat=”server”>
  5. <script src=”Scripts/jquery-1.10.2.min.js” type=”text/javascript”></script>
  6. <script type=”text/javascript” language=”javascript”>
  7. function ValidateName(e)
  8. {
  9. var keyCode = (e.which) ? e.which : e.keyCode
  10. if (((keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122)) || keyCode == 32)
  11. {
  12. document.getElementById(“chkName”).style.display = “none”;
  13. return true;
  14. }
  15. else
  16. {
  17. document.getElementById(“chkName”).style.display = “inline”;
  18. return false;
  19. }
  20. }
  21. </script>
  22. <title></title>
  23. </head>
  24. <body>
  25. <form id=”form1" runat=”server”>
  26. <div>
  27. <table>
  28. <tr>
  29. <td>
  30. <asp:HiddenField ID=”hdnValue” runat=”server” /> </td>
  31. </tr>
  32. <tr>
  33. <td>
  34. <asp:HiddenField ID=”hdfHidden” runat=”server” /> </td>
  35. </tr>
  36. <tr>
  37. <td> Name : </td>
  38. <td>
  39. <asp:TextBox ID=”txtName” runat=”server” onkeypress=”return ValidateName(event);”> </asp:TextBox> <span id=”chkName” style=”color: Red; display: none”>Name Should Not Contain Numeric Values</span> </td>
  40. </tr>
  41. <tr>
  42. <td> Please Select Image : </td>
  43. <td>
  44. <asp:FileUpload ID=”imgFile” runat=”server” /> </td>
  45. </tr>
  46. <tr>
  47. <td>
  48. <asp:Button ID=”btnSubmit” runat=”server” Text=”Submit” onclick=”btnSubmit_Click” /> </td>
  49. <td>
  50. <asp:Button ID=”btnCancel” runat=”server” Text=”Cancel” onclick=”btnCancel_Click” /> </td>
  51. </tr>
  52. <tr>
  53. <td> Search by Name: </td>
  54. <td>
  55. <asp:TextBox ID=”txtSearch” runat=”server”></asp:TextBox>
  56. </td>
  57. <td>
  58. <asp:Button ID=”btnSearch” runat=”Server” Text=”Search” onclick=”btnSearch_Click” /> </td>
  59. </tr>
  60. <tr>
  61. <td>
  62. <asp:GridView ID=”gvDisplayDetails” DataKeyNames=”Id” runat=”server” AutoGenerateColumns=”false” onrowcommand=”gvDisplayDetails_RowCommand” onrowdeleting=”gvDisplayDetails_RowDeleting” onselectedindexchanging=”gvDisplayDetails_SelectedIndexChanging”>
  63. <Columns>
  64. <asp:BoundField DataField=”Name” HeaderText=”Name” />
  65. <asp:TemplateField HeaderText=”Images”>
  66. <ItemTemplate>
  67. <asp:Image ID=”img” runat=”server” ImageUrl=’<%# Bind(“ImgPath”, “~/Images/{0}”) %>’ /> </ItemTemplate>
  68. </asp:TemplateField>
  69. <asp:CommandField ButtonType=”Button” SelectText=”Edit” ShowSelectButton=”True” />
  70. <asp:TemplateField>
  71. <ItemTemplate>
  72. <asp:Button runat=”server” ID=”btnDelete” OnClientClick=”return confirm(‘Are you sure,you want to delete this record ?’);” Text=”Delete” CommandName=”Delete” /> </ItemTemplate>
  73. </asp:TemplateField>
  74. </Columns>
  75. </asp:GridView>
  76. </td>
  77. </tr>
  78. </table>
  79. </div>
  80. </form>
  81. </body>
  82. </html>

Now again right-click on the Application and Add New a LINQ to SQL Class. Select Add New Item then in Installed Templates.

Select Data then Select LINQ to SQL Classes, Name it as PersonalDetails. Extension is .dbml.

Now From Server Explorer just drag and drop your table on dbml file and save it. You will see in web.config a connection string is created automatically:

<add name=”sameerDBConnectionString” connectionString=”Data Source=.\SQLEXPRESS;Initial Catalog=sameer;Integrated Security=True”

providerName=”System.Data.SqlClient” />

Here TestDB is my DataBase Name.

  1. Generate Events for GridView Selected Index Changing, OnRowCommand, OnRowDeleting.
  2. Just write the following code on the CS side.
  3. using System;
  4. using System.Collections.Generic;
  5. using System.LINQ;
  6. using System.Web;
  7. using System.Web.UI;
  8. using System.Web.UI.WebControls;
  9. using System.IO;
  10. using System.Configuration;
  11. using System.Data.SqlClient;
  12. namespace LINQApplication
  13. {
  14. public partial class Details: System.Web.UI.Page
  15. {
  16. PersonalDetailsDataContext obj = new PersonalDetailsDataContext();
  17. SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[“TestDBConnectionString”].ToString());
  18. protected void Page_Load(object sender, EventArgs e)
  19. {
  20. if (!Page.IsPostBack)
  21. {
  22. BindGrid();
  23. btnCancel.Visible = false;
  24. }
  25. }
  26. private void BindGrid()
  27. {
  28. try
  29. {
  30. var Details = from details in obj.tblDetails
  31. select new
  32. {
  33. details.Id,
  34. details.Name,
  35. details.ImgPath
  36. };
  37. if (Details.Any())
  38. {
  39. gvDisplayDetails.DataSource = Details;
  40. gvDisplayDetails.DataBind();
  41. }
  42. else
  43. {
  44. Showmsg(“No Record Found”);
  45. }
  46. }
  47. catch (Exception ex)
  48. {
  49. throw ex;
  50. }
  51. }
  52. protected void btnSubmit_Click(object sender, EventArgs e)
  53. {
  54. try
  55. {
  56. if (btnSubmit.Text == “Submit”)
  57. {
  58. if (checkBlank())
  59. {
  60. Save();
  61. }
  62. }
  63. else if (btnSubmit.Text == “Update”)
  64. {
  65. Update();
  66. }
  67. }
  68. catch (Exception ex)
  69. {
  70. throw ex;
  71. }
  72. }
  73. private void Update()
  74. {
  75. try
  76. {
  77. string filename = UploadImages();
  78. int id = Convert.ToInt32(hdnValue.Value);
  79. var singleRecord = obj.tblDetails.First(dtl => dtl.Id == id);
  80. singleRecord.Name = txtName.Text;
  81. if (imgFile.HasFile)
  82. {
  83. singleRecord.ImgPath = filename;
  84. }
  85. else
  86. {
  87. singleRecord.ImgPath = hdfHidden.Value;
  88. }
  89. obj.SubmitChanges();
  90. btnSubmit.Text = “Submit”;
  91. Showmsg(“Information Updated Successfulluy”);
  92. BindGrid();
  93. Clear();
  94. btnCancel.Visible = false;
  95. }
  96. catch (Exception ex)
  97. {
  98. throw ex;
  99. }
  100. }
  101. private void Save()
  102. {
  103. try
  104. {
  105. string fileName = UploadImages();
  106. tblDetail objDetail = new tblDetail();
  107. objDetail.Name = txtName.Text;
  108. if (imgFile.HasFile)
  109. {
  110. objDetail.ImgPath = fileName;
  111. }
  112. else
  113. {
  114. objDetail.ImgPath = hdfHidden.Value;
  115. }
  116. obj.tblDetails.InsertOnSubmit(objDetail);
  117. obj.SubmitChanges();
  118. Showmsg(“Details Inserted Successfully”);
  119. BindGrid();
  120. Clear();
  121. }
  122. catch (Exception ex)
  123. {
  124. throw ex;
  125. }
  126. }
  127. private string UploadImages()
  128. {
  129. string result = string.Empty;
  130. if (imgFile.HasFile)
  131. {
  132. string extension = System.IO.Path.GetExtension(imgFile.PostedFile.FileName);
  133. if (extension == “.jpg” || extension == “.png” || extension == “.img”)
  134. {
  135. result = imgFile.PostedFile.FileName;
  136. imgFile.PostedFile.SaveAs(MapPath(“~”) + “/Images/” + result);
  137. }
  138. }
  139. return result;
  140. }
  141. private bool checkBlank()
  142. {
  143. try
  144. {
  145. bool flag = true;
  146. string msg = string.Empty;
  147. if (!imgFile.HasFile)
  148. {
  149. msg += “Please Upload File, “;
  150. flag = false;
  151. }
  152. else
  153. {
  154. if (!(Path.GetExtension(imgFile.PostedFile.FileName).Equals(“.jpg”) || Path.GetExtension(imgFile.PostedFile.FileName).Equals(“.img”) || Path.GetExtension(imgFile.PostedFile.FileName).Equals(“.png”)))
  155. {
  156. msg += “Please Upload Valid File, “;
  157. flag = false;
  158. }
  159. }
  160. if (txtName.Text == string.Empty)
  161. {
  162. msg += “Please Enter Name, “;
  163. flag = false;
  164. }
  165. if (msg.Length > 0)
  166. {
  167. msg = msg.Remove(msg.Length — 2);
  168. Showmsg(msg);
  169. }
  170. return flag;
  171. }
  172. catch (Exception ex)
  173. {
  174. throw ex;
  175. }
  176. }
  177. private void Showmsg(string Message)
  178. {
  179. ScriptManager.RegisterClientScriptBlock(this, this.GetType(), “Alert”, “alert(‘“ + Message + “‘);”, true);
  180. }
  181. private void Clear()
  182. {
  183. txtName.Text = “”;
  184. txtSearch.Text = “”;
  185. }
  186. protected void gvDisplayDetails_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
  187. {
  188. try
  189. {
  190. string id = gvDisplayDetails.DataKeys[e.NewSelectedIndex].Value.ToString();
  191. hdnValue.Value = id;
  192. var singleRecord = obj.tblDetails.Single(dtls => dtls.Id == Convert.ToInt32(id));
  193. txtName.Text = singleRecord.Name;
  194. hdfHidden.Value = singleRecord.ImgPath;
  195. btnSubmit.Text = “Update”;
  196. btnCancel.Visible = true;
  197. }
  198. catch (Exception ex)
  199. {
  200. throw ex;
  201. }
  202. }
  203. protected void gvDisplayDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
  204. {
  205. try
  206. {
  207. int Id = Convert.ToInt32(gvDisplayDetails.DataKeys[e.RowIndex].Value);
  208. var singleRecord = obj.tblDetails.First(dtl => dtl.Id == Id);
  209. obj.tblDetails.DeleteOnSubmit(singleRecord);
  210. obj.SubmitChanges();
  211. Showmsg(“Records Deleted Successfully”);
  212. BindGrid();
  213. }
  214. catch (Exception ex)
  215. {
  216. throw ex;
  217. }
  218. }
  219. protected void gvDisplayDetails_RowCommand(object sender, GridViewCommandEventArgs e)
  220. {}
  221. protected void btnCancel_Click(object sender, EventArgs e)
  222. {
  223. try
  224. {
  225. btnSubmit.Text = “Submit”;
  226. BindGrid();
  227. btnCancel.Visible = false;
  228. Clear();
  229. }
  230. catch (Exception ex)
  231. {
  232. throw ex;
  233. }
  234. }
  235. protected void btnSearch_Click(object sender, EventArgs e)
  236. {
  237. try
  238. {
  239. if (txtSearch.Text != string.Empty && txtSearch.Text != “”)
  240. {
  241. string txt = txtSearch.Text;
  242. BindSearch(txt);
  243. Clear();
  244. }
  245. else
  246. {
  247. Showmsg(“Please Enter a Keyword to Search”);
  248. }
  249. }
  250. catch (Exception ex)
  251. {
  252. throw ex;
  253. }
  254. }
  255. private void BindSearch(string name)
  256. {
  257. try
  258. {
  259. var results = from details in obj.tblDetails where details.Name.Contains(name)
  260. select new
  261. {
  262. details.Id,
  263. details.Name,
  264. details.ImgPath
  265. };
  266. if (results.Any())
  267. {
  268. gvDisplayDetails.DataSource = results;
  269. gvDisplayDetails.DataBind();
  270. }
  271. else
  272. {
  273. Showmsg(“No Record Found for Particular Keyword”);
  274. BindGrid();
  275. }
  276. }
  277. catch (Exception ex)
  278. {
  279. throw ex;
  280. }
  281. }
  282. }
  283. }
  284. We can see I have created an object of PersonalDataContext class it contains all entities that map to tables in databases. On page load on If(!Page.IsPostBack) i have called a method BindGrid() which bind Details to Gridview. Also, I have used Any to see if the result of the LINQ query contains data.
  285. Also, there are two methods, one for submit and another for the update, for submit and update I have used insert on submit and just passed the object of the table entity to it. Then submit changes to save changes. For Deletion use Deletion Submit.

These are basic Crud operations using LINQ to SQL in ASP.NET, I will come up with more details on LINQ in my next blog posts. #mesameergaikwad

Post a Comment

0 Comments