Insert, update and delete data using DataGridView
You can use DataGridView to fetch all the data from SQL server 2005 and then perform insert, update and delete directly in gridview then make save changes all at once.(in window application(C#)).
First Create Table in SQL server 2005:
Student
id int not null,
name Varchar(50) null,
Age int not null,
And insert some data...
then try following code....
write following code in page_load event...
//Bind datagrid using dataset and create all command.
public Form2()
{
InitializeComponent();
bs.DataSource = table;
this.dataGridView1.DataSource = bs;
string connstr = "Data Source=SD2-1\\SQLEXPRESS;Initial Catalog=datagrid;Integrated Security=True";
conn.ConnectionString = connstr;
string selectsql = "select * from student";
da.SelectCommand = new SqlCommand(selectsql, conn);
SqlCommand insercommand = new SqlCommand("insert into student(id,name,age) values(@id,@name,@age)", conn);
insercommand.Parameters.Add("@id", SqlDbType.Int, 4, "ID");
insercommand.Parameters.Add("@name", SqlDbType.VarChar, 50, "Name");
insercommand.Parameters.Add("@age", SqlDbType.Int, 4, "Age");
da.InsertCommand = insercommand;
SqlCommand updatecommand = new SqlCommand("update student set name=@name,age=@age where (id=@id)", conn);
updatecommand.Parameters.Add("@id", SqlDbType.Int, 4, "ID");
updatecommand.Parameters.Add("@name", SqlDbType.VarChar, 50, "Name");
updatecommand.Parameters.Add("@age", SqlDbType.Int, 4, "Age");
da.UpdateCommand = updatecommand;
SqlCommand deletecommand = new SqlCommand("delete student where id=@id", conn);
//deletecommand.Transaction = tran;
deletecommand.Parameters.Add("@id", SqlDbType.Int, 4, "ID");
da.DeleteCommand = deletecommand;
conn.Open();
da.Fill(table);
conn.Close();
}
//Save changes all at once on button click event..
private void button1_Click(object sender, EventArgs e)
{
try
{
da.Update(table);
}
catch(Exception ex)
{
label1.text=ex.message;
}
}
I like it that's great