Monday, July 7, 2014

How to create user control in ASP.NET using C#


DateControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="DateControl.ascx.cs" Inherits="MyControl" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>&nbsp;
<asp:Image ID="imgCalenderIcon" runat="server" ImageUrl="~/Images/calender3.jpg" />
<asp:CalendarExtender ID="TextBox1_CalenderExtender" runat="server"
                      PopupButtonID="imgCalenderIcon"
                      TargetControlID="txtDate"
                      Format="dd/MM/yyyy">                    
</asp:CalendarExtender>

Include User Control to web form: 
          After creating User Control we have to include that to our web form. So here we have to crate @Register directive that includes following attributes,
·         TagPrefix attribute, which associates a prefix with the user control. This prefix will be included in opening tag of the user control element.
·         TagName attribute, which associates a name with the user control. This name will be included in the opening tag of the user control element.
·         Src attribute, which defines the virtual path to the user control file that you are including.

Sample code:
<%@ Register Src="~/DateControl.ascx" TagName="Date" TagPrefix="UC" %> 

          Here we have to create a web form which is include User Control we have created, 
Designer source code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Src="~/DateControl.ascx" TagName="Date" TagPrefix="UC" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>
<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>  
    <UC:Date runat="server" ID="ucDate"/><br />  
     <asp:Button ID="btnSubmit" runat ="server" Text="Submit" OnClick="btnSubmit_Click"/>
    <asp:Label ID="lblDate" runat="server" ></asp:Label>
    </div>
    </form>
</body>
</html>

Code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; 
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    { 
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        lblDate.Text = ucDate.date;
    }  

}

Grid DropDowns Dynamically Add

Create table script:
CREATE TABLE [dbo].[EmployeeDetails](
          [empid] [varchar](50) NULL,
          [name] [varchar](100) NULL,
          [designation] [varchar](100) NULL,
          [city] [varchar](50) NULL,
          [country] [varchar](50) NULL
) ON [PRIMARY]


CREATE TABLE [dbo].[Designation](
          [id] [int] NULL,
          [designation] [varchar](50) NULL
) ON [PRIMARY]


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="gvEmployeeDetails" runat="server" Width="100%" AutoGenerateColumns="false"
            ShowFooter="true" OnRowCommand="gvEmployeeDetails_RowCommand" OnRowDataBound="gvEmployeeDetails_OnRowDataBound">
            <Columns>
                <asp:TemplateField HeaderText="Employee ID">
                    <ItemTemplate>
                        <asp:Label ID="lblEmpID" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "empid") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtAddEmpID" runat="server"></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:Label ID="lblName" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "name") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtAddName" runat="server"></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Designation">
                    <ItemTemplate>
                        <asp:Label ID="lblDesignation" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "designation") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:DropDownList ID="ddlDesignation" runat="server">
                        </asp:DropDownList>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="City">
                    <ItemTemplate>
                        <asp:Label ID="lblCity" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "city") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtAddCity" runat="server"></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Country">
                    <ItemTemplate>
                        <asp:Label ID="lblCountry" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "country") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtAddCountry" runat="server"></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Action">
                    <FooterTemplate>
                        <asp:LinkButton ID="lbtnAdd" runat="server" CommandName="ADD" Text="Add" Width="100px"></asp:LinkButton>
                    </FooterTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html> 


----------------------------
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
{
   SqlConnection conn = new SqlConnection("Data Source=SPIDER;Initial Catalog=Demo;Integrated Security=True");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindData();
        }
    }
     protected void BindData()
    {
        DataSet ds = new DataSet();    
        conn.Open();
        string cmdstr = "Select * from EmployeeDetails";
        SqlCommand cmd = new SqlCommand(cmdstr, conn);
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        adp.Fill(ds);
        cmd.ExecuteNonQuery();
        conn.Close();
        gvEmployeeDetails.DataSource = ds;
        gvEmployeeDetails.DataBind();       
    }

    protected void gvEmployeeDetails_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("ADD"))
        {
            TextBox txtAddEmpID = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddEmpID");
            TextBox txtAddName = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddName");
            DropDownList ddlDesignation = (DropDownList)gvEmployeeDetails.FooterRow.FindControl("ddlDesignation");
            TextBox txtAddCity = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddCity");
            TextBox txtAddCountry = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddCountry");
          
            conn.Open();
            string cmdstr = "insert into EmployeeDetails(empid,name,designation,city,country) values(@empid,@name,@designation,@city,@country)";
            SqlCommand cmd = new SqlCommand(cmdstr, conn);
            cmd.Parameters.AddWithValue("@empid", txtAddEmpID.Text);
            cmd.Parameters.AddWithValue("@name", txtAddName.Text);
            cmd.Parameters.AddWithValue("@designation", ddlDesignation.SelectedItem.ToString());
            cmd.Parameters.AddWithValue("@city", txtAddCity.Text);
            cmd.Parameters.AddWithValue("@country", txtAddCountry.Text);
            cmd.ExecuteNonQuery();
            conn.Close();
            BindData();
        }     
    }   
    protected void gvEmployeeDetails_OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            DropDownList ddlDesignation = (DropDownList)e.Row.FindControl("ddlDesignation");
            DataSet ds = new DataSet();
            conn.Open();
            string cmdstr = "Select * from Designation";
            SqlCommand cmd = new SqlCommand(cmdstr, conn);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            adp.Fill(ds);           
            ddlDesignation.DataSource = ds.Tables[0];
            ddlDesignation.DataTextField = "designation";
            ddlDesignation.DataValueField = "id";
            ddlDesignation.DataBind();
            ddlDesignation.Items.Insert(0, new ListItem("--Select--""0"));
            conn.Close();
        } 
    }
}