Home
Manage Your Code
Snippet: Rebind DatagridView (C#)
Title: Rebind DatagridView Language: C#
Description: Rebinding/refreshing of DataGridView after Inserting, Deleting and Updating of data. Views: 182
Author: Juan Rodrigo Villanueva Date Added: 1/29/2008
Copy Code  
1private void FillDataSet() 
2        {           
3            String selectcommand = "SELECT EmployeeID, LastName, FirstName, MiddleName, Age, Birthday, MobileNumber, EmailAddress FROM Test";
4            GetData(selectcommand);            
5        }
6
7
8private void GetData(string selectCommand)
9        {          
10
11            try
12            {
13                // Create a new data adapter based on the specified query.

14                dataAdapter = new SqlDataAdapter(selectCommand, connection());
15
16                // Create a command builder to generate SQL update, insert, and

17                // delete commands based on selectCommand. These are used to

18                // update the database.

19                SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
20
21                // Populate a new data table and bind it to the BindingSource.

22                DataTable table = new DataTable();
23                table.Locale = System.Globalization.CultureInfo.InvariantCulture;
24                dataAdapter.Fill(table);
25                dgvEmployee.DataSource = table;
26
27                // Resize the DataGridView columns to fit the newly loaded content.

28               //dgvEmployee.AutoResizeColumns(

29               //     DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);

30            }
31            catch (SqlException)
32            {
33                MessageBox.Show("To run this example, replace the value of the " +
34                    "connectionString variable with a connection string that is " +
35                    "valid for your system.");
36            }
37        }
38