Populate Data into DataGridView using DataTable in C#/CSharp
The following snippet allows to populate data into DataGridView Control using DataTable in CSharp.
First, we establish a connection to our database.
This DataTable returns the Books Table.
We call this function to set prepare the DataTable and set it as the DataSource of the DataGridView Control.
First, we establish a connection to our database.
string sConnect = "Data Source=" + Properties.Settings.Default.Server + ";Initial Catalog=" + Properties.Settings.Default.Database + ";"; if (Properties.Settings.Default.UseIntegratedSecurity) sConnect += "Integrated Security=SSPI;"; else sConnect += "User Id=" + Properties.Settings.Default.Username + ";Password=" + Properties.Settings.Default.Password + ";"; this.sSQLConnectString = sConnect;
This DataTable returns the Books Table.
public DataTable GetBooks() { string sql = "select * from Book order by ISBN13, ISBN10"; SqlDataAdapter da = new SqlDataAdapter(sql, sqlConnection); try { DataTable dt = new DataTable(); da.Fill(dt); return dt; } catch (Exception ex) { throw ex; } }
We call this function to set prepare the DataTable and set it as the DataSource of the DataGridView Control.
private void loadBooks() { if (!this.bConnectedToDatabase) return; DataOperations dbo = new DataOperations(sSQLConnectString); DataTable dt = dbo.GetBooks(); this.dgvBooks.DataSource = dt; }
Comments
Post a Comment