C# - DataGrid Control

The DataGrid control is a table driven. It is ideal for displaying information that contains many elements or fields or many rows and columns

The DataGrid control also provides many advanced features that make it the right choice for many programming tasks. For example, ou can use the DataGrid control for selecting items, sorting, paging, and editing in place.

Using DataGrid Control

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Data" %>


<script language="C#" runat="server">


void Page_Load(object src, EventArgs e){
      //Create Instance of Connection and Command object
      SqlConnection cn = new SqlConnection("server=localhost;uid=sa;pwd=;
                                                                                          database=Northwind");
      SqlDataAdapter adapter = new SqlDataAdapter("Select * from products", cn);


      DataSet ds = new DataSet();
      adapter.Fill(ds, "products");
    
     mygrid.DataSource = ds.Tables["products"];
     mygrid.DataBind();

}
</script>


<html>
<head>
  <title>Basic DataGrid Example</title>
</head>
<body>
<asp:datagrid id="mygrid" runat="server" />

</body>
</html>

The definition of the DataGrid control is quite simple, and it actually contains only one line. When the DataBind() method is invoked, the DataGrid control automatically builds the table by creating a column for every data field and a row for every record. It even builds a header, using field names in the data source. The output will be as the following.

Output