Home > DeveloperSection > Blogs > Data Binding controls in ASP.NET

Data Binding controls in ASP.NET


.NET ASP.Net 
Ratings:
0 Comment(s)
 695  View(s)
Rate this:

Data Binding controls in ASP.NET

In this blog I will talk about Data binding controls in ASP.NET

 

Data binding is binding controls to data from database. With data binding we can bind a controls to a particular column in a  table from the database or we can  bind the whole table to the  data grid.

Data binding allows you to take the results of properties, collection, method calls, and database queries and integrate them with your ASP.NET code. You can combine data binding with Web control rendering to relieve much of the programming burden surrounding Web control creation. You can also use data binding with ADO.Net and web controls to populate control contents from SQL select statement or stored procedures.

Data binding uses a special syntax:

<%# %>

There are three types of binding:

1.      Declarative Binding

2.      Static  Binding

3.      Programmatically Binding

 

Data Bound Controls

1.      Single-item data bound controls

2.       Multi-item data bound controls

 

Single item data bound controls

1. Text

2. Label

3. Button

4. Image

Multi item data bound controls

1.      DataGrid

2.      Datalist

3.      ListBox

4.      DropDownListBox

5.      Repeater

6.      Formview

7.      DropdownList

8.      CheckBoxList

9.      RadioButtonList

 

 

HierarchicalDataBoundControl class:

1.      Treeview

2.      MenuSitePath

 

//Treeview control

 <asp:TreeView ID="TreeView1" runat="server" DataSourceID="XmlDataSource1"></asp:TreeView>

//MenuSitePath control

 

<asp:SiteMapPath ID="SiteMapPath1" runat="server">

                    </asp:SiteMapPath>

//Gridview control

 

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1">

            <Columns>

                <asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" InsertVisible="False" ReadOnly="True" SortExpression="EmployeeID" />

                <asp:BoundField DataField="DateOfBirth" HeaderText="DateOfBirth" SortExpression="DateOfBirth" />

                <asp:BoundField DataField="State" HeaderText="State" SortExpression="State" />

                <asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />

            </Columns>

        </asp:GridView>

//FormView control

 <asp:FormView ID="FormView1" runat="server" DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1">

            <EditItemTemplate>

                EmployeeID:

                <asp:Label ID="EmployeeIDLabel1" runat="server" Text='<%# Eval("EmployeeID") %>' />

                <br />

                DateOfBirth:

                <asp:TextBox ID="DateOfBirthTextBox" runat="server" Text='<%# Bind("DateOfBirth") %>' />

                <br />

                State:

                <asp:TextBox ID="StateTextBox" runat="server" Text='<%# Bind("State") %>' />

                <br />

                FirstName:

                <asp:TextBox ID="FirstNameTextBox" runat="server" Text='<%# Bind("FirstName") %>' />

                <br />

                <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" />

                &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />

            </EditItemTemplate>

            <InsertItemTemplate>

                DateOfBirth:

                <asp:TextBox ID="DateOfBirthTextBox" runat="server" Text='<%# Bind("DateOfBirth") %>' />

                <br />

                State:

                <asp:TextBox ID="StateTextBox" runat="server" Text='<%# Bind("State") %>' />

                <br />

                FirstName:

                <asp:TextBox ID="FirstNameTextBox" runat="server" Text='<%# Bind("FirstName") %>' />

                <br />

                <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert" Text="Insert" />

                &nbsp;<asp:LinkButton ID="InsertCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />

            </InsertItemTemplate>

            <ItemTemplate>

                EmployeeID:

                <asp:Label ID="EmployeeIDLabel" runat="server" Text='<%# Eval("EmployeeID") %>' />

                <br />

                DateOfBirth:

                <asp:Label ID="DateOfBirthLabel" runat="server" Text='<%# Bind("DateOfBirth") %>' />

                <br />

                State:

                <asp:Label ID="StateLabel" runat="server" Text='<%# Bind("State") %>' />

                <br />

                FirstName:

                <asp:Label ID="FirstNameLabel" runat="server" Text='<%# Bind("FirstName") %>' />

                <br />

 

            </ItemTemplate>

        </asp:FormView>

 

Example:

Create a EmployeeDetail.aspx

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

 

<!DOCTYPE html>

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

        <table>

            <tr>

                <td colspan="2" style="text-align: right">

                    <%

                        var role = Session["RoleName"] != null ? Session["RoleName"].ToString() : "";

                    %>

                   

                    <asp:Button ID="Logout" runat="server" Text="Logout" OnClick="Logout_Click" />

                    <%if (!string.IsNullOrEmpty(role) && role == "User")

                      { %>

                    <asp:Button ID="Button2" runat="server" Text="Change Password" OnClick="Button2_Click" Visible="true" />

                    <%}else{ %>

                    <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Default.aspx">New Registration</asp:HyperLink>

                    <%} %>

                     

                </td>

            </tr>

            <tr>

                <td colspan="2">

//Databinding in Gridview

                    <asp:GridView ID="Records" runat="server" AutoGenerateColumns="False" DataKeyNames="id" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowCancelingEdit="Records_RowCancelingEdit" OnRowDeleting="Records_RowDeleting" OnRowEditing="Records_RowEditing" OnRowUpdating="Records_RowUpdating" OnRowDataBound="Records_RowDataBound" OnRowCommand="Records_RowCommand">

                        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />

                    

                        <Columns>

                            

                            <asp:TemplateField HeaderText="id">

                                 

                                <EditItemTemplate>

//Databinding in label

 

                                    <asp:Label ID="lblID" runat="server" Text='<%# Bind("id") %>'></asp:Label>

 

                                </EditItemTemplate>

                                <ItemTemplate>

                                    <asp:Label ID="Label10" runat="server" Text='<%# Bind("id") %>'></asp:Label>

                                </ItemTemplate>

                            </asp:TemplateField>

                            <asp:TemplateField HeaderText="FirstName">

                                <EditItemTemplate>

//Databinding in textbox

 

                                    <asp:TextBox ID="EditFirstName" runat="server" Text='<%# Bind("FirstName") %>'></asp:TextBox>

                                </EditItemTemplate>

                                <ItemTemplate>

                                    <asp:Label ID="Label9" runat="server" Text='<%# Bind("FirstName") %>'></asp:Label>

                                </ItemTemplate>

                            </asp:TemplateField>

                            <asp:TemplateField HeaderText="LastName">

                                <EditItemTemplate>

                                    <asp:TextBox ID="EditLastName" runat="server" Text='<%# Bind("LastName") %>'></asp:TextBox>

                                </EditItemTemplate>

                                <ItemTemplate>

                                    <asp:Label ID="Label8" runat="server" Text='<%# Bind("LastName") %>'></asp:Label>

                                </ItemTemplate>

                            </asp:TemplateField>

                            <asp:TemplateField HeaderText="Address">

                                <EditItemTemplate>

                                    <asp:TextBox ID="EditAddress" runat="server" Text='<%# Bind("Address") %>'></asp:TextBox>

                                </EditItemTemplate>

                                <ItemTemplate>

                                    <asp:Label ID="Label7" runat="server" Text='<%# Bind("Address") %>'></asp:Label>

                                </ItemTemplate>

                            </asp:TemplateField>

                            <asp:TemplateField HeaderText="FatherName">

                                <EditItemTemplate>

 

                                    <asp:TextBox ID="EditFatherName" runat="server" Text='<%# Bind("FatherName") %>'></asp:TextBox>

                                </EditItemTemplate>

                                <ItemTemplate>

                                    <asp:Label ID="Label6" runat="server" Text='<%# Bind("FatherName") %>'></asp:Label>

                                </ItemTemplate>

                            </asp:TemplateField>

                            <asp:TemplateField HeaderText="MotherName">

                                <EditItemTemplate>

                                    <asp:TextBox ID="EditMotherName" runat="server" Text='<%# Bind("MotherName") %>'></asp:TextBox>

                                </EditItemTemplate>

                                <ItemTemplate>

                                    <asp:Label ID="Label5" runat="server" Text='<%# Bind("MotherName") %>'></asp:Label>

                                </ItemTemplate>

                            </asp:TemplateField>

                            <asp:TemplateField HeaderText="MobileNo">

                                <EditItemTemplate>

                                    <asp:TextBox ID="EditMobileNo" runat="server" Text='<%# Bind("MobileNo") %>'></asp:TextBox>

                                </EditItemTemplate>

                                <ItemTemplate>

                                    <asp:Label ID="Label4" runat="server" Text='<%# Bind("MobileNo") %>'></asp:Label>

                                </ItemTemplate>

                            </asp:TemplateField>

 

                            <asp:TemplateField HeaderText="Role">

                                <EditItemTemplate>

                                     <% int userId = (int)Eval("id"); %>

                                    <%if (Session["RoleName"].ToString() == "Admin" && Convert.ToInt32(Session["userid"]) != userId)

                                      { %>

                                    <asp:DropDownList ID="drpEditRole" runat="server" DataSourceID="SqlDataSource1" DataTextField="RoleName" DataValueField="RoleId" AutoPostBack="true"></asp:DropDownList>

                                    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:PriyankaDBConnectionString %>" SelectCommand="SELECT * FROM [RoleTable]"></asp:SqlDataSource>

                                    <%}

                                      else

                                      { %>

                                    <asp:Label ID="EditRole" runat="server" Text='<%# Bind("RoleName") %>'></asp:Label>

                                    <%} %>

                                </EditItemTemplate>

                                <ItemTemplate>

                                    <asp:Label ID="LabelRole" runat="server" Text='<%# Bind("RoleName") %>'></asp:Label>

                                </ItemTemplate>

                            </asp:TemplateField>

                            <asp:TemplateField HeaderText="DOB">

                                <EditItemTemplate>

                                    <asp:TextBox ID="EditDOB" runat="server" Text='<%# Bind("DOB") %>'></asp:TextBox>

                                </EditItemTemplate>

                                <ItemTemplate>

                                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("DOB") %>'></asp:Label>

                                </ItemTemplate>

                            </asp:TemplateField>

                            <asp:TemplateField HeaderText="Edit" ShowHeader="False">

                                <EditItemTemplate>

                                    <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>

                                    &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>

                                </EditItemTemplate>

                                <ItemTemplate>

                                    <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>

                                </ItemTemplate>

                            </asp:TemplateField>

                            <asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />

 

                        </Columns>

                        <EditRowStyle BackColor="#999999" />

                        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />

                        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />

                        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />

                        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />

                        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />

                        <SortedAscendingCellStyle BackColor="#E9E7E2" />

                        <SortedAscendingHeaderStyle BackColor="#506C8C" />

                        <SortedDescendingCellStyle BackColor="#FFFDF8" />

                        <SortedDescendingHeaderStyle BackColor="#6F8DAE" />

                    </asp:GridView>

                </td>

            </tr>

            <tr>

                <td colspan="2">

                    <asp:Label ID="msg" runat="server" Text=""></asp:Label></td>

            </tr>

        </table>

  </form>

</body>

</html>

 

Example of Programmatically Binding

Write in EmployeeDetail.axpx.cs

 

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;

using System.Configuration;

public partial class EmployeeDetail : System.Web.UI.Page

{

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cons"].ConnectionString);

    SqlCommand cmd;

  

    void GridViewBind()

    {

        cmd = new SqlCommand();

        try

        {

            con.Open();

            cmd.Connection = con;

            DataTable dt = new DataTable();

            if (Session["RoleName"] != null && Session["RoleName"].ToString() == "Admin")

            {

                cmd = new SqlCommand(@"select t1.id,t1.FirstName,t1.LastName,t1.Address,t1.FatherName,t1.MotherName,t1.MobileNo,t1.DOB,t2.RoleName,t1.Password from

 EmployeeDetail t1 , RoleTable t2 where t1.RoleId=t2.RoleId", con);

            }

            else

            {

                cmd.CommandText = "PriyankaDBSelect";

                cmd.Parameters.Add(new SqlParameter("@id", Session["userid"].ToString()));

                cmd.Parameters.Add(new SqlParameter("@Password", Session["password"].ToString()));

                cmd.CommandType = CommandType.StoredProcedure;

                cmd.ExecuteNonQuery();

 

            }

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            da.Fill(dt);

            if (dt.Rows.Count > 0)

            {

                Records.DataSource = dt;

                Records.DataBind();

            }

            else

            {

 

                dt.Rows.Add(dt.NewRow());

                Records.DataSource = dt;

                Records.DataBind();

                int columncount = Records.Rows[0].Cells.Count;

                Records.Rows[0].Cells.Clear();

                Records.Rows[0].Cells.Add(new TableCell());

                Records.Rows[0].Cells[0].ColumnSpan = columncount;

                Records.Rows[0].Cells[0].Text = "No Records Found";

            }

        }

        catch (Exception e)

        {

        }

        finally

        {

            con.Close();

        }

    }

 

    protected void Page_Load(object sender, EventArgs e)

    {

 

        if (Session["userid"] != null)

        {

 

            if (!IsPostBack)

            {

                GridViewBind();

 

            }

        }

        else

            Response.Redirect("login.aspx");

}

  protected void Records_RowEditing(object sender, GridViewEditEventArgs e)

    {

Records.EditIndex = e.NewEditIndex;

 GridViewBind();

    }

    DropDownList Rolelist;

    protected void Records_RowUpdating(object sender, GridViewUpdateEventArgs e)

    {  int userid = Convert.ToInt32(Records.DataKeys[e.RowIndex].Value.ToString());

        GridViewRow row = (GridViewRow)Records.Rows[e.RowIndex];

        Label lblID = (Label)row.FindControl("lblID");

        TextBox FirstName = (TextBox)Records.Rows[e.RowIndex].FindControl("EditFirstName");

        TextBox LastName = (TextBox)Records.Rows[e.RowIndex].FindControl("EditLastName");

        TextBox Address = (TextBox)Records.Rows[e.RowIndex].FindControl("EditAddress");

        TextBox FatherName = (TextBox)Records.Rows[e.RowIndex].FindControl("EditFatherName");

        TextBox MotherName = (TextBox)Records.Rows[e.RowIndex].FindControl("EditMotherName");

        TextBox MobileNo = (TextBox)Records.Rows[e.RowIndex].FindControl("EditMobileNo");

        TextBox Password = (TextBox)Records.Rows[e.RowIndex].FindControl("EditPassword");

        if (Session["RoleName"].ToString() == "Admin")

        {

             Rolelist = (DropDownList)Records.Rows[e.RowIndex].FindControl("drpEditRole");

        }

        else

        {

            Label Role = (Label)Records.Rows[e.RowIndex].FindControl("EditRole");

        }

  TextBox DOB = (TextBox)Records.Rows[e.RowIndex].FindControl("EditDOB");

        cmd = new SqlCommand();

        if (Session["RoleName"].ToString() == "User")

        {

            try

            {

                con.Open();

                cmd.Connection = con;

                cmd.CommandText = "PriyankaDBUpdate";

                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add(new SqlParameter("@FirstName", FirstName.Text));

                cmd.Parameters.Add(new SqlParameter("@LastName", LastName.Text));

                cmd.Parameters.Add(new SqlParameter("@Address", Address.Text));

                cmd.Parameters.Add(new SqlParameter("@FatherName", FatherName.Text));

                cmd.Parameters.Add(new SqlParameter("@MotherName", MotherName.Text));

                cmd.Parameters.Add(new SqlParameter("@MobileNo", MobileNo.Text));

                cmd.Parameters.Add(new SqlParameter("@DOB", DOB.Text));

                cmd.Parameters.Add(new SqlParameter("@id", userid));

                cmd.ExecuteNonQuery();

            }

            catch (Exception ex)

            {

            }

            finally

            {

                con.Close();

            }

        }

        if (Session["RoleName"].ToString() == "Admin")

        {

        try

        {

            con.Open();

            cmd.Connection = con;

            cmd.CommandText = "update EmployeeDetail set FirstName=@FirstName,LastName=@LastName,Address=@Address,FatherName=@FatherName,MotherName=@MotherName,MobileNo=@MobileNo,DOB=@DOB,RoleId=@RoleName  where id=@id";

            cmd.CommandType = CommandType.Text;

            cmd.Parameters.Add(new SqlParameter("@FirstName", FirstName.Text));

            cmd.Parameters.Add(new SqlParameter("@LastName", LastName.Text));

            cmd.Parameters.Add(new SqlParameter("@Address", Address.Text));

            cmd.Parameters.Add(new SqlParameter("@FatherName", FatherName.Text));

            cmd.Parameters.Add(new SqlParameter("@MotherName", MotherName.Text));

            cmd.Parameters.Add(new SqlParameter("@MobileNo", MobileNo.Text));

            cmd.Parameters.Add(new SqlParameter("@DOB", DOB.Text));

            cmd.Parameters.Add(new SqlParameter("@RoleName", Rolelist.SelectedValue));

            cmd.Parameters.Add(new SqlParameter("@id",userid));

          int i=  cmd.ExecuteNonQuery();

        }

        catch (Exception ex)

        {

        }

        finally

        {

          con.Close();

        }

 

        }

 

    }

    protected void Records_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

    {

        Records.EditIndex = -1;

        GridViewBind();

    }

    protected void Records_RowDeleting(object sender, GridViewDeleteEventArgs e)

    {

        cmd = new SqlCommand();

        GridViewRow row = (GridViewRow)Records.Rows[e.RowIndex];

        Label lbldeleteid = (Label)row.FindControl("lblID");

    

        int grid = Convert.ToInt32(Records.DataKeys[e.RowIndex].Value.ToString());

        int x = 0;

        try

        {

            con.Open();

            cmd.Connection = con;

            cmd.CommandText = "PriyankaDBDelete";

            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add(new SqlParameter("@id", grid));

            int userid = Convert.ToInt16(Session["userid"]);

 

            if (userid != grid)

            {

                x = cmd.ExecuteNonQuery();

            }

            if (x > 0)

            {

                GridViewBind();

                msg.Text = "successfully Deleted ";

            }

            else

            {

                msg.Text = "can not delete your record";

            }

        }

        catch (Exception exc)

        {

        }

        finally

        {

            con.Close();

        }

        Records.EditIndex = -1;

        GridViewBind();

    }

    protected void Records_RowDataBound(object sender, GridViewRowEventArgs e)

    {

        string role = Session["RoleName"].ToString();

        if (role == "User")

        {

            Records.Columns[10].Visible = false;

            Button2.Visible = true;

        }

     }

    protected void Logout_Click(object sender, EventArgs e)

    {

        Session.Clear();

        Response.Redirect("login.aspx");

 

    }

    protected void Button2_Click(object sender, EventArgs e)

    {

 

        Response.Redirect("ChangePasswordForm.aspx");

    }

    protected void BtnAdmin_Click(object sender, EventArgs e)

    {

        Response.Redirect("RoleForm.aspx");

    }

 

    protected void Records_RowCommand(object sender, GridViewCommandEventArgs e)

    {

      

       

   }

   

}

Output

 

 


Don't want to miss updates? Please click the below button!

Follow MindStick