articles

Home / DeveloperSection / Articles / DataGridView Control in C#.Net

DataGridView Control in C#.Net

Anonymous User14980 24-Jan-2011

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.

DataGridView Control in C#.Net

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.

DataGridView Control in C#.Net

Update data in DataGridView

Write code on Update Button.

DataGridView Control in C#.Net

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.

DataGridView Control in C#.Net



Updated 19-Mar-2020
I am a content writter !

Leave Comment

Comments

Liked By