Looking for work? Check out our jobs area.
*/

Other Views

corner
*/

ADONET FAQ - Data Grid Example Application

How can I make my first application with DataGrid using the data from ADO.Net?

Let’s create a simple application first that loads a table data from database server to the data grid control. First of all, add a data grid control and a button to your form from Visual Studio toolbox. We have set the Name property of data grid to ‘dgDetails’ and its CaptionText property to ‘ProgrammersHeaven Database’. The name of button is ‘btnLoadData’. The event handler for button is:

C# Version
private void btnLoadData_Click(object sender, System.EventArgs e)
{
	string connectionString = "server=FARAZ; database=programmersheaven;" +
					  "uid=sa; pwd=;";
	SqlConnection conn = new SqlConnection(connectionString);
	string cmdString = "SELECT * FROM article";
	SqlDataAdapter dataAdapter = new SqlDataAdapter(cmdString, conn);
	DataSet ds = new DataSet();
	dataAdapter.Fill(ds, "article");
	dgDetails.SetDataBinding(ds, "article");
}


VB.Net Version
    Private Sub btnLoadData_Click(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles btnLoadData.Click
        Dim connectionString As String = "server=P-III; database=programmersheaven;" + _
                                         "uid=sa; pwd=;"
        Dim conn As New SqlConnection(connectionString)
        Dim cmdString As String = "SELECT * FROM article"
        Dim dataAdapter As New SqlDataAdapter(cmdString, conn)
        Dim ds As New DataSet()
        dataAdapter.Fill(ds, "article")
        dgDetails.SetDataBinding(ds, "article")
    End Sub


Here we first created data adapter and filled the data set using it as we used to do in other applications. The only new thing is the binding of “article” table to the data grid control which is done by calling the SetDataBinding() method of the DataGrid class. The first parameter of this method is the dataset while the second parameter is the name of table in the dataset.
C# Version
	dgDetails.SetDataBinding(ds, "article");


VB.Net Version
	dgDetails.SetDataBinding(ds, "article")


When you execute this program and select the Load button you will see the output presented in the previous figure.

Back
corner
© 1996-2008 CommunityHeaven LLC. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
North American business development: Nicolai Wadstrom. Publisher: Lars Hagelin.
Resource Listings