SqlDataAdapter. This C# class interacts with the DataTable type. It can be used to fill a DataTable with a table from your SQL Server database.
Type notes. We review important members (methods, events and properties) on SqlDataAdapter. We should include the System.Data namespace to access this type.
Example. You can change the SELECT command to use a table from a custom database. You may also need to add a DataGridView to the Windows Forms program.
Part 1 This creates a new SqlConnection instance. Note that you must include the System.Data.SqlClient namespace in your program.
Part 2 We use another using block. The using statements are ideal for disposing of resources, making programs more efficient and reliable.
Part 3 We instantiate and Fill a new DataTable. Fill() will populate the internal rows and columns of the DataTable to match the SQL result.
Part 4 The DataSource is assigned to the DataTable. The result will be a filled DataGridView with data from SQL Server.
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
FillData();
}
void FillData()
{
// Part 1: open connection.
using (SqlConnection c = new SqlConnection( Properties.Settings.Default.DataConnectionString))
{
c.Open();
// Part 2: create new DataAdapter.
using (SqlDataAdapter a = new SqlDataAdapter( "SELECT * FROM EmployeeIDs", c))
{
// Part 3: Use DataAdapter to fill DataTable.
DataTable t = new DataTable();
a.Fill(t);
// Part 4: render data onto the screen.// dataGridView1.DataSource = t;
}
}
}
}
}
Fill. Fill is the most important method on the DataAdapter objects. It executes the query and fills the DataAdapter object with the results.
Note OnFillError is an event that allows you to listen to when an error occurred when filling the DataTable.
Note 2 GetFillParameters() allows you to get the parameters that are being used in a SELECT statement.
Options. LoadOption is an enumeration of the options you can use when the DataAdapter is loaded. You can specify OverwriteChanges, PreserveChanges and Upsert.
Tip Your code can use the AcceptChanges method when you want to accept all changes made to the row.
Summary. We used SqlDataAdapter, part of the System.Data.SqlClient namespace. There are many members of SqlDataAdapter. We touched on SqlCeDataAdapter, which is similar.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 24, 2024 (simplify).