0% found this document useful (0 votes)
16 views

Crud

Code
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Crud

Code
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

class DBhelper

{
SqlConnection con;
public void Establishconnection()
{
string connectionstring = "Integrated Security=SSPI;Persist Security
Info=False;Initial Catalog=Student;Data Source=DESKTOP-B64FAB3\\SQLEXPRESS";
con = new SqlConnection();
con.ConnectionString = connectionstring;
if (con.State==ConnectionState.Closed)
{
con.Open();
}

public int RunQuery(string query)


{
Establishconnection();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = query;
int row= cmd.ExecuteNonQuery();
return row;
}
public DataTable GetRecord(string query)
{
Establishconnection();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = query;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
return dt;
}
}

DBhelper help = new DBhelper();


public Form1()
{
InitializeComponent();
LoadData();
}

private void btninsert_Click(object sender, EventArgs e)


{
string query = @"INSERT INTO [Student].[dbo].[studentinfo]
([ID]
,[Name]
,[F/Name]
,[Department]
,[Telephone])
VALUES

("+txtid.Text+",N'"+txtname.Text+"',N'"+txtfname.Text+"',N'"+txtdep.Text+"','"+txtt
el.Text+"')";

int count = help.RunQuery(query);


if (count>0)
{
MessageBox.Show("Record Inserted");
LoadData();
}
}

private void btnupdate_Click(object sender, EventArgs e)


{
string query = @"UPDATE [Student].[dbo].[studentinfo]
SET [ID] = "+txtid.Text+",[Name] = N'"+txtname.Text+"',[F/Name]
=N'"+txtfname.Text+"',[Department] =N'"+txtdep.Text+"',[Telephone]
=N'"+txttel.Text+"' WHERE ID="+txtid.Text+" ";

int check= help.RunQuery(query);


if (check>0)
{
MessageBox.Show("Record Updated");
LoadData();
}
}

private void btndelete_Click(object sender, EventArgs e)


{
string query = @"DELETE FROM [Student].[dbo].[studentinfo]
WHERE ID="+txtid.Text+"";
int check= help.RunQuery(query);
if (check>0)
{
MessageBox.Show("Record Deleted");
LoadData();
}
}

public void LoadData()


{
string query = @"SELECT [ID]
,[Name]
,[F/Name]
,[Department]
,[Telephone]
FROM [Student].[dbo].[studentinfo]";

DataTable dt = new DataTable();


dt = help.GetRecord(query);
gv.DataSource = dt;

private void gv_RowHeaderMouseClick(object sender,


DataGridViewCellMouseEventArgs e)
{

txtid.Text = gv.Rows[e.RowIndex].Cells[0].Value.ToString();
txtname.Text=gv.Rows[e.RowIndex].Cells[1].Value.ToString();
txtfname.Text=gv.Rows[e.RowIndex].Cells[2].Value.ToString();
txtdep.Text=gv.Rows[e.RowIndex].Cells[3].Value.ToString();
txttel.Text = gv.Rows[e.RowIndex].Cells[4].Value.ToString();
}

You might also like