-->

22 December 2019

Asp.Net Programmatic DataBinding

  Asp.Net CS By Example       22 December 2019


 Programmatic DataBinding:  

  When we bind a DataBound control to a DataSource control, we can take advantage of
declarative databinding. When we use declarative databinding, ASP.NET Framework handles
all the messy details of deciding when to retrieve the data items represented by a
DataSource control.

  In certain situations, we want to handle these messy details ourself. For example, we
might want to force a GridView control to refresh the data it displays after we add a new
record to a database table. Or we might want to bind a DataBound control to a data
source that can’t be easily represented by one of the existing DataSource controls. In these
situations, we want to use programmatic databinding.

  Every DataBound control has a DataSource property and a DataBind() method. By using
this property and method, we can programmatically associate a DataBound control with a
data source.

  For example, the page displays a list of all the fonts installed on our computer.

  Code: ShowFontsEx01.aspx 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ShowFontsEx01.aspx.cs"
    Inherits="LearnAsp.Net.ControlDemo.DataBound.ShowFontsEx01" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Show Fonts</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" ForeColor="#246cb3" BackColor="#e6e6e6" 
        BorderColor="#928383" runat="server" />
    </div>
    </form>
</body>
</html>

  Code: ShowFontsEx01.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing.Text;

namespace LearnAsp.Net.ControlDemo.DataBound
{
    public partial class ShowFontsEx01 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                InstalledFontCollection fonts = new InstalledFontCollection();
                GridView1.DataSource = fonts.Families;
                GridView1.DataBind();
            }
        }
    }
}

  Output:

logoblog

Thanks for reading Asp.Net Programmatic DataBinding

Previous
« Prev Post