Windows Forms: Linq To Sql using Stored Procedure in C#
By FoxLearn 7/24/2017 10:11:20 PM 7.73K
An overview of using stored procedures with LINQ to SQL in C# Windows Forms
Step 1: Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "LinqToSQL" and then click OK
Step 2: Design your form as below
Step 3: Create a Linq to sql model, then select Category table, GetProductByCateogryId stored from northwind database
You can create a GetProductByCategoryId stored as below
CREATE procedure [dbo].[GetProductByCategoryId] ( @CategoryId int ) as select *from Products where CategoryID = @CategoryId
Step 4: Add code to handle your form as below
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 LinqToSQL { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { using(ModelDataContext db = new ModelDataContext()) { //Get category from northwind database cboCategory.DataSource = db.Categories.ToList(); cboCategory.DisplayMember = "CategoryName"; cboCategory.ValueMember = "CategoryID"; Category obj = cboCategory.SelectedItem as Category; if (obj != null) dataGridView.DataSource = db.GetProductByCategoryId(obj.CategoryID); } } private void cboCategory_SelectionChangeCommitted(object sender, EventArgs e) { Category obj = cboCategory.SelectedItem as Category; if (obj != null) { using(ModelDataContext db = new ModelDataContext()) { //Call stored procedure dataGridView.DataSource = db.GetProductByCategoryId(obj.CategoryID); } } } } }
VIDEO TUTORIALS
Categories
Popular Posts
How to Download Chromedriver for Selenium
08/29/2024
C# Tutorial
07/20/2024
How to Download Microsoft SQL Server
06/22/2024
What is ARM architecture?
04/01/2024