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
{
publicpartialclass frmDataGridView : Form
{
public frmDataGridView()
{
InitializeComponent();
}
privatevoid frmDataGridView_Load(object sender, EventArgs e)
{
//Connect to the database
string constring = "Server=(local);Database=my; User Id=sa; Password=sa";
SqlConnection sqlcon = newSqlConnection(constring);
//Open the connection
sqlcon.Open();
SqlCommand cmd = newSqlCommand();
SqlDataAdapter da = newSqlDataAdapter();
// Write the query
cmd.CommandText = "select * from regform";
da.SelectCommand = cmd;
cmd.Connection = sqlcon;
da.SelectCommand = cmd;
//create a dataset
DataSet ds = newDataSet();
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.
privatevoid btnUpdate_Click(object sender, EventArgs e)
{
SqlCommand cmd=newSqlCommand();
// 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 = newSqlConnection(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.
Anonymous User
05-Apr-2019Thanks for sharing.
Samuel Fernandes
26-Jul-2017Thanks for sharing informative post.