Tuesday, July 20, 2010

Insert Update Delete Through Linq in C#

take a Window Form Application


add a Class LINQ to SQL Classes named DataClasses1.dbml

now Double Click on DataClasses1.dbml it Design View will be open

now on it Give Database Conection and drag Table on Designer



Now make a object of DataClasses1DataContext Class and access all Clases



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 LinqImplementation

{

public partial class Form1 : Form

{

DataClasses1DataContext dc1 = null;

string ss = null;

public Form1()

{

InitializeComponent();

ss = "Data Source=(local);Initial Catalog=EMP;Integrated Security=SSPI;";

dc1 = new DataClasses1DataContext(ss);

}



private void btnSelect_Click(object sender, EventArgs e)

{



var q = from a in dc1.GetTable()

where a.ClientName.Contains("aj")

a.Salary == 20000

select a;



dataGridView1.DataSource = q;



}



private void btnSave_Click(object sender, EventArgs e)

{

try

{

Table XPCClient = dc1.GetTable();

Client cl = new Client();

cl.Oid = Guid.NewGuid();

cl.ClientName = txtclientname.Text;

cl.Salary = int.Parse(txtsalary.Text);

cl.SEX = cmbsex.SelectedIndex;

XPCClient.InsertOnSubmit(cl);

XPCClient.Context.SubmitChanges();

MessageBox.Show("Record Inserted Successfully");

}

catch (Exception ex)

{

MessageBox.Show(ex.Message+"Record Insertion Failed");

}

}



private void btnDelete_Click(object sender, EventArgs e)

{

Table XpCClient = dc1.GetTable();

var obj = (from w in XpCClient

where w.Salary == 12000

select w).FirstOrDefault();



var obj1 = XpCClient.Where(a => a.Salary == 20000).FirstOrDefault();

XpCClient.DeleteOnSubmit(obj);

XpCClient.Context.SubmitChanges();

}



private void btnUpdate_Click(object sender, EventArgs e)

{

Table XPCClient = dc1.GetTable();

var obj = from a in XPCClient

where a.Salary == Convert.ToInt32(txtsalary.Text)

select a;

Client obj1 = (from ab in XPCClient

where ab.Salary == Convert.ToInt32(txtsalary.Text)

select ab).FirstOrDefault();



if (obj == null)

MessageBox.Show("Record Not Found");

else

{

foreach (Client c in obj)

{

c.Salary = 55000;

dc1.SubmitChanges();

}

}

}

}

}



Note : Client is a Table in EMP Database

No comments:

Post a Comment

Mat Table Angular

Mat Table in Angular Mat table is used to display data . its a material designed styled data-table . For using Material Table MatTableMo...