Wednesday, December 23, 2009

Creating custom Server Control

write this coding in Web Control Library Form

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace my_first_control
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:WebCustomControl1 runat=server>")]
public class WebCustomControl1 : System.Web.UI.WebControls.WebControl,INamingContainer
{
protected TextBox new_textbox = new TextBox();
protected Button button = new Button();

The Below Strings are Displayed Default in a cs file.Am attached the meaning for the terms below....

[Bindable(true)]----specifies for visual designers whether it is meaningful to bind the property to data

[Category("Appearance")]----specifies how to categorize the property in the visual designer's property browser

[DefaultValue("")]----specifies a default value for the property

[Localizable(true)]----specified as true or false, specifies for visual designers whether it is meaningful to localize the property.

public string Text
{
get
{
String s = (String)ViewState["Text"];
return ((s == null) ? String.Empty : s);
}

set
{
ViewState["Text"] = value;
}
}
public override ControlCollection Controls
{
get
{
EnsureChildControls();//EnsureChildControls method checks if CreateChildControls is already called, and call it if not
return base.Controls;
}
}
protected override void CreateChildControls()
{
//base.CreateChildControls();

Controls.Clear();
new_textbox.ToolTip = "User Created Control";
new_textbox.Text = "NEW CREATED TEXT BOX";

button.Click += new EventHandler(button_Click);

Controls.Add(new_textbox);
Controls.Add(new LiteralControl("
"));
Controls.Add(button);
Controls.Add(new LiteralControl("
"));
}
private void button_Click(object sender, EventArgs e)
{
EnsureChildControls();
new_textbox.Text = "TEXT WORKS";
}
public override void RenderControl(HtmlTextWriter writer)
{
base.RenderControl(writer);
}

protected override void OnInit(EventArgs e)
{
string javascript_code_data = @"";
Page.RegisterClientScriptBlock("my script", javascript_code_data);
base.OnInit(e);
}
}
}

Build the Form as Dll.It Stores in Project Foldrename-->Debug-->Bin-->Filename.dll
add the dll reference to ur page.

We have Two type to Register the Control into our Web From
1. Using Register Namesapace="my_frist_Control" Assembly="My_First_Control" TagPrefix="vijay" with in the tag "<%@Register %>"

2. Add this web Config File.If u Register in web Config File.You need not to Register in Each File.You can use the control in Different File.
system.web
pages
controls
add tagPrefix="mycontrol" namespace="my_first_control" assembly="my_first_control"/
/controls
/pages
/system.web

Then Call the tag name in Web form as

mycontrol:WebCustomControl1 ID="my_control" runat="server"

It Will Show your Control on your Web Form.