C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: SqlDataAdapter doesn't require the DataGridView. However, DataGridViews are a common usage.
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 your programs more efficient and reliable.
SqlClientPart 3: We instantiate and Fill a new DataTable. The Fill method will populate the internal rows and columns of the DataTable to match the SQL result.
Part 4: This part is commented out. The DataSource is assigned to the DataTable. The result will be a filled DataGridView with data from SQL Server.
C# program that uses SqlDataAdapter type
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
FillData();
}
void FillData()
{
// 1
// Open connection
using (SqlConnection c = new SqlConnection(
Properties.Settings.Default.DataConnectionString))
{
c.Open();
// 2
// Create new DataAdapter
using (SqlDataAdapter a = new SqlDataAdapter(
"SELECT * FROM EmployeeIDs", c))
{
// 3
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
// 4
// Render data onto the screen
// dataGridView1.DataSource = t; // <-- From your designer
}
}
}
}
}
OnFillError: This is an event that allows you to listen to when an error occurred when filling the DataTable.
GetFillParameters: This allows you to get the parameters that are being used in a SELECT statement.
AcceptChangesDuringUpdate: You code can use the AcceptChanges method when you want to accept all changes made to the row.