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.
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

Popular posts from this blog

How to Create a Configuration.INI Files in VB6

How to Set Windows Form Always on Top of Other Applications in VB6

How to Minimize/Send an App Icon to System Tray in Visual Basic 6