-->

06 February 2020

Asp.Net GridView TemplateFields 

  Asp.Net CS By Example       06 February 2020
 GridView TemplateFields 

 A TemplateField enables we to add any content to a GridView column that we need, which can contain HTML, DataBinding expressions, or ASP.NET controls. TemplateFields are particularly useful when we use GridView to edit database records. we can use TemplateField to customize the user interface and add validation to the fields being edited.

 TemplateField supports the following six types of templates:

Sr.No Property Description
1) AlternatingItemTemplate The contents of this template display for every other row rendered by GridView
2) EditItemTemplate The contents of this template display when a row is selected for editing
3) FooterTemplate The contents of this template display in the column footer
4) HeaderTemplate The contents of this template display in the column header
5) InsertItemTemplate The contents of this template display when a new data item is inserted
6) ItemTemplate The contents of this template display for every row rendered by the GridView.

 The RowType property verifies that the row is DataRow (not a header row or some other type of row). The DataItem property retrieves the database record associated with the row. The DataBinder.Eval() method retrieves the value of the Salary.

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

<!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">
    <style type="text/css">
        .grid
        {
            font: 16px Arial, Sans-Serif;
        }
        .grid td, .grid th
        {
            padding: 10px;
        }
        .header
        {
            text-align: left;
            color: white;
            background-color: blue;
        }
        .row td
        {
            border-bottom: solid 1px blue;
        }
        .alternating
        {
            background-color: #eeeeee;
        }
        .alternating td
        {
            border-bottom: solid 1px blue;
        }
    </style>
    <title>Show TemplateField</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>
            Employee Book</h1>
        <asp:GridView ID="grid" runat="server" AutoGenerateColumns="false" CellPadding="4" DataKeyNames="empno"
            AutoGenerateEditButton="true" OnRowEditing="grid_RowEditing" OnRowCancelingEdit="grid_RowCancelingEdit"
            OnRowUpdating="grid_RowUpdating" OnRowDataBound="grid_RowDataBound" ForeColor="#333333">
            <Columns>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <%# Eval("ename")%>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtName" Text='<%# Bind("ename") %>' runat="server" />
                        <asp:RequiredFieldValidator ID="valName" ControlToValidate="txtName" Text="(required)"
                            runat="server" />
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Department">
                    <ItemTemplate>
                        <%# Eval("dname")%>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:DropDownList ID="ddlDepartment"   DataTextField="dname"
                            DataValueField="deptno"   runat="server" />
                    </EditItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <EditRowStyle BackColor="#999999" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        </asp:GridView>
        <br />
        <asp:Label ID="lblSelectRow" runat="server" />
    </div>
    </form>
</body>
</html>

  Code: GridView16_TemplateFields.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.Data.OracleClient;
using System.Data;
using System.Configuration;

namespace LearnAsp.Net.ControlDemo.GridView
{
    public partial class GridView16_TemplateFields : System.Web.UI.Page
    {
        static string strConn = ConfigurationManager.ConnectionStrings["LearnAsp"].ToString();
        private OracleConnection objConn = new OracleConnection(strConn);
        DataTable dtDept = new DataTable();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                String queryDept = "select dname,deptno from dept";
                OracleCommand objCmd = new OracleCommand(queryDept, objConn);
                DataTable dt = new DataTable();
                objConn.Open();
                OracleDataAdapter oda = new OracleDataAdapter(objCmd);
                oda.Fill(dtDept);
                objConn.Close();

                DataRow dr = dtDept.NewRow();
                dr[0] = "-- Select Option --";
                dr[1] = "0";
                dtDept.Rows.InsertAt(dr, 0);
                ViewState["dtDept"] = dtDept;
                GridBind();
            }
        }

        protected void GridBind()
        {
            String query = " SELECT	empno, ename, d.deptno, d.dname FROM emp e INNER JOIN dept d ON e.deptno = d.deptno ";
            OracleCommand objCmd = new OracleCommand(query, objConn);
            DataTable dt = new DataTable();
            objConn.Open();
            OracleDataAdapter oda = new OracleDataAdapter(objCmd);
            oda.Fill(dt);
            objConn.Close();

            if (dt.Rows.Count > 0)
            {
                grid.DataSource = dt;
                grid.DataBind();
            }
            else
            {
                dt.Rows.Add(dt.NewRow());
                grid.DataSource = dt;
                grid.DataBind();
                int columncount = grid.Rows[0].Cells.Count;
                grid.Rows[0].Cells.Clear();
                grid.Rows[0].Cells.Add(new TableCell());
                grid.Rows[0].Cells[0].ColumnSpan = columncount;
                grid.Rows[0].Cells[0].Text = "No Records Found";
            }
        }

       
        protected void grid_RowEditing(object sender, GridViewEditEventArgs e)
        {
            grid.EditIndex = e.NewEditIndex;
            GridBind();
        }
        protected void grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            int userid = Convert.ToInt32(grid.DataKeys[e.RowIndex].Value.ToString());
            string deptID = (grid.Rows[e.RowIndex].FindControl("ddlDepartment") as DropDownList).SelectedItem.Value;
            String EmpName = (grid.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text;

            grid.EditIndex = -1;
            objConn.Open();
            OracleCommand cmd = new OracleCommand("update emp set ename='" + EmpName + "',deptno=" + deptID + " where empno='" + userid + "'", objConn);
            cmd.ExecuteNonQuery();
            objConn.Close();
            GridBind();
        }

        protected void grid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grid.EditIndex = -1;
            GridBind();
        }
        //-------------------------------------------------------------------------------
        protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow && grid.EditIndex == e.Row.RowIndex)
            {
                DropDownList ddl = (DropDownList)e.Row.FindControl("ddlDepartment");
                ddl.DataValueField = "deptno".ToString();
                ddl.DataTextField = "dname".ToString();
                ddl.DataSource = (DataTable)ViewState["dtDept"];
                ddl.DataBind();
                string SetDept = DataBinder.Eval(e.Row.DataItem, "dname").ToString();
                ddl.ClearSelection();
                ddl.Items.FindByText(SetDept).Selected = true;
            }
        }
    }
}

  Output:
logoblog

Thanks for reading Asp.Net GridView TemplateFields 

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.