How to bind data to a gridView control in asp.net using datatable with c#


In this article, I am going to explain with an example how to create a bind data to a gridView control in asp.net using data table with c#.

One of the most popular controls in Asp.Net is GridView control.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="gridview.aspx.cs" Inherits="gridview" %>

    <!DOCTYPE html>
    <html>
    <head>
        <title>GridView Control Data Bind In Data Table</title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:GridView ID="GridView" Font-Names="Arial" Font-Size="0.75em" runat="server">
                   
                </asp:GridView>
            </div>
        </form>
    </body>

    </html>


Source Code C#


  1. using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Data.SqlClient;

    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string constr = "Connection String";

            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT *FROM Table_Name"))
                {
                    SqlDataAdapter sda = new SqlDataAdapter();
                    try
                    {
                        cmd.Connection = con;
                        con.Open();
                        sda.SelectCommand = cmd;
                        DataTable dt = new DataTable();
                        sda.Fill(dt);
                        GridView.DataSource = dt;
                        GridView.DataBind();
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
        }
    }

.

Post a Comment

0 Comments