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