Sql data adapter in C#  

Posted by: Quadtechindia in

using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsFormsApplication9
public partial class Form1 : Form
public Form1()

void FillData()
// 1
// Open connection
using (SqlConnection c = new SqlConnection(
// 2
// Create new DataAdapter
using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM EmployeeIDs", c))
// 3
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();

// 4
// Render data onto the screen
dataGridView1.DataSource = t; // <-- From your designer

Part 1. This creates a new SqlConnection instance. Note that you must include the System.Data.SqlClient namespace in your program. [See top of code]

Part 2. After calling Open() on the SqlConnection, we use another using block for the SqlDataAdapters. The using statements are ideal for disposing of resources, making your programs more efficient and reliable. [C# SqlClient Tutorial - dotnetperls.com]

Part 3. Here we instantiate and Fill a new DataTable. Note that the Fill method on DataTable will populate the internal rows and columns of the DataTable to match the SQL result.

Part 4. This part is commented out because it won't compile unless you have a DataGridView. We see the DataSource being assigned to the DataTable. The result will be a filled DataGridView with data from SQL Server.

This entry was posted on Wednesday, November 04, 2009 and is filed under . You can leave a response and follow any responses to this entry through the Subscribe to: Post Comments (Atom) .


Post a Comment