Here is a really simple data binding sample. Just drag and drop a datagrid onto a default Windows Forms application. Follow the steps below to bind this grid to the NorthWind db in SQL server.
Complete Sample: simpledata.zip
// Create a connection
SqlConnection connection = new SqlConnection(this.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(this.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 this
// 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;
}
Share with