insert and display data into excel using asp.net

July 23, 2009

Create excel file as Data.xls and change the name of sheet1 to users

in users sheet type ID,Name,Address,Phoneno in first row to inserting data

and for display the data in drag gridview control.

excel

file name: Data.xls

sheet name: users

Step1: In Default.aspx page take four textbox’s(ID,Name,Address,Phoneno) and one submit button

change Textbox ID in Properties

ID textbox =txtID

Name textbox =txtName

Address textbox=txtAddres

Phoneno textbox=txtPhoneno

step2: Connectionstring write below code

“ConnectionString” for for Office 97-2003
string  connectionString = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\\lokeshoracle\\data.xls;Extended Properties=Excel 8.0;”;

“ConnectionString” for for Office 2007

string  connectionString = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\\excel\\data.xls;Extended Properties=\”Excel 8.0;HDR=YES;\“”;

step3: Displaying excel data in gridview

In Page_load event

Dont forget to use below namespaces

using System.Data;
using System.Data.OleDb;
using System.IO;

protected void Page_Load(object sender, EventArgs e)
{
string  connectionString = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\\lokeshoracle\\data.xls;Extended Properties=Excel 8.0;”;
OleDbConnection objConn = new OleDbConnection(connectionString);

string query = “select * from [users$]“;
OleDbCommand objCmd = new OleDbCommand(query,objConn);

DataSet objDs = new DataSet();
OleDbDataAdapter objDa = new OleDbDataAdapter(objCmd);

objConn.Open();
objDa.Fill(objDs);
objCmd.ExecuteNonQuery();
GridView1.DataSource = objDs;
GridView1.DataBind();
objConn.Close();
}

step4: Inserting the data into excel sheet

protected void btnSubmitExcelData_Click(object sender, EventArgs e)
{
OleDbConnection objConn = new OleDbConnection(connectionString);
//string query = “insert into [users$] values(1,’bbb’,'bbb’,'2345′)”;
string query = “insert into [users$](ID,Name,Address,Phoneno) values(“+txtID.Text+”,’”+txtName.Text+”‘,’”+txtAddress.Text+”‘,’”+txtPhoneno.Text+”‘)”;
OleDbCommand objCmd = new OleDbCommand(query, objConn);

objConn.Open();
objCmd.ExecuteNonQuery();
objConn.Close();
}

Happy coding


asp.net convert string to date, date to string, string to Int,string to Double,string to Decimal,object to int,object tostring,string to byte array

July 16, 2009

www.codeforasp.net

asp.net convert string to date

string strDate = DateTime.Today.ToString();
DateTime c = DateTime.Parse(strDate);

For TextBox Control: If TextBox contain Calender Date value for date comparisions use below code

DateTime a = DateTime.Parse(TextBox1.Text);

asp.net convert string to integer

string a = “1234″;

int b = Convert.ToInt16(a);
int c = 2;

int d = b + c;

SO string a value is converted to integer and stored in b. for testing i declare int c=2 and i add b and c values
then the result d is integer.

asp.net convert datetime to string

string strDate = DateTime.Today.ToString();

DateTime date = DateTime.Today;
string a = date.ToString(“dd/MM/yyyy”); //result look like 01-12-08
string b = date.ToString(“dd MMM, yyyy”); //result look like 01 Dec, 2008
string c = date.ToString(“dd/MM/yyyy”).Replace(“-”,”/”); // result look like 01/12/2008
string month = date.ToString(“MM”); // result look like month is 12
string alphaMonth = date.ToString(“MMM”); //result look like month is Dec
string fullMonth = date.ToString(“MMMM”); //Result full month name is like December
string day = date.ToString(“dd”); //result look like day is 01
string weekdayName = date.ToString(“ddd”);  //Result look like Wed
string FullweekDayName = date.ToString(“dddd”); //Result look like Wednesday
string shortDate = date.ToShortDateString(); //result is 01-Dec-09
string longDate = date.ToLongDateString(); //result is Wednesday, Dec 01, 2009

asp.net convert object to string

object txtbox;
txtbox = “items”;
string objStr = txtbox.ToString();

asp.net convert object to int

object txtbox;
txtbox = 3;
int objInt =Convert.ToInt16(txtbox);

asp.net convert string to decimal

string a = “1234.34″;
decimal b = decimal.Parse(a);

asp.net convert string to double

string a = “1234.34″;
double b = Convert.ToDouble(a);

Note:

string a = “$52.50″;
double b = Convert.ToDouble(a.Substring(1));

asp.net convert string to byte array

‘ VB.NET to convert a string to a byte array
Public Shared Function StrToByteArray(str As String) As Byte()
Dim encoding As New System.Text.ASCIIEncoding()
Return encoding.GetBytes(str)
End Function ‘StrToByteArray

// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
System.Text.ASCIIEncoding  encoding=new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}

‘ VB.NET to convert a byte array to a string:
Dim dBytes As Byte() = …
Dim str As String
Dim enc As New System.Text.ASCIIEncoding()
str = enc.GetString(dBytes)

// C# to convert a byte array to a string.
byte [] dBytes = …
string str;
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
str = enc.GetString(dBytes);

asp.net convert string to byte array from http://www.chilkatsoft.com/faq/DotNetStrToBytes.html

Thank u


Comparing two dates in Asp.net

July 16, 2009

In this tutorial I compare two dates in asp.net using two textbox controls and two ajax calender controls. You can use

asp.net calender controls instead of ajax calender controls but date formats must be same for both textbox’s date values i.e

(“dd/MM/yyyy” or “MM/dd/yyyy”)

www.codeforasp.net

Date Formats for Ajax CalendarExtender Control

Format=”MMMM d, yyyy”  Result is April 28, 1906

=”dd/MM/yyyy”    Result is 23/11/2008

=”MM/dd/yyyy”    Result is 12/28/2008

=”dd-MMM-yyyy” Result is 23-Mar-2008
Comparing Two dates

If second textbox1(DespatchOrder) date value is less than to first textbox2(OrderTaken) date value then alert box will

display “Check date values”.This TextBox2_TextChanged event is fired when textbox2 is less than textbox1 date value.

Default.aspx Page: When using ajax controls paste script manager in aspx pages top. Check Date Formats in ajax calender
must be in dd/MM/yyyy

Ajax CalendarExtender1 both PopupButtonID=”TextBox1″    and  TargetControlID=”TextBox1″

Ajax CalendarExtender2 both PopupButtonID=”TextBox2″    and  TargetControlID=”TextBox2″

When you click Textbox1 or Textbox2 Calender control will popup you can choose the dates from there
comparedates

<table style=”border: 1px solid #000000; font-family: Arial, Helvetica, sans-serif; font-size: 9pt; background-color:

#E6E6E6″>
<tr>
<td>OrderTaken</td>
<td>
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>

<cc1:CalendarExtender ID=”CalendarExtender1″ runat=”server” Format=”dd/MM/yyyy”
PopupButtonID=”TextBox1″ TargetControlID=”TextBox1″>
</cc1:CalendarExtender>

</td>
</tr>

<tr>
<td>
DespatchOrder</td>
<td><asp:TextBox ID=”TextBox2″ runat=”server” AutoPostBack=”True”
ontextchanged=”TextBox2_TextChanged”></asp:TextBox>

<cc1:CalendarExtender ID=”CalendarExtender2″ runat=”server” Format=”dd/MM/yyyy”
PopupButtonID=”TextBox2″ TargetControlID=”TextBox2″ >
</cc1:CalendarExtender>

</td>
</tr>

</table>

Default.aspx.cs code: Double click in TextBox2

protected void TextBox2_TextChanged(object sender, EventArgs e)
{
DateTime a = DateTime.Parse(TextBox1.Text);
DateTime b = DateTime.Parse(TextBox2.Text);

if (a > b)
{
Response.Write(“<script>alert(‘Check date ranges to OrderTaken and OrderDespatch’);</script>”);
TextBox2.Text=”";
}
}

***Now Run the project Enter Textbox1 value as 09-02-2008

TextBox2 value as 02-02-2008

then textbox changed event fires and popup alert message “check date ranges to orderTaken and orderDespatch”

Note: You can write in this format also javascript alert message

Response.Write(“<script language=’javascript’>”);
Response.Write(“alert(‘Please Check date ranges to OrderTaken and OrderDespatch.’);”);
Response.Write(“return false;”);
Response.Write(“<” + “/script>”);

Note:

dd_MMM_yyyyYou can compare date formats like above figure but change the ajax calender control formats i.e Format=”dd-MMM-yyyy”

<cc1:CalendarExtender ID=”CalendarExtender1″ runat=”server” Format=”dd-MMM-yyyy”
PopupButtonID=”TextBox1″ TargetControlID=”TextBox1″>
</cc1:CalendarExtender>

Similarly for calenderExtender2 Format=”dd-MMM-yyyy”

Happy coding


using Oracle Provider msdaora.1 and asp.net to insert data

July 13, 2009

In Oracle
I am going to Create a table in Oracle using database name is dbName

Database name is dbName

Create a table name tblSales with three fields

create table TBLSALES
(
SALESCODE NUMBER not null,
ITEMS     CHAR(32) not null,
SALESDATE DATE not null
)

In Visual Studio

I am going to explain the steps to insert the data into oracle using asp.net application.

Step1:  Open VS2005 or 2008 -> New -> website -> choose Asp.net Web     site -> Ok

Step2:  Open web.config file to write connection string.

<appSettings>
<add key=”ConnectionString” value=”Provider=msdaora.1;Data Source=dbName;User ID=sa;Password=aaa;Persist Security Info=True;” />
</appSettings>

step3:  In Default.aspx page, Drag three textbox,Button and calender control by clicking calender control date, the date will be displayed in txtDate(its id name of TextBox3)

salesform

give textbox1 ID is txtSalescode
textBox2 ID is txtItems
textBox3 Id is txtDate
Button ID is btnSubmitSales
Step4: In Default.aspx.cs write below code.

add namespace using System.Data.OleDb;

Sample Code in Default.aspx.cs

using System.Data.OleDB;

protected void Page_Load(object sender, EventArgs e)
{

}

protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
txtDate.Text = Calendar1.SelectedDate.ToShortDateString();
}

protected void btnSubmitSales_Click(object sender, EventArgs e)
{

OleDbConnection objConn = new OleDbConnection(ConfigurationManager.AppSettings["ConnectionString"]);

string query = “insert into tblSales(Salescode,Items,SalesDate) values(?,?,?)”;

OleDbCommand objCmd = new OleDbCommand(query, objConn);

objCmd.CommandType = CommandType.Text;

objCmd.Parameters.Add(“@SalesCode”, OleDbType.BigInt).Value = long.Parse(txtSalescode.Text);

objCmd.Parameters.Add(“@Items”, OleDbType.VarChar).Value = txtItems.Text;

objCmd.Parameters.Add(“@SalesDate”, OleDbType.Date).Value = txtDate.Text;

objConn.Open();

objCmd.ExecuteNonQuery();

objConn.Close();

}

Step5: Run the application


asp.net and oracle Using OledB Connection

July 13, 2009

Step1: Open VS2005 or 2008 -> New -> website -> choose Asp.net Web site -> Ok

Step2: Open web.config file to write connection string.

<appSettings>
<add key=”ConnectionString” value=”Provider=msdaora.1;Data Source=dbName;User ID=sa;Password=aaa;Persist Security Info=True;” />
</appSettings>

step3: In Default.aspx page, Drag Gridview control to display the data.

Step4: In Default.aspx.cs write below code.

add namespace using System.Data.OleDb;


Sample code look like

protected void Page_Load(object sender, EventArgs e)
{

OleDbConnection objConn = new OleDbConnection(ConfigurationManager.AppSettings["ConnectionString"]);

string query=”select *from tblEmpRegister”;

OleDbCommand objCmd = new OleDbCommand(query, objConn);

objCmd.CommandType = CommandType.Text;

DataSet objDs = new DataSet();

OleDbDataAdapter objDa = new OleDbDataAdapter(objCmd);

objConn.Open();

objDa.Fill(objDs);

objCmd.ExecuteNonQuery();

GridView1.DataSource = objDs;

GridView1.DataBind();

objConn.Close();

}


using stored procedures in asp.net

July 9, 2009

Using Stored Procedure with ADO.Net

A stored procedure is a set of one or more SQL statements (insert, update, select, delete … with combinations) that are stored together in database. It improves performance of the database.

Definition from:

http://www.c-sharpcorner.com/UploadFile/raj1979/SQLViewsStoredProcedures10032008152021PM/SQLViewsStoredProcedures.aspx

Stored Procedures (Database Engine)

When you create an application with Microsoft SQL Server 2005, the Transact-SQL programming language is the primary programming interface between your applications and the Microsoft SQL Server database. When you use Transact-SQL programs, two methods are available for storing and executing the programs.

  • You can store the programs locally and create applications that send the commands to SQL Server and process the results.
  • You can store the programs as stored procedures in SQL Server and create applications that execute the stored procedures and process the results.

Content From http://msdn.microsoft.com/en-us/library/ms190782(SQL.90).aspx

Creating Stored Procedure in Sql Server 2005

Open your Sqlserver 2005 -> Expand Databases -> Choose Your Database (Ex: Employees) ->choose Programmability and Expand -> choose Stored Procedure ->

Right Click on Stored Procedure ->New Stored Procedure.

See below figure

sp

Create Procedure ProcTblRegistrationGetRegisterData

as

Begin

select *from tblEmpRegister order by EmpID desc

End


Calling Stored Procedure into Asp.net Application

In Web.config, Write ConnectionString in AppSetting

<appSettings>

<add key=”ConnectionString” value=”Data Source=yourServerNameOrlocalhostname;Initial Catalog=Contact;User ID=sa;Password=xxx;”/>

</appSettings>

1) Add Gridview Control in Default.aspx page

2) Write below code in Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)

{

SqlConnection objConn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);

SqlCommand objCmd = new SqlCommand(“ProcTblRegistrationGetRegisterData”, objConn);

objCmd.CommandType = CommandType.StoredProcedure;

DataSet objDs = new DataSet();

SqlDataAdapter objDa = new SqlDataAdapter(objCmd);

objConn.Open();

objDa.Fill(objDs);

objCmd.ExecuteNonQuery();

GridView1.DataSource = objDs;

GridView1.DataBind();

objConn.Close();

}


Storing and Retrieving images in Gridview using Sqlserver 2005 Image Datatype

July 3, 2009

Original article from

http://www.codeforasp.net/storing-and-retrieving-images-in-gridview-using-sqlserver-2005-image-datatype.html

1) First Create Database  ImageDB

2) Create table ImageGallary

CREATE TABLE ImageGallery(
Img_Id int  IDENTITY(1,1) NOT NULL,
Image_Content image NOT NULL,
Image_Type varchar(50)  NOT NULL,
Image_Size bigint NOT NULL
)

3) Create New Asp.net Application

Programs -> Microsoft Visual Studio 2005 or 2008 -> File –>website ->

4) open your web.config file in your project write your connectionstring

<appSettings>
<add key=”ConnectionString” value=”Data Source=localhost name/server name;Initial Catalog=ImageDB;User ID=sa;Password=xxx”/>
</appSettings>

Ex: localhost name= Raju and Server Name=192.168.2.34

5) Storing Image In Sqlserver Database

In Default.aspx

Place FileUploader control and Button ID

Button ID is btnSubmitCustImage

FileUploader ID is FileUpload1

6) In  Button Click event (code will appear in Default.aspx.cs) write this code

First Add Namespaces

using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.IO;

now write code button click i.e.

protected void btnSubmitCustImage_Click(object sender, EventArgs e)
{

SqlConnection objConn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != “”)
{

byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile Image = FileUpload1.PostedFile;
Image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);

SqlCommand storeimage = new SqlCommand(“INSERT INTO ImageGallery(Image_Content, Image_Type, Image_Size) values (@image, @imagetype, @imagesize)”,objConn);
storeimage.Parameters.Add(“@image”, SqlDbType.Image, myimage.Length).Value = myimage;
storeimage.Parameters.Add(“@imagetype”, SqlDbType.VarChar, 100).Value = FileUpload1.PostedFile.ContentType;
storeimage.Parameters.Add(“@imagesize”, SqlDbType.BigInt, 99999).Value = FileUpload1.PostedFile.ContentLength;

objConn.Open();
storeimage.ExecuteNonQuery();
objConn.Close();
}
}

** Run Your website Add image using Fileuploader control and click submit button theck check your database ImageDB open your table Image Gallary you can see values of Img_ID,Image_content,Image_type,Image_size

6) Retrieving Images to Gridview with Handler.aspx Using sqlserver 2005

What is Handler?

An ASP.NET HTTP Handler is a simple class that allows you to process a request and return a response to the browser. Simply we can say that a Handler is responsible for fulfilling requests from the browser. It can handle only one request at a time, which in turn gives high performance. A handler class implements the IHttpHandler interface. //from aspdotnetcodes.com

a) Create Handler.aspx

Goto website -> Add new item -> choose Generic Handler (i.e Handler.ashx)

The Handler.ashx file to perform image retrieval. This Handler.ashx page will contain only one method called ProcessRequest. This method will return binary data to the incoming request. In this method, we do normal data retrieval process and return only the Image_Content field as bytes of array.

In Handler.aspx the code looks like this

public void ProcessRequest (HttpContext context)

{

context.Response.ContentType = “text/plain”;  //Remove
context.Response.Write(“Hello World”); //Remove

}

Remove above two lines code and Add below code in ProcessRequest

<%@ WebHandler Language=”C#” %>

using System;
using System.Web;
using System.Data.SqlClient;  //Add this namespace
using System.Configuration; // Add this namespace
using System.Data; //Add this namespace
using System.IO; //Add this namespace

public class Handler : IHttpHandler {

public void ProcessRequest (HttpContext context)

{
SqlConnection myConnection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
myConnection.Open();
string sql = “Select Image_Content, Image_Type from ImageGallery where Img_Id=@ImageId”;
SqlCommand cmd = new SqlCommand(sql, myConnection);
cmd.Parameters.Add(“@ImageId”, SqlDbType.Int).Value = context.Request.QueryString["id"];
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.ContentType = dr["Image_Type"].ToString();
context.Response.BinaryWrite((byte[])dr["Image_Content"]);
dr.Close();
myConnection.Close();
}

public bool IsReusable {
get {
return false;
}
}

}

b) now  Place Gridview in Default.aspx page below of Fileuploader control and button already we placed this two controls for storing images in Database below of this controls Add gridview control or you can add some other .aspx page.

c)  To Retrieve images from sqlserver 2005 using query

public DataTable FetchAllImagesInfo()
{
string sql = “Select * from ImageGallery”;
SqlDataAdapter da = new SqlDataAdapter(sql, objConn);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}

d) To display Images In gridview template field

Note: To add template Field to Gridview

gridview Template field Adding

gridview Template field Adding

First click -> Edit columns.. -> choose TemplateField –> Add –> ok

once see the above figure now click Edit Template (Display Mode must be in ItemTemplate)  –> in that add Image control from toolbox –>click  End Template

First bind the image in gridview like below code

<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False”>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID=”Image1″ runat=”server” ImageUrl=’<%# “Handler.ashx?id=” + Eval(“Img_Id”)  %>’ />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

To display images in Default.aspx Page Gridview write code in Page_Load

protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = FetchAllImagesInfo();
GridView1.DataBind();
}

Now Run your website see the result

Happy coding

Original Post from www.aspdotnetcodes.com

For learning more asp.net topics please visit the site below

http://www.codeforasp.net

http://www.codegain.com


asp.net class file and web.config using Oracle connectionstring

June 29, 2009

Create table tblCustomerData(CustCode number,CustName varchar2(32));

Oracle ConnectionString

<connectionStrings>
<add name=”ConnectionString” connectionString=”Data Source=dbname;Persist Security Info=True;User ID=xxx;Password=xxx;Unicode=True” providerName=”System.Data.OracleClient”/>
</connectionStrings>

class file creation:- website –> Add new item –> clsCustomer.cs

using System.Data.OracleClient ;  //to add this namespace right click on project (Ex: D:\TestOracle) –> add reference –> choose .Net tab –> choose System.Data.OracleClient –>  –> ok

Calling web.config ConnectionString

OracleConnection objConn = new OracleConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

Get/Sets Properties

private long c_CustCode;

public long nCustCode
{
get { return c_CustCode; }
set { c_CustCode = value; }
}

private string c_CustName;

public string sCustName
{
get { return c_CustName; }
set { c_CustName = value; }
}

public long AddCustomers()
{
string query = “insert into tblCustomerData(CustCode,CustName) values(:pCustCode,:pCustName)”;
OracleCommand objCmd = new OracleCommand(query, objConn);
objCmd.CommandType = CommandType.Text;

objCmd.Parameters.Add(“:pCustCode”, OracleType.Number).Value = nCustCode;

objCmd.Parameters.Add(new OracleParameter(“:pCustName”, OracleType.VarChar, 32, “CustName”)).Value = sCustName;

objConn.Open();
long value = long.Parse(objCmd.ExecuteNonQuery().ToString());
objConn.Close();
return value;

}

Default.aspx: Add two textboxs for Customercode and CustomerName

and one button ,its ID is btnSubmitData

Default.aspx.cs:

clsCustomer objCustomer = new clsCustomer();

protected void btnSTringAdd_Click(object sender, EventArgs e)
{
objCustomer.nCustCode = int.Parse(TextBox2.Text);
objCustomer.sCustName = TextBox1.Text;
objCustomer.AddCustomers();
}


EventHandler in Asp.net with C#

April 15, 2009

Textbox Event:

protected override void OnInit(EventArgs e) {
    TextBox txtName = new TextBox();
    txtName.ID = "txtName";
    txtName.Text = "Enter your name";
    this.form1.Controls.Add(txtName);
 
    base.OnInit(e);
}

Dropdown List Event

DropDownList DropDown1 = new DropDownList();

this.form1.Controls.Add(DropDown1);

Example:

DropDownList ddlStatus = new DropDownList();

ddlStatus.Items.Insert(0, (new ListItem(“Pending”, “1″)));

ddlStatus.Items.Insert(1, (new ListItem(“Aproved”, “2″)));

ddlStatus.Items.Insert(2, (new ListItem(“Deleted”, “3″)));

ddlStatus.ID = “ddlStatus”;

Page.Form.Controls.Add(ddlStatus); //Remember

ddlStatus.SelectedIndexChanged += this.ddlStatus_SelectedIndexChanged1;

ddlStatus.AutoPostBack = true;

#region “ddlStatus_SelectedIndexChanged1″

protected void ddlStatus_SelectedIndexChanged1(object sender, System.EventArgs e)

{

Response.Redirect(“http://wwww.yahoo.com”);

}

#endregion

CheckBox Event :

#region “Page_Load”

protected void Page_Load(object sender, EventArgs e)

{

CheckBox CheckBox1 = new CheckBox();

this.form1.Controls.Add(CheckBox1);

((CheckBox)CheckBox1).CheckedChanged += new System.EventHandler(this.ClickMe);

CheckBox1.AutoPostBack = true; //Remember

}

#endregion

public void ClickMe(object sender, EventArgs e)

{

Response.Write(“Checkbox is checked”);

}

Button Event:

Example: protected void Page_Load(object sender, EventArgs e)

{

Button Button1 = new Button();

Button1.Text = “Submit”;

Panel3.Controls.Add(Button1);

Button1.Click += new System.EventHandler(this.JustAnotherEventHandler);

}

void JustAnotherEventHandler(object sender, System.EventArgs e)

{

Label1.Text = “Clicked”;

//ListBox1.Items.Add(“Event 1 says hello”);

}

Example:

System.Web.UI.HtmlControls.HtmlGenericControl div1= new
HtmlGenericControl( “div” );
div1.ID = “divNewTextBox”;
TextBox txt1 = new TextBox();
div1.Controls.Add( txt1 );

Linkbutton Events:

Example: You add an event delegate to a linkbutton and use the called method to do the work.

In C# (you can do the translation yourself) :

LinkButton lb = new LinkButton();
lb.text = “foo”;
lb.CommandArgument = “foo”;
lb.Click += new EventHandler(LbClick);
c.Controls.Add(lb);

then :

public void LbClick(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
string bar = lb.CommandArgment; //should == foo

}

Example2:

private LinkButton lb = new LinkButton();

protected void Page_Load(object sender, EventArgs e)

{

LinkButton lbTemp = CreateLinkButton(“lnk1″, “my 1st dynam control”);

lbTemp.Click += linkbutton_click;

//pnlHoldsStuff.Controls.Add(lbTemp);

this.Form1.Controls.Add(lb);

}

[System.Runtime.InteropServices.OptionalAttribute, System.Runtime.InteropServices.DefaultParameterValueAttribute("")] // ERROR: Optional parameters aren’t supported in C#

//string vsCssClsass

private LinkButton CreateLinkButton(string vsID, string vsText)

{

lb.ID = vsID;

lb.Text = vsText;

//lb.CssClass = vsCssClsass;

return lb;

}

private void linkbutton_click(object sender, System.EventArgs e)

{

Response.Write(“I got clicked”);

LinkButton lb = CreateLinkButton(“lnk2″, “my 2nd dynam control”);

lb.Click += linkbutton2_click;

//pnlHoldsStuff.Controls.Add(lb);

this.Form1.Controls.Add(lb);

}

private void linkbutton2_click(object sender, System.EventArgs e)

{

Response.Write(“Second Link button clicked”);

}