The DataGridView control
enables you to connect to a database and display data in tabular format.
How to use DataGridView Control
Drag and drop DataGridView control from toolbox on WindowForm.

BindData in DataGridView
Code:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class frmDataGridView : Form
{
public frmDataGridView()
{
InitializeComponent();
}
private void frmDataGridView_Load(object sender, EventArgs e)
{
//Connect to the database
string constring = "Server=(local);Database=my; User Id=sa; Password=sa";
SqlConnection sqlcon = new SqlConnection(constring);
//Open the connection
sqlcon.Open();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
// Write the query
cmd.CommandText = "select * from regform";
da.SelectCommand = cmd;
cmd.Connection = sqlcon;
da.SelectCommand = cmd;
//create a dataset
DataSet ds = new DataSet();
da.Fill(ds);
//Close the connection
sqlcon.Close();
dataGridView1.DataSource = ds.Tables[0];
}
}
}
Run the project
Data will show in DataGridView when application run.

Update data in DataGridView
Write code on Update Button.

Double click on Click event.
private void btnUpdate_Click(object sender, EventArgs e)
{
SqlCommand cmd=new SqlCommand();
// write query to update database
cmd.CommandText = "update regform set pass='"+dataGridView1.CurrentRow.Cells[1].Value+"',name='" + dataGridView1.CurrentRow.Cells[2].Value+ "' where id='" + dataGridView1.CurrentRow.Cells[0].Value + "'";
SqlConnection sqlcon = new SqlConnection(constring);
cmd.Connection = sqlcon;
// open the connection
sqlcon.Open();
cmd.ExecuteScalar();
}
Click the cell in which you want to update then change value and
click update button.

Leave Comment
2 Comments