DataGrid and SQL Server 2000 Data Binding
Select blog from powerchow
Add a DataGrid Control datagrid1 to the webform page. You only need to click a few mouse points to manually bind the DataGrid Control with sqlserver. Here isCodeBIND.
First, add the sqlclient namespace to the namespace.
Usingsystem. Data. sqlclient;
Then, create a data connection con in the page loading event,
Sqlconnectioncon = newsqlconnection ();
Con. connectionstring = "Server = (local); database = yourdatabase; trusted_connection = yes ";
Open the data connection,
Con. open ();
Create a Data command COM,
Sqlcommandcom = newsqlcommand ();
Com. commandtext = "select * fromyourtable ";
Com. Connection = con;
This allows you to start data binding in many ways. The simplest way is to directly use the executereader method of the Data command. Data Binding is to set the datasource attribute of the control.
Datagrid1.datasource = com. executereader ();
You can also use the data reader sqldatareader (cannot use its constructor). The Code is as follows:
Sqldatareaderdr = com. executereader ();
Datagrid1.datasource = Dr;
Of course, you can also use the core data set and data adapter of ADO. net;
Sqldataadapterada = newsqldataadapter (COM. commandtext, con );
Datasetset1 = newdataset ();
Ada. Fill (set1 );
Datagrid1.datasource = set1;
Finally, calculate the data binding expression,
Datagrid1.databind ();