LINQ to SQL - Basic Guide To Perform Fetch, Filter, Insert, Update And Delete

Many years ago, I created a simple demo about “Creating a Simple Registration Form using the ADO.NET way”. In this article, we’re going to look at how to create a simple form that would allow users to perform basic database operations, such as fetch, insert, update and delete using L2S.

As an overview, LINQ to SQL is a technology that allows you to query SQL Server database. LINQ to SQL is an O/RM (object relational mapping) implementation that ships in the .NET Framework "Orcas" release, and which allows you to model a relational database using .NET classes. You can then query the database using LINQ, as well as update/insert/delete data from it.

I will not cover much on details about it in this article. So, if you need to know more about this technology, then you can refer to this link.

Let’s Get Started!

To get started, let’s go ahead and fire up Visual Studio and create a new WebSite by selecting File > New WebSite.

Adding a DBML File

Since we are going to use L2S, we need to add a .dbml file. To do this, just right click on the application root and select Add New Item. On the template, select LINQ to SQL Classes file, just like in the figure shown below,

DBML File

Rename your .dbml file the way you want it and then click OK. Note that I’m using the Northwind database for this particular demo, and on that account, I have renamed the .dbml file to Northwind for simplicity.

Now, open up server explorer in Visual Studio and browse the database that you want to work on (in this case, the Northwind database). Just for the purpose of this example, we’re going to use the Customers table from the Northwind database. Drag and drop the aforementioned table to the Northwind.dbml design surface. See the screenshot below,

server explorer

What happened there is that by the time you drag a table in the design surface, L2S will automatically generate the business object for you within the DataContext, and let you query against it. The DataContext is the main gateway by which you retrieve objects from the database and resubmit changes. You use it in the same way that you would use an ADO.NET Connection. In fact, the DataContext is initialized with a connection or connection string you supply. The purpose of the DataContext is to translate your requests for objects into SQL queries made against the database and then assemble objects out of the results. The DataContext enables language-integrated query (LINQ) by implementing the same operator pattern as the standard query operators, such as Where and Select.

Setting Up the GUI

Now, let’s go ahead and create a new WebForm’s page for data entry. For the simplicity of this demo, I just set up the form like below:

  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2. <head runat="server">  
  3.     <title>LINQ to SQL Demo</title>  
  4.     <style type="text/css">  
  5.         .style1 {  
  6.             width: 400px;  
  7.         }  
  8.         .style1 td {  
  9.             width: 200px;  
  10.         }  
  11.     </style>  
  12. </head>  
  13. <body>  
  14.     <form id="form1" runat="server">  
  15.         <asp:Literal ID="LiteralMessage" runat="server"></asp:Literal>  
  16.         <table class="style1">  
  17.             <tr>  
  18.                 <td>Company ID</td>  
  19.                 <td><asp:TextBox ID="TextBoxID" runat="server" /></td>  
  20.             </tr>  
  21.             <tr>  
  22.                 <td>Company Name</td>  
  23.                 <td><asp:TextBox ID="TextBoxCompanyName" runat="server" /></td>  
  24.             </tr>  
  25.             <tr>  
  26.                 <td>Contact Name</td>  
  27.                 <td><asp:TextBox ID="TextBoxContactName" runat="server" /></td>  
  28.             </tr>  
  29.             <tr>  
  30.                 <td>Contact Title</td>  
  31.                 <td><asp:TextBox ID="TextBoxContactTitle" runat="server" /></td>  
  32.             </tr>  
  33.             <tr>  
  34.                 <td>Address</td>  
  35.                 <td><asp:TextBox ID="TextBoxAddress" runat="server" /></td>  
  36.             </tr>  
  37.             <tr>  
  38.                 <td>City</td>  
  39.                 <td><asp:TextBox ID="TextBoxCity" runat="server" /></td>  
  40.             </tr>  
  41.             <tr>  
  42.                 <td>Region</td>  
  43.                 <td><asp:TextBox ID="TextBoxRegion" runat="server" /></td>  
  44.             </tr>  
  45.             <tr>  
  46.                 <td>Postal Code</td>  
  47.                 <td><asp:TextBox ID="TextBoxPostalCode" runat="server" /></td>  
  48.             </tr>  
  49.             <tr>  
  50.                 <td>Country</td>  
  51.                 <td><asp:TextBox ID="TextBoxCountry" runat="server" /></td>  
  52.             </tr>  
  53.         </table>  
  54.         <asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />  
  55.     </form>  
  56. </body>  
  57. </html>  
There’s nothing fancy from the markup above. It just contains some basic server controls to compose the form.

Perform Insert

After setting up our GUI, let’s go ahead and create the method for inserting the data to the database using L2S. Here’s the full code block below:
  1. using System;  
  2. using System.Configuration;  
  3. using System.Data;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.UI;  
  7. using System.Web.UI.HtmlControls;  
  8. using System.Web.UI.WebControls;  
  9. using System.Xml.Linq;  
  10.   
  11. public partial class _Default : System.Web.UI.Page  
  12. {  
  13.     protected void Button1_Click(object sender, EventArgs e)  
  14.     {  
  15.         SaveCustomerInfo();  
  16.     }  
  17.   
  18.     private void SaveCustomerInfo()  
  19.     {  
  20.         using (NorthwindDataContext context = new NorthwindDataContext())  
  21.         {  
  22.             //Create a new instance of the Customer object  
  23.             Customer cust = new Customer();  
  24.             //Add new values to each fields  
  25.             cust.CustomerID = TextBoxID.Text;  
  26.             cust.CompanyName = TextBoxCompanyName.Text;  
  27.             cust.ContactName = TextBoxContactName.Text;  
  28.             cust.ContactTitle = TextBoxContactTitle.Text;  
  29.             cust.Address = TextBoxAddress.Text;  
  30.             cust.City = TextBoxCity.Text;  
  31.             cust.Region = TextBoxRegion.Text;  
  32.             cust.PostalCode = TextBoxPostalCode.Text;  
  33.             cust.Country = TextBoxCountry.Text;  
  34.   
  35.             //Insert the new Customer object  
  36.             context.Customers.InsertOnSubmit(cust);  
  37.             //Sumbit changes to the database  
  38.             context.SubmitChanges();  
  39.   
  40.             //Display a message for successful operation  
  41.             LiteralMessage.Text = "<p style='color:Green;'>Information Successfully saved!</p>";  
  42.         }  
  43.     }  
  44. }  
The code above was very straightforward. First, we have created a new instance of the DataContext which we had created earlier, and wrapped it inside the “using” block; this is to ensure that the DataContext will be disposed and closed the connection after it's processing. Second, we created a new instance of the Customer object that was defined within the DataContext. This object has properties which are filled with values that came from the user inputs. Third, we inserted a new Customer object to the Customers set and then call the context.SubmitChanges() to update our database. Lastly, L2S will do the rest for you ;).

Note: The Customer and Customer's objects are automatically created once you’ve added the Customer table in the .dmbl design surface.

Testing the App

Running the code will result to something like this:

App

From there, we can fill in those fields with values we want. Just for this demo, notice that I have filled in the fields with a sample data. Hitting the save button will invoke the method SaveCustomerInfo() which is responsible for doing the insert operation. Now, if we look at the database, we can see that the data we entered was being saved successfully to the database. See the screenshot below,

database

Pretty simple!

Okay, I know that you have few questions that pops in your mind now and these are, 
  • What happened behind the scene? How does it actually save the data to the database?
  • How does the query being constructed? Does it handle SQL Injection?
  • How does the connection string being set up? What If I want to set the connection string manually?
  • Does L2S always open the connection to the database once we created a new instance of the DataContext?

To answer the questions that you have in mind then I would suggest you to give this FAQ a read.

Performing Fetch and Filter

Now that we’ve learned the basics on performing an insert to our database, it’s time for us to move one step further. We’ll see how to fetch and filter data from database and fill the fields in the form using L2S.

Setting Up the GUI

Okay, add a new WebForm to your application and set up the GUI. Again, just for the simplicity of this demo, let’s just setup the form like this,

  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2. <head runat="server">  
  3.     <title>LINQ to SQL Demo</title>  
  4.     <style type="text/css">  
  5.         .style1 {  
  6.             width: 400px;  
  7.         }  
  8.         .style1 td {  
  9.                 width: 200px;  
  10.         }  
  11.     </style>  
  12. </head>  
  13. <body>  
  14.     <form id="form1" runat="server">  
  15.         <asp:DropDownList ID="DropDownListCustomerID" runat="server"  
  16.                           AutoPostBack="true"  
  17. onselectedindexchanged="DropDownListCustomerID_SelectedIndexChanged">  
  18.         </asp:DropDownList>  
  19.         <br />  
  20.         <table class="style1">  
  21.             <tr>  
  22.                 <td>Company Name</td>  
  23.                 <td><asp:TextBox ID="TextBoxCompanyName" runat="server" ReadOnly="true" /></td>  
  24.             </tr>  
  25.             <tr>  
  26.                 <td>Contact Name</td>  
  27.                 <td><asp:TextBox ID="TextBoxContactName" runat="server" ReadOnly="true" /></td>  
  28.             </tr>  
  29.             <tr>  
  30.                 <td>Contact Title</td>  
  31.                 <td><asp:TextBox ID="TextBoxContactTitle" runat="server" ReadOnly="true" /></td>  
  32.             </tr>  
  33.             <tr>  
  34.                 <td>Address</td>  
  35.                 <td><asp:TextBox ID="TextBoxAddress" runat="server" ReadOnly="true" /></td>  
  36.             </tr>  
  37.             <tr>  
  38.                 <td>City</td>  
  39.                 <td><asp:TextBox ID="TextBoxCity" runat="server" ReadOnly="true" /></td>  
  40.             </tr>  
  41.             <tr>  
  42.                 <td>Region</td>  
  43.                 <td><asp:TextBox ID="TextBoxRegion" runat="server" ReadOnly="true" /></td>  
  44.             </tr>  
  45.             <tr>  
  46.                 <td>Postal Code</td>  
  47.                 <td><asp:TextBox ID="TextBoxPostalCode" runat="server" ReadOnly="true" /></td>  
  48.             </tr>  
  49.             <tr>  
  50.                 <td>Country</td>  
  51.                 <td><asp:TextBox ID="TextBoxCountry" runat="server" ReadOnly="true" /></td>  
  52.             </tr>  
  53.         </table>  
  54.     </form>  
  55. </body>  
  56. </html>  
If you have noticed, we set the ReadOnly attribute of each TextBox to True; this is because we don’t need users to edit the fields in the form once the TextBox are filled with data.

Populating the DropDownList with the List of Customers

Now, switch to our code behind page and create the method for fetching the list of customers. Here’s the code block below:
  1. private List<Customer> GetCustomers()  
  2. {  
  3.     using (NorthwindDataContext context = new NorthwindDataContext())  
  4.     {  
  5.         return (from c in context.Customers select c).ToList();  
  6.     }  
  7. }  
The code above used a LINQ syntax for querying data. It basically query the Customers’ object that is generated from the DataContext and then fetch the results.

Since we are done creating the method for fetching the list of customers, we can simply call the method above and populate the DropDownList control with the results. Typically we do this at Page_Load event within Not IsPostBack block like below,
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     if (!Page.IsPostBack)  
  4.     {  
  5.         DropDownListCustomerID.DataSource = GetCustomers();  
  6.         DropDownListCustomerID.DataTextField = "ContactName";  
  7.         DropDownListCustomerID.DataValueField = "CustomerID";  
  8.         DropDownListCustomerID.DataBind();  
  9.     }  
  10. }  
The code above is pretty much straight forward and self-explanatory. Running the code above will result in something like this,

result
Let’s proceed and continue on the next step.

Populating the Form with Customer’s Information

The next step is to populate the form with the customer information based on the CustomerID selected from the DropDownList.

Note: Since the form will be populated based on the selected item from the DropDownList, then you’ll need to set the AutoPostBack attribute to TRUE in the DropDownList so that the SelectedIndexChanged event will fire up.

Here’s the code block below for fetching the customer information based on the CustomerID,
  1. private List<Customer> GetCustomerInfo(string customerID)  
  2. {  
  3.     using (NorthwindDataContext context = new NorthwindDataContext())  
  4.     {  
  5.         return (from c in context.Customers  
  6.                 where c.CustomerID == customerID  
  7.                 select c).ToList();  
  8.     }  
  9. }  
Again, the code above used LINQ syntax for querying data. As you can see, we created a new instance of the DataContext and queried the Customer's object based on the parameter we passed on the GetCustomerInfo() method. Once we invoke the LINQ ToList() function, this LINQ query will issue a parameterized SQL query to the database which the SQL Server can understand, and then bring back the results to the DataContext.

One of the cool things about L2S is that we don’t need to worry how the query is being constructed because L2S will take care of that for you including mapping of the data types from your table columns, mapping relationships between tables, etcetera, etcetera and etcetera. Always keep in mind that L2S is an ORM (Object Relational Mapper), and so we don’t need to deal directly with databases, tables and columns but instead, we deal with the objects that are in the DataContext and query the data against it using LINQ syntax.

Populating the Forms with Data

The final step is to populate our form with data based on the selected value from the DropDownList. To do this, we can simply call the method GetCustomerInfo() at the SelectedIndexChanged event of DropDownList like below:
  1. protected void DropDownListCustomerID_SelectedIndexChanged(object sender, EventArgs e)  
  2. {  
  3.     var customerInfo = GetCustomerInfo(DropDownListCustomerID.SelectedValue);  
  4.     TextBoxCompanyName.Text = customerInfo[0].CompanyName;  
  5.     TextBoxContactName.Text = customerInfo[0].ContactName;  
  6.     TextBoxContactTitle.Text = customerInfo[0].ContactTitle;  
  7.     TextBoxAddress.Text = customerInfo[0].Address;  
  8.     TextBoxCity.Text = customerInfo[0].City;  
  9.     TextBoxRegion.Text = customerInfo[0].Region;  
  10.     TextBoxPostalCode.Text = customerInfo[0].PostalCode;  
  11.     TextBoxCountry.Text = customerInfo[0].Country;  
  12. }  
The code above calls the method GetCustomerInfo() and pass the selected value of the DropDownList as a parameter to that method. We then stored it in a customerInfo implicit typed variable and assign each TextBox with the corresponding data returned from the query.

When you run the code above and select an item in the DropDownList, you will see that the textbox fields will be populated with the data based from what you have selected in the DropDownList:

DropDownList
That simple!

Performing Edit and Update

Up to this point, we’ve learned how to insert, fetch and filter data from our database using L2S. In this section, we’re going to see the basic way on how to edit and update the data

Setting Up the GUI

Now create another page and replace the markup with the following,
  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2. <head runat="server">  
  3.     <title>LINQ to SQL Demo</title>  
  4.     <style type="text/css">  
  5.         .style1 {  
  6.             width: 400px;  
  7.         }  
  8.         .style1 td {  
  9.                 width: 200px;  
  10.         }  
  11.     </style>  
  12. </head>  
  13. <body>  
  14.     <form id="form1" runat="server">  
  15.         <asp:DropDownList ID="DropDownListCustomerID" runat="server"  
  16.                           AutoPostBack="true"  
  17.                           onselectedindexchanged="DropDownListCustomerID_SelectedIndexChanged">  
  18.         </asp:DropDownList>  
  19.         <br />  
  20.         <asp:Literal ID="LiteralMessage" runat="server"></asp:Literal><br />  
  21.         <asp:Button ID="ButtonEdit" runat="server" Text="Edit" Enabled="false" onclick="ButtonEdit_Click" />  
  22.         <asp:Button ID="ButtonDelete" runat="server" Text="Delete" Enabled="false" />  
  23.         <asp:Button ID="ButtonUpdate" runat="server" Text="Update" Enabled="false" />  
  24.         <asp:Button ID="ButtonCancel" runat="server" Text="Cancel" Enabled="false" />  
  25.         <asp:Panel ID="PanelCustomerInfo" runat="server" Enabled="false">  
  26.             <table class="style1">  
  27.                 <tr>  
  28.                     <td>Company Name</td>  
  29.                     <td><asp:TextBox ID="TextBoxCompanyName" runat="server" /></td>  
  30.                 </tr>  
  31.                 <tr>  
  32.                     <td>Contact Name</td>  
  33.                     <td><asp:TextBox ID="TextBoxContactName" runat="server" /></td>  
  34.                 </tr>  
  35.                 <tr>  
  36.                     <td>Contact Title</td>  
  37.                     <td><asp:TextBox ID="TextBoxContactTitle" runat="server" /></td>  
  38.                 </tr>  
  39.                 <tr>  
  40.                     <td>Address</td>  
  41.                     <td><asp:TextBox ID="TextBoxAddress" runat="server" /></td>  
  42.                 </tr>  
  43.                 <tr>  
  44.                     <td>City</td>  
  45.                     <td><asp:TextBox ID="TextBoxCity" runat="server" /></td>  
  46.                 </tr>  
  47.                 <tr>  
  48.                     <td>Region</td>  
  49.                     <td><asp:TextBox ID="TextBoxRegion" runat="server" /></td>  
  50.                 </tr>  
  51.                 <tr>  
  52.                     <td>Postal Code</td>  
  53.                     <td><asp:TextBox ID="TextBoxPostalCode" runat="server" /></td>  
  54.                 </tr>  
  55.                 <tr>  
  56.                     <td>Country</td>  
  57.                     <td><asp:TextBox ID="TextBoxCountry" runat="server" /></td>  
  58.                 </tr>  
  59.             </table>  
  60.         </asp:Panel>  
  61.     </form>  
  62. </body>  
  63. </html>  
If you look at the previous example, you will notice that the html markup above is a bit similar. The things that are added above are Buttons for Edit, Delete, Update, and Cancel. Notice that the enabled property for each Buttons were set to false, this is to prevent users from doing certain actions when the page is loaded in the browser. Aside from that, we have also moved the form fields inside a Panel control for validation purposes, and removed the ReadOnly attribute for each TextBox.

Populating the Forms

Now, just like the previous section above, let’s populate the DropDownList with the list of customers and populate the form with the customer’s information based on the CustomerID selected from the DropDownList. Here is the code block below,
  1. private List<Customer> GetCustomers()  
  2. {  
  3.     using (NorthwindDataContext context = new NorthwindDataContext())  
  4.     {  
  5.         return (from c in context.Customers select c).ToList();  
  6.     }  
  7. }  
  8.   
  9. private List<Customer> GetCustomerInfo(string customerID)  
  10. {  
  11.     using (NorthwindDataContext context = new NorthwindDataContext())  
  12.     {  
  13.         return (from c in context.Customers  
  14.                 where c.CustomerID == customerID  
  15.                 select c).ToList();  
  16.     }  
  17. }  
  18.   
  19. private void BindCustomersToList()  
  20. {  
  21.     DropDownListCustomerID.DataSource = GetCustomers();  
  22.     DropDownListCustomerID.DataTextField = "ContactName";  
  23.     DropDownListCustomerID.DataValueField = "CustomerID";  
  24.     DropDownListCustomerID.DataBind();  
  25. }  
  26.   
  27. protected void Page_Load(object sender, EventArgs e)  
  28. {  
  29.     if (!Page.IsPostBack)  
  30.     {  
  31.         BindCustomersToList();  
  32.     }  
  33. }  
  34. protected void DropDownListCustomerID_SelectedIndexChanged(object sender, EventArgs e)  
  35. {  
  36.     var customerInfo = GetCustomerInfo(DropDownListCustomerID.SelectedValue);  
  37.     TextBoxCompanyName.Text = customerInfo[0].CompanyName;  
  38.     TextBoxContactName.Text = customerInfo[0].ContactName;  
  39.     TextBoxContactTitle.Text = customerInfo[0].ContactTitle;  
  40.     TextBoxAddress.Text = customerInfo[0].Address;  
  41.     TextBoxCity.Text = customerInfo[0].City;  
  42.     TextBoxRegion.Text = customerInfo[0].Region;  
  43.     TextBoxPostalCode.Text = customerInfo[0].PostalCode;  
  44.     TextBoxCountry.Text = customerInfo[0].Country;  
  45.   
  46.     ButtonEdit.Enabled = true;  
  47.     ButtonDelete.Enabled = true;  
  48. }  
I will not elaborate more on details about the code above because we have already demonstrated this in previous section. The only thing that’s added in the code above is that we are setting the Enabled attribute of the Edit and Delete Buttons to true. We did it like this so by the time a user selects a certain Customer from the DropDownList, then that’s the time that they can do certain operations like editing and deleting.

Running the code above will show something like this in the browser,

result
Selecting a customer from the DropDownList

DropDownList.
After selecting a customer from the DropDownList.

DropDownList

Notice the change of the buttons enabled property after we select a customer.

Here’s the code for the Edit Button,
  1. protected void ButtonEdit_Click(object sender, EventArgs e)  
  2. {  
  3.     PanelCustomerInfo.Enabled = true;  
  4.     DropDownListCustomerID.Enabled = false;  
  5.     ButtonEdit.Enabled = false;  
  6.     ButtonDelete.Enabled = false;  
  7.     ButtonUpdate.Enabled = true;  
  8.     ButtonCancel.Enabled = true;  
  9.     LiteralMessage.Text = string.Empty;  
  10. }  
As you can see, there’s nothing special from the code above. It just basically did some basic validations when you hit the Edit button on the form.

Here’s the code for the Update Button,
  1. private void UpdateCustomerInfo(string ID)  
  2. {  
  3.     using (NorthwindDataContext context = new NorthwindDataContext())  
  4.     {  
  5.         var customer = (from c in context.Customers  
  6.                         where c.CustomerID == ID  
  7.                         select c).Single();  
  8.   
  9.         customer.CompanyName = TextBoxCompanyName.Text;  
  10.         customer.ContactName = TextBoxContactName.Text;  
  11.         customer.ContactTitle = TextBoxContactTitle.Text;  
  12.         customer.Address = TextBoxAddress.Text;  
  13.         customer.City = TextBoxCity.Text;  
  14.         customer.Region = TextBoxRegion.Text;  
  15.         customer.PostalCode = TextBoxPostalCode.Text;  
  16.         customer.Country = TextBoxCountry.Text;  
  17.   
  18.         context.SubmitChanges();  
  19.   
  20.         LiteralMessage.Text = "<p style='color:Green;'>Information Updated!</p>";  
  21.     }  
  22. }  
As you can see, the code above is very straight forward and self-explanatory. What happened there is that we created a new instance of the DataContext and then we query the Customer object based on the ID using LINQ syntax and passed it in a variable customer. The Single function is an eager function which returns the only element of a sequence that satisfies a specified condition. Once the LINQ Single function is invoked then DataContext will issue a parameterize SQL query to the database in which the SQL Server can understand and then bring back the results to the DataContext.

From there, we can then assign the customer fields based on the TextBox values and then call the context.SubmitChanges() method to update the database with the changes we made.

Now, let’s try to run the code and see what will happen,

output
On editing,

output
After invoking the Update Button,

Update

That's simple! Now, we’re down to the last and final step in this article.

Perform Delete

Here’s the code block for the Delete Button,
  1. private void DeleteCustomerInfo(string ID)  
  2. {  
  3.     using (NorthwindDataContext context = new NorthwindDataContext())  
  4.     {  
  5.         var customer = (from c in context.Customers  
  6.                         where c.CustomerID == ID  
  7.                         select c).First();  
  8.   
  9.         context.Customers.DeleteOnSubmit(customer);  
  10.         context.SubmitChanges();  
  11.         LiteralMessage.Text = "<p style='color:Green;'>Information Deleted!</p>";  
  12.     }  
  13. }  
Just like in the update method, the code above creates a new instance of the DataContext and then queries the Customer entity based on the ID. Note that since we are using the northwind database in this demo, then deleting of customer data directly will throw an exception because this table is being referenced to other tables like Orders. So in order for the code above to work and just for the simplicity of this demo, I remove the relationships to the table that referenced it. If you want to implement a cascading delete, then you have to delete the related information to the other tables that have foreign key relationships. So for example, if you have a customer and this customer has orders then you'll have to perform delete in both tables to avoid exceptions. Here's an article that you can refer to: Cascading. Deletes in LINQ to SQL

Since we don’t want users to delete the information right away, we need to prompt them with a confirmation message if they wish to continue the deletion or not. To do this, we could simply hook up a JavaScript Confirm function in the delete button. Take a look at the highlighted code below,
  1. <asp:Button ID="ButtonDelete" runat="server" Text="Delete" Enabled="false"  
  2.             onclick="ButtonDelete_Click" OnClientClick="return confirm('The selected customer will be deleted. Do you wish to continue?');return false;" />  
Now, let’s create the method for clearing the text fields and then call the method that we have created above at Click event of the delete button. Here’s the code block below,
  1. private static void ClearFormFields(Control Parent)  
  2. {  
  3.   
  4.     if (Parent is TextBox)  
  5.     { (Parent as TextBox).Text = string.Empty; }  
  6.     else  
  7.     {  
  8.         foreach (Control c in Parent.Controls)  
  9.             ClearFormFields(c);  
  10.     }  
  11. }  
  12.   
  13. protected void ButtonDelete_Click(object sender, EventArgs e)  
  14. {  
  15.     //Call the DELETE Method  
  16.     DeleteCustomerInfo(DropDownListCustomerID.SelectedValue);  
  17.     //Rebind the DropDownList to reflect the changes after deletion  
  18.     BindCustomersToList();  
  19.     //Clear the fields  
  20.     ClearFormFields(Page);  
  21. }  
Here are the outputs when running the page and perform the delete,

On Deletion,

delete
After Deletion,

After Deletion

Here’s the code for the Cancel Button,
  1. protected void ButtonCancel_Click(object sender, EventArgs e)  
  2. {  
  3.     PanelCustomerInfo.Enabled = false;  
  4.     DropDownListCustomerID.Enabled = true;  
  5.     ButtonEdit.Enabled = true;  
  6.     ButtonDelete.Enabled = true;  
  7.     ButtonUpdate.Enabled = false;  
  8.     ButtonCancel.Enabled = false;  
  9. }  
There's nothing fancy about the code above. It just basically toggles the enable property of the button when you hit the Cancel button on the form so that it will return to its default state.

Summary

In this article, we have learned about the basics of how to perform Insert, Fetch, Filter, Edit, Update and Delete using the LINQ to SQL.


Similar Articles