Code Heaven For C# Developer

Friday, July 23, 2010

Insert,Update,Delete with LINQ.....

Here i am going to do simple INSERT,DELETE and UPDATE with LINQ....




Add DataClasses1.dbml in ur solution.
and then write the following code ...


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Linq;


namespace LinqOperation
{
public partial class Form1 : Form
{
DataClasses1DataContext dc = null;
public Form1()
{
InitializeComponent();
dc = new DataClasses1DataContext();
}

private void Form1_Load(object sender, EventArgs e)
{

RefreshGrid();


}
public void RefreshGrid()
{
Table XPC = dc.GetTable();

var q = from x in XPC
select x;

var data = dc.GetTable();
dataGridView1.DataSource = q;


}

private void Add_Click(object sender, EventArgs e)
{

if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text) ||string.IsNullOrEmpty(textBox3.Text))
else
{
Table XPC = dc.GetTable();
Customer cs = new Customer { id = int.Parse(textBox1.Text), Names = textBox2.Text, Grade = textBox3.Text };

XPC.InsertOnSubmit(cs);
XPC.Context.SubmitChanges();
}
RefreshGrid();
textBox1.Text = null;
textBox2.Text = null;
textBox3.Text = null;

}

private void Update_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text) || string.IsNullOrEmpty(textBox3.Text))
MessageBox.Show("Plz enter all the entries");
else
{
Table XPC = dc.GetTable();
Customer w = XPC.Where(a => a.id == int.Parse(textBox1.Text)).FirstOrDefault();
if (w == null)
MessageBox.Show("Record not found");
else
{
w.Grade = textBox3.Text;
w.Names = textBox2.Text;
XPC.Context.SubmitChanges();
}
}
RefreshGrid();
textBox1.Text = null;
textBox2.Text = null;
textBox3.Text = null;
}

private void Delete_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
Table XPC = dc.GetTable();
XPC.DeleteOnSubmit(XPC.Where(a => a.id == int.Parse(textBox1.Text)).FirstOrDefault());
XPC.Context.SubmitChanges();
RefreshGrid();
}
else
{
MessageBox.Show("Enter the Id");
}
textBox1.Text = null;
textBox2.Text = null;
textBox3.Text = null;
}
}
}

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home