Data Controls
For understanding data controls design form like shown in below picture and take datagrid view control from toolbox. And add new database from solution explorer by choosing new item. Add namespace-
using System.Data.SqlClient;
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename= D:\Documents
and Settings\R4R\My Documents\Visual Studio 2008\Projects\WindowsFormsApplication14
\WindowsFormsApplication14\r4r.mdf;Integrated Security=True;User Instance=True");
Now i want to insert record in database by clicking on insert button. Code for this is given below-
Code for inserting Data in Database-
private void button1_Click(object sender, EventArgs e)
{
SqlCommand com = new SqlCommand("insert into emp_detail values('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"')",con);
con.Open();
com.ExecuteNonQuery();
con.Close();
} |
private void button4_Click(object sender, EventArgs e)
{
SqlCommand com2 = new SqlCommand("select * from emp_detail",con);
SqlDataAdapter da = new SqlDataAdapter(com2);
DataSet ds = new DataSet();
con.Open();
da.Fill(ds, "emp_detail");
con.Close();
dataGridView1.DataSource = ds.Tables[0];
} |
string name, address, sal, cont;
private void button2_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
if (row.Index != dataGridView1.Rows.Count)
{
id = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
name= dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
address = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
sal = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
cont = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
dataGridView1.Rows.RemoveAt(row.Index);
}
}
SqlCommand com3 = new SqlCommand("update emp_detail set emp_name='"+name+"',emp_address='"+
address+"',emp_sal='"+sal+"',emp_cont='"+cont+"' where emp_id ='" + id + "'", con);
con.Open();
com3.ExecuteNonQuery();
con.Close();
} |
Code for Deleting the recording from Datagridview control-
private void button3_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
if (row.Index != dataGridView1.Rows.Count)
{
id = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
dataGridView1.Rows.RemoveAt(row.Index);
}
}
SqlCommand com3 = new SqlCommand("delete from emp_detail where emp_id ='"+id+"'",con);
con.Open();
com3.ExecuteNonQuery();
con.Close();
} |
No comments:
Post a Comment