-->

Saturday, May 31, 2014

Dynamically add rows and columns in data table, also bind Gridview with data table

First create instance of DataTable class, which is inside in System.Data namespace. After that you make columns and rows inside the DataTable. First create columns with their data type also insert rows data in it.

Source Code

<div>
        <asp:GridView ID="GridView1" runat="server">
        <HeaderStyle BackColor ="Green" ForeColor ="Orange" />
        <RowStyle BackColor ="Black" ForeColor ="White" />

        </asp:GridView><br />

        <asp:Button ID="B1" runat="server" Text="Bind GridView" onclick="B1_Click" />
    
    </div>

Business Logic Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class Default4 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }


    protected void B1_Click(object sender, EventArgs e)
    {
  
DataTable datatable = new DataTable();
datatable.Columns.Add("serial Number", typeof(Int32));
datatable.Columns.Add("Name", typeof(string));
datatable.Columns.Add("Address", typeof(string));
datatable.Rows.Add(1, "Jacob", "USA");
datatable.Rows.Add(2, "Lefore", "USA");
datatable.Rows.Add(3, "Bill", "UK");
datatable.Rows.Add(4, "Smith", "UK");
GridView1 .DataSource =datatable;
            GridView1.DataBind ();

    }
}

Code Generate the following Output

Dynamically add rows and columns in data table, also bind Gridview with data table

Friday, May 30, 2014

How to call event in page load method and example of EventHandler class

If you want to add event at run time like click event in page load method. For this types of problem you can use EventHandler class. Create a object of this class also pass new method as a parameter.

Source Code

<div>
    
        <asp:Button ID="B1" runat="server" CommandName="Add" Text="Button" />
    
    </div>

    Business Code


    public partial class Default4 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        B1.Click += new System.EventHandler(this.calculate);
    }
    protected void calculate(object sender, System.EventArgs e)
    {
        switch (((Button)sender).CommandName)
        {
            case "Add": Response.Write("hello");
                break;
        }
    }

}
Code Generate the following output
How to call event in page load method and example of EventHandler class

How to Use Filtered TextBox Extender of AJAX in ASP.NET

FilteredTextBoxExtender enables you to apply filtering to a text box control that prevents certain characters from being inserted in the text box. For example, you can limit a text box to either enter only characters, or digit, or dates. This extender is different from ASP.NET validation controls as it prevents the users from entering invalid characters.

Lets take an simple example

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<%@ 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">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
    Enter Number only:
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" />
        <asp:FilteredTextBoxExtender ID="FilteredTextBoxExtender1" runat="server" TargetControlID ="TextBox1" FilterType="Numbers">
        </asp:FilteredTextBoxExtender>
    </div>
    </form>
</body>
</html>

Code Generate the following Output

How to Use Filtered TextBox Extender of AJAX in ASP.NET

For Lower case Letter Only Set 
FilterType="LowercaseLetters"
For Upper Case Letter only
FilterType="UppercaseLetters"
For Upper and Number
FilterType="UppercaseLetters,Numbers"

Thursday, May 29, 2014

Nested Gridview Example in ASP.NET

A gridview with some items and another gridview structure

<form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server">
        <Columns>
        <asp:TemplateField>
        
        <ItemTemplate>
            <asp:TextBox ID="TextBox1" runat="server" Text ='<%# Eval("database field") %>' />
        
        </ItemTemplate>
         <ItemTemplate>
             <asp:GridView ID="GridView2" runat="server">
             <Columns>
             <asp:TemplateField>
                 
        <ItemTemplate>
            <asp:DropDownList ID="DropDownList1" runat="server">
            </asp:DropDownList>
        
        </ItemTemplate>
             
             </asp:TemplateField>
             
             </Columns>
             </asp:GridView>
        
        </ItemTemplate>
        
        
        </asp:TemplateField>
        
        </Columns>
        </asp:GridView>
    </div>
    </form>

Multiple Events call same event Handler in ASP.NET

In ASP.NET,  you can connect multiple Events with same event handler. If you thing about it, this types of code reduce space complexity as well as time complexity. If you use events with separate events handler then take more time. Like

<div>
    Both Event and methods name are same, both call to same handler.<br />
&nbsp;<asp:Button ID="Button1" runat="server" Text="First Button" 
            onclick="Button1_Click" /><br />
         <asp:Button ID="Button2" runat="server" Text="Second Button" onclick="Button1_Click" /><br />
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    </div>
In my previous article, we have already discussed about it, which is how to determine which web server control is raised.

Business Logic Code

 protected void Button1_Click(object sender, EventArgs e)
    {
        Button button = (Button)sender;
        Label1.Text = button.Text;
    }

Code generate the following output

Multiple Events call same event Handler in ASP.NET

Multiple Events call same event Handler in ASP.NET

Tuesday, May 27, 2014

How to Render HTML Controls in View: Asp.Net MVC

Asp.Net MVC provides a way to write simple programming syntaxes and HTML Helpers convert them in to HTML at runtime to be simply open the pages at client end. These provides generates html and return result as a string.

Like other web form controls in Asp.Net, HTML helpers are used to modify HTML, but HTML Helpers does not have an event model/ view state as web form controls have. Programmer can use these helpers by using built in HTML property of the view that are in System.Web.Mvc.Html namespace. We can create our own Html helpers or use built-in provided in the specified namespace.

HTML helpers have methods for creating forms, rendering partial views, performing input validation etc. Here are some mostly used html helpers:

HTML Links

These type of links are used to render an html link on the page, but in MVC they create a link to redirect on a particular action of the controller.
        @Html.ActionLink(“Text to Display”, “Action-name”)

The first parameter is used to specify the text to be displayed for user and second parameter is used to specify the action-name to which user will redirect after click.

HTML BeginForm

To place a form element on MVC, following syntax is used that will create an HTML form with some parameter values listed below.

@using (Html.BeginForm())
{
//Other Html Helpers to complete the form
}

Parameters used 
  • ActionName: specify the name of action on which user will redirect
  • ControllerName: name of controller in which action has written
  • Route values: the values send as a parameter to action
  • FormMethod: Type of form whether HttpPost or HttpGet
  • Html attributes: used at run time like making readonly, applying css classes and more.

    ------------------------
Here are some standard html helpers used mostly when programming:

Understanding Attributes in Asp.Net MVC

Earlier article was about to handle browser request from the user and then invokes related controller and actions written for that particular URL. What is to be done after these requests can also be specified by the programmer in Asp.Net MVC, as this article will discuss.

Asp.Net MVC provides a way to use some extra features for actions and controller, these features are called Attributes and Filters. We have discusses about Required attribute in creating MVC View Model using required field validations.

The first and most attribute, MVC use by default is [Authorize] which specifies which action is to be executed by authenticated users only or it may be used for whole controller. The syntax for this authorize attribute is:

[Authorize]
Public ActionResult Profile()
{
return View();
}

Now whenever an un-authorized user will try to get access of this profile action, it will redirect the request to login page or the page specified.

Attributes can also take parameters specified in their declaration, they may be positional or named. Positional parameter corresponds to attribute’s public constructor like the one specified below. It will change the name of this action profile to Details, as specified as the parameter.

[ActionName(“Details”)]
Public ActionResult Profile()
{ return View(); }

Named parameter correspond to public property or field of the respective attribute. For example authorize attribute have some named parameters like order, roles and users as written in following code:

[Authorize(Roles="Role1, Role2", Users="User1, User2")]
Public ActionResult Profile()
{ return View(); }

By specifying these named parameters, this profile action will only be accessed by the users having role "Role1" and "Role2". If we talk about the users, this action will only be accessed by only the person having username "User1" and "User2".
Attribute is a class which inherits from the abstract class System.Attribure. 
So we have to inherit from the same System.Attribute class to create our own attribute. Each attribute class (created by us) will must ends with the word "Attribute". E.g.
  • AuthorizeAttribute
  • RequiredAttribute
  • ActionNameAttribute
  • CustomizedAttribute
  • ValueCheckAttribute
© Copyright 2013 Computer Programming | All Right Reserved