How To Create Controls Dynamicaly in ASP.NET
ASP.NET is a very powerful and flexible technology, allowing programmers to develop sophisticated web applications within a short period of time. It is so easy to drag and drop controls in a web form and start writing the business logic in the code behind file.
Ofcourse, dragging and dropping controls from the toolbox is the easiest approach.
In this article, I will discuss how you can create ASP.NET controls at runtime using C# syntax.
1. Create a new ASP.NET web application using VS.NET
2. Drag a Drop a Panel control into webform
3. Double click on the webpage this will add a Load Event Handler in the code behind
private void Page_Load(object sender, System.EventArgs e)
{
TextBox _txt = new TextBox();
_txt.ID = “txtId”;
_txt.Text = “This is Dynamicaly genrated Textbox”;
Panel1.Controls.Add(_txt);
}
The above code will create a TextBox dynamicaly and add to the form.Using this
approach you can create any other ASP.NET server controls and add to form.
How To Specify postion for dynamicaly created control
The most common method is to use Table control to position controls and text in Page.
The following code sample will create 5 textboxes and labels. We will create 5 rows and 2 cells in each row dynamically and add our dynamicaly created textbox/label controls to the table so that they will be aligned properly and will appear in the page in proper format.
protected void Page_Load(object sender, EventArgs e)
{
Table tblDynamic = new Table();
for (int i = 0; i < 5; i++)
{
TableRow tr = new TableRow();
// Create column 1
TableCell td1 = new TableCell();
// Create a label control dynamically
Label _label = new Label();
_label.ID = “lbl” + i.ToString();
_label.Text = “Enter Value ” + i.ToString();
// Add control to the table cell
td1.Controls.Add(_label);
// Create column 2
TableCell td2 = new TableCell();
TextBox _text = new TextBox();
_text.ID = “txt_” + i.ToString();
// Add control to the table cell
td2.Controls.Add(_text);
// Add cell to the row
tr.Cells.Add(td1);
tr.Cells.Add(td2);
// Add row to the table.
tblDynamic.Rows.Add(tr);
}
pnl.Controls.Add(tblDynamic);
}
How To Create Javascript Alert from ASP.NET code behind
In Windows Forms it is very easy to pop up a status message by calling MessageBox।Show(“message”). It is that kind of object model we want in ASP.NET for printing out JavaScript alerts. We want Alert.Show(“message”) in ASP.NET.
I’ve written a static class called Alert with one public method called Show। The implementation is as simple as can be. Just put the .cs file in the App_Code folder on your website and you instantly have access to the method from all pages and user controls.
I’ve written a static class called Alert with one public method called Show. The implementation is as simple as can be. Just put the .cs file in the App_Code folder on your website and you instantly have access to the method from all pages and user controls.
using System.Web;
using System.Text;
using System.Web.UI;
///
/// A JavaScript alert
///
public static class Alert
{
///
/// Shows a client-side JavaScript alert in the browser.
///
///
The message to appear in the alert.
public static void Show(string message)
{
// Cleans the message to allow single quotation marks
string cleanMessage = message.Replace(“‘”, “\\’”);
string script = ” “;
// Gets the executing web page
Page page = HttpContext.Current.CurrentHandler as Page;
// Checks if the handler is a Page and that the script isn’t allready on the Page
if (page != null && !page.ClientScript.IsClientScriptBlockRegistered(“alert”))
{
page.ClientScript.RegisterClientScriptBlock(typeof(Alert), “alert”, script);
}
}
}
How To Use
Add a button in you asp.net file and add following code in click event of the button
void btnSave_Click(object sender, EventArgs e)
{
try
{
SaveSomething();
Alert.Show(“You document has been saved”);
}
catch (ReadOnlyException)
{
Alert.Show(“You do not have write permission to this file”);
}
}
How To Upload Files Larger Than 4 MB
By default, the size limit for ASP.NET uploads is set at 4MB. Although this is large enough for most sites, if you’re dealing in particularly hefty uploads, there’s a little-known technique for upping the cap.
Simply open machine.config in the \Microsoft.NET\Framework\ \Config folder and locate the following setting:
<httpRuntime maxRequestLength=4096>
Now, simply alter the maxRequestLength value to a figure of your choice. To allow uploads of up to 8MB, for example, change the value from 4096 to 8192.
Do Postback With Parameters in javascript
Whenever you use a Button or LinkButton it is because you want to be able to do a postback when it is clicked. The same could be the case for CheckBox or DropDownList etc. but then you need to set the AutoPostback property to true. It all works very much the same way from a user’s point of view – click or select and the page performs a postback.
However, in some cases you want to be able to do a postback from a custom JavaScript function that emulates the click of an e.g. LinkButton. That is very simple to do so, but did you know that you also can send custom information via such a postback?
Example
The following LinkButton calls the server-side event handler OnSaveClick.
<asp:LinkButton runat=”Server” ID=”btnSave” Text=”Save” OnClick=”OnSaveClick” />
This is pretty much standard and no tricks have been used so far. Now we need the
JavaScript method that forces the LinkButton to do a postback that calls the
server-side method OnSaveClick.
<script type=”text/javascript”>
function SaveWithParameter(parameter)
{
__doPostBack(‘btnSave ‘, parameter)
}
</script>
Notice that the function takes a parameter that it sends to the __doPostBack
function. All we need to do now is to call the SaveWithParamter function from
JavaScript.
>
SaveWithParameter(“Hello world!”);
Now the page performs a postback and we can now access the “Hello world!” string
that we sent as a parameter from within the OnSaveClick event handler.
protected void OnSaveClick(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"];
}
What we just did was to perform a postback from a custom JavaScript function and
send a parameter to the server-side event handler. It sounds a lot harder than it
is, right?
>
In ASP.NET 2.0 you have to set the EnableEventValidation=”false” attribute in the
page declaration or in web.config to make it work.
How To Print certain areas of Page
Create a style sheet for printing purpose, normally by removing/hiding background
colors, images…. After that include it with media=”print”, so that this style sheet
will be applied while printing.
<LINK media=”print” href=”styles/printStyle.css” type=”text/css”
rel=”stylesheet”>
Retrieve data from a web page
Summary: An example of how we can make a request to a web page and retrieve the resulting HTML![]()
There are a few situations where it would be useful to be able to retrieve the HTML from a web page via code. Fortunately, this is made relatively easy by the HttpWebRequest and httpWebResponse classes.
Firstly, we need to decide which type of form the web page is using. The two different methods are GET and POST and for this article, I’m going to assume you have a basic understanding of these methods and I’ll simply show you an example of how to implement either method rather than go into the differences between them. For both methods we’ll need a simple page to actually display the results so let’s start by making a page with a TextBox on it:
- <%@ Page Language=”VB” AutoEventWireup=”false” CodeFile=”Default1.aspx.vb” Inherits=”Default1″ %>
- <!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>Retrieve data from a web page</title>
- </head>
- <body>
- <form id=”form1″ runat=”server”>
- <div>
- <asp:TextBox ID=”TextBox1″ runat=”server” Rows=”40″ Columns=”100″ TextMode=”MultiLine”></asp:TextBox>
- </div>
- </form>
- </body>
- </html>