Complete Sample: simpledata.zip
// Create a connection
SqlConnection connection = new SqlConnection(GetConnectionString());
// Create a data adapter. Think of the data adapter as an object that knows
// how to get the data from the data source into a dataset
SqlDataAdapter dataAdapter =
new SqlDataAdapter(GetCommandText(), connection);
// fill the dataset using the data adapter
DataSet dataSet = new DataSet("Customers");
dataAdapter.Fill(this.dataSet, "Customers");
// bind to the grid
grid.DataSource = this.dataSet; // the big picture
grid.DataMember = "Customers"; // the specific table that we want to bind to
The connection text looks like the following. If your SQL server is running on the default port, you can remove the port attribute.
private string GetConnectionString()
{
string server = "your_server_name";
string serverPort = "port_address";
string catalog = "NorthWind";
string password = "user_pass";
string userId = "user_name";
string connectionString = "data source={0},{1};initial catalog={2};" +
"password={3}; user id={4}; packet size=4096";
return string.Format(connectionString, server,
serverPort, catalog, password, userId);
}
The command text looks like this:
private string GetCommandText()
{
string commandText = "Select * from customers";
return commandText;
}
Contributed from George Shepherd's Windows Forms FAQ