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.
We review important members (methods, events and properties) on SqlDataAdapter
. We should include the System.Data
namespace to access this type.
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.
SqlConnection
instance. Note that you must include the System.Data.SqlClient
namespace in your program.DataTable
. Fill()
will populate the internal rows and columns of the DataTable
to match the SQL result.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 is the most important method on the DataAdapter
objects. It executes the query and fills the DataAdapter
object with the results.
OnFillError
is an event that allows you to listen to when an error occurred when filling the DataTable
.GetFillParameters()
allows you to get the parameters that are being used in a SELECT statement.LoadOption
is an enumeration of the options you can use when the DataAdapter
is loaded. You can specify OverwriteChanges
, PreserveChanges
and Upsert.
AcceptChanges
method when you want to accept all changes made to the row.We used SqlDataAdapter
, part of the System.Data.SqlClient
namespace. There are many members of SqlDataAdapter
. We touched on SqlCeDataAdapter
, which is similar.