C# DataGridView Binding - SQL Server dataset

The DataGridView offers the capability to present data in three distinct modes: Bound mode, unbound mode, and Virtual mode. Bound mode, an immensely practical approach, facilitates efficient data management through automatic interaction with the underlying data store.

Binding the DataGridView

Particularly, binding the DataGridView to a database table stands out as an exceedingly prevalent usage scenario, enabling seamless integration with the existing data source. On the other hand, unbound mode is a viable option when the objective involves displaying relatively smaller data sets that can be programmatically handled. This mode allows for more hands-on control over the data presentation, empowering developers to manipulate and manage the information within the DataGridView as needed.

The following C# program shows how to bind a SQL Server dataset to a DataGridView.

Full Source C#
using System; using System.Data; using System.Windows.Forms; using System.Data.SqlClient; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"; string sql = "SELECT * FROM Authors"; SqlConnection connection = new SqlConnection(connectionString); SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection); DataSet ds = new DataSet(); connection.Open(); dataadapter.Fill(ds, "Authors_table"); connection.Close(); dataGridView1.DataSource = ds; dataGridView1.DataMember = "Authors_table"; } } }

Conclusion

For those seeking an even greater degree of control and flexibility, Virtual mode emerges as an excellent choice. With Virtual mode, the DataGridView empowers developers by postponing the provision of cell values until the precise moment they are about to be displayed. This results in heightened control and optimization, ensuring optimal performance and an efficient allocation of system resources. By deferring the retrieval and assignment of cell values until they are required for display, Virtual mode enhances the overall responsiveness and efficiency of the DataGridView.