ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET 4.5 HOSTING - ASPHostPortal :: How to Create Nested WebGrid in ASP.NET MVC6.

clock November 19, 2014 05:51 by author Mark

How to Create Nested WebGrid with Expand/Collapse in ASP.NET MVC6.

Introduction

In this post, I am explain How to Create Nested WebGrid with Expand/Collapse in ASP.NET MVC6.
Steps :

Step - 1 : Create New Project.

  • Go to File > New > Project > Select asp.net MVC6 web application > Entry Application Name > Click OK > Select Internet Application > Select view engine Razor > OK

Step-2: Add a Database.

  • Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for fetch data.

  • Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > OK.

In this example, I have used two tables as below

Step-4: Add Entity Data Model.

  • Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
  • A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
  • Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a class for create a view model.

  • 1st : Add a folder.
  • Go to Solution Explorer > Right Click on the project > add > new folder.
  • 2nd : Add a class on that folder
  • Go to Solution Explorer > Right Click on that folder > Add > Class... > Enter Class name > Add.

Write the following code in this class

using System.Collections.Generic;
namespace MVCNestedWebgrid.ViewModel
{
    public class OrderVM
    {
        public OrderMaster order { get; set; }
        public List<OrderDetail> orderDetails { get; set; }
    }
}

Step-6: Add a new Controller.

  • Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Step-7: Add new action into your controller for show nested data in a webgrid.

Here I have added "List" Action into "Order" Controller. Please write this following code

public ActionResult List()
{
    List<OrderVM> allOrder = new List<OrderVM>();
 
    // here MyDatabaseEntities is our data context
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        var o = dc.OrderMasters.OrderByDescending(a => a.OrderID);
        foreach (var i in o)
        {
            var od = dc.OrderDetails.Where(a => a.OrderID.Equals(i.OrderID)).ToList();
            allOrder.Add(new OrderVM { order= i, orderDetails = od });
        }
    }
    return View(allOrder);
}

Step-8: Add view for the Action & design.

  • Right Click on Action Method (here right click on form action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Add.

NOTE " Please Rebuild solution before add view

Html Code
@model IEnumerable<MVCNestedWebgrid.ViewModel.OrderVM>

@{
    ViewBag.Title = "Order List";
    WebGrid grid = new WebGrid(source: Model, canSort: false);
}
<div id="main" style="padding:25px; background-color:white;">
    @grid.GetHtml(
    htmlAttributes: new {id="gridT", width="700px" },
    columns:grid.Columns(
            grid.Column("order.OrderID","Order ID"),
            grid.Column(header:"Order Date",format:(item)=> string.Format("{0:dd-MM-yyyy}",item.order.OrderDate)),
            grid.Column("order.CustomerName","Customer Name"),
            grid.Column("order.CustomerAddress","Address"),
            grid.Column(format:(item)=>{
                WebGrid subGrid = new WebGrid(source: item.orderDetails);
                return subGrid.GetHtml(
                    htmlAttributes: new { id="subT" },
                    columns:subGrid.Columns(
                            subGrid.Column("Product","Product"),
                            subGrid.Column("Quantity", "Quantity"),
                            subGrid.Column("Rate", "Rate"),
                            subGrid.Column("Amount", "Amount")
                        )                   
                    );
            })
        )
    )
</div>
Css Code
<style>
th, td {
        padding:5px;
    }
    th
    {
        background-color:rgb(248, 248, 248);       
    }
    #gridT,  #gridT tr {
        border:1px solid #0D857B;
    }
    #subT,#subT tr {
        border:1px solid #f3f3f3;
    }
    #subT {
        margin:0px 0px 0px 10px;
        padding:5px;
        width:95%;
    }
    #subT th {
        font-size:12px;
    }
    .hoverEff {
        cursor:pointer;
    }
    .hoverEff:hover {
        background-color:rgb(248, 242, 242);
    }
    .expand {
        background-image: url(/Images/pm.png);
        background-position-x: -22px;
        background-repeat:no-repeat;
    }
    .collapse  {
        background-image: url(/Images/pm.png);
        background-position-x: -2px;
        background-repeat:no-repeat;
    }
</style>
Write the following Jquery code for make webgrid collapsible
<script>
    $(document).ready(function () {
        var size = $("#main #gridT > thead > tr >th").size(); // get total column
        $("#main #gridT > thead > tr >th").last().remove(); // remove last column
        $("#main #gridT > thead > tr").prepend("<th></th>"); // add one column at first for collapsible column
        $("#main #gridT > tbody > tr").each(function (i, el) {
            $(this).prepend(
                    $("<td></td>")
                    .addClass("expand")
                    .addClass("hoverEff")
                    .attr('title',"click for show/hide")
                );
            //Now get sub table from last column and add this to the next new added row
            var table = $("table", this).parent().html();
            //add new row with this subtable
            $(this).after("<tr><td></td><td style='padding:5px; margin:0px;' colspan='" + (size - 1) + "'>" + table + "</td></tr>");
            $("table", this).parent().remove();
            // ADD CLICK EVENT FOR MAKE COLLAPSIBLE
            $(".hoverEff", this).live("click", function () {
                $(this).parent().closest("tr").next().slideToggle(100);
                $(this).toggleClass("expand collapse");
            });
        });
        //by default make all subgrid in collapse mode
        $("#main #gridT > tbody > tr td.expand").each(function (i, el) {
            $(this).toggleClass("expand collapse");
            $(this).parent().closest("tr").next().slideToggle(100);
        });    
    });
</script>



Free Trial ASP.NET 4.5.1 Hosting with ASPHostPortal.com :: How to Send Bulk Email Using ASP.Net 4.5

clock April 3, 2014 12:14 by author Kenny

In this article I’m going to explain about how to send bulk email using ASP.Net 4.5. Bulk email software is software that is used to send email in large quantities. Bulk mail broadly refers to mail that is mailed and processed in bulk at reduced rates. The term does not denote any particular purpose for the mail; but in general usage is synonymous with "junk mail". This tutorial we will use ASP.NET Web Page for provide the user interface for your Web applications, Grid View for enables you to select, sort, and edit values of a data source in a table where each column represents a field and each row represents a record, HTML Email Templates and Gmail SMTP Mail Server.

Let’s start to try this tutorial, for the first step you must create a new project.
Click "File" -> "New" -> choose "Project..." and then select web "ASP .Net Web Forms Application". Name it as "Bulk Email".
And now let’s see in the Design page “Default.aspx” design the web page as in the following screen:

This is code for Design Source (Default.aspx):
Default.aspx.cs

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="BulkEmail._Default" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
    <section class="featured">
        <div class="content-wrapper">
            <hgroup class="title">              
                <h2>Send Bulk email using asp.net</h2>
            </hgroup>
            <p>To learn more about ASP.NET
            </p>
        </div>
    </section>
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
       <h3>We suggest the following:</h3>
    <asp:Panel ID="Panel1" runat="server" Width="100%" ScrollBars="Horizontal">
    <p>
       <asp:Button ID="btnBind" runat="server" Text="View" OnClick="btnBind_Click" /> <asp:Label
ID="Label1" runat="server" Font-Bold="true" ForeColor="Green" Text="Total
Customers:">   
</asp:Label><asp:Label ID="lbltotalcount" runat="server" ForeColor="Red" Font
Size="Larger"></asp:Label> </p>
        <asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" />
        <asp:GridView ID="grvCustomers" runat="server"></asp:GridView>
    </asp:Panel>
</asp:Content>

In the Web.config file create the connection string as:
Web.config

<connectionStrings>   
<add name="ConnectionString"connectionString="Server=localhost;userid=root;password=;Database=
orthwind"providerName="MySql.Data.MySqlClient"/>      
</connectionStrings>


In the code behind file (Default.aspx.cs) write the code as:

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

//Using namespaces 
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Data;

namespace BulkEmail
{
    public partial class _Default : Page
    {
        #region MySqlConnection Connection
        MySqlConnection conn = new
MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {
            Try
            {
                if (!Page.IsPostBack)
                {

                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }
        #endregion
        #region show message
        /// <summary>
        /// This function is used for show message.
        /// </summary>
        /// <param name="msg"></param>
        void ShowMessage(string msg)
        {
            ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script
language='javascript'>alert('" + msg + "');</script>");
        }       
        #endregion
        #region Bind Data
        /// <summary>
        /// This display the data fetched from the table using MySQLCommand,DataSet and
MySqlDataAdapter
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBind_Click(object sender, EventArgs e)
        {
            Try
            {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand("Select
CustomerID,ContactName,Address,Phone,Email from customers", conn);
                MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adp.Fill(ds);
                grvCustomers.DataSource = ds;
                grvCustomers.DataBind();
                lbltotalcount.Text = grvCustomers.Rows.Count.ToString();
            }
            catch (MySqlException ex)
            {
                ShowMessage(ex.Message);
            }
            Finally
            {
                conn.Close();

            }
            btnBind.Visible = false;
        }
        #endregion
        #region Bulk email,GridView,gmail
        /// <summary>
        /// this code used to Send Bulk email 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSend_Click(object sender, EventArgs e)
        {
            Try
            {
                lbltotalcount.Text = string.Empty;
                foreach (GridViewRow grow in grvCustomers.Rows)
               {
                    string strCustomerID = grow.Cells[0].Text.Trim();
                    string strContactName = grow.Cells[1].Text.Trim();
                    string strAddress = grow.Cells[2].Text.Trim();
                    string strPhone = grow.Cells[3].Text.Trim();
                    string strEmail = grow.Cells[4].Text.Trim();               

                    string filename = Server.MapPath("~/Event.html");
                    string mailbody = System.IO.File.ReadAllText(filename);
                    mailbody = mailbody.Replace("##NAME##", strContactName);
                    string to = strEmail;
                    string from = "[email protected]";
                    MailMessage message = new MailMessage(from, to);
                    message.Subject = "Auto Response Email";
                    message.Body = mailbody;
                    message.BodyEncoding = Encoding.UTF8;
                    message.IsBodyHtml = true;
                    SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                    System.Net.NetworkCredential basicCredential = newSystem.Net.NetworkCredential("[email protected]", "Password");
                    client.EnableSsl = true;
                    client.UseDefaultCredentials = true;
                    client.Credentials = basicCredential;
                    try
                    {
                        client.Send(message);
                        ShowMessage("Email Sending successfully...!" + strContactName + " &nbsp;");                                           
                    }
                    catch (Exception ex)
                    {
                        ShowMessage(ex.Message);
                    }
                } 
            }
            catch (MySqlException ex)
            {
                ShowMessage(ex.Message);
            }
            Finally
            {
                conn.Close();
            }
        }
        #endregion
    }
}


Finally, Bulk Sending an E-Mail Using ASP.NET 4.5 with HTML Email Templates and Gmail SMTP Mail Server.



FREE Trial 7 Days ASP.NET Hosting | No Setup Fees! | 24/7 Support | 99.9% Uptime

clock March 14, 2014 11:33 by author Diego

ASPHostPortal.com, no#1 Microsoft RECOMMENDED hosting partner, we’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic.ASPHostPortal.com Company offers secure and reliable web hosting for individuals and businesses owners. We are offering shared and reseller hosting and domain names services. Our best cheap hosting packages come with friendly and fast support and with no setup or other hidden fees. All the servers have the latest stable version of Plesk Panel. We listened our customers and now we offer SEVEN Days FREE on all  shared payments.

ASPHostPortal.com is proud to offer a FREE Trial ASP.NET 4 Hosting. We believes in try it before buy it. We are completely confident in our ASP.NET 4 hosting quality and customer service. Anyone is welcome to come and try us before they decide whether or not they want to buy. If the service does not meet your expectations simply cancel before the end of the free trial period.

Tired of SPAM? So are we! All shared & reseller hosting accounts come with FREE SpamExperts incoming email filtering for 1 domain.


FREE ASP.NET 4 Hosting Complete Features:

  • Hosted Domains UNLIMITED
  • Disk Space 5 GB
  • Bandwith 60 GB
  • Total SQL database 2
  • MSSQL/database 200 mb
  • Total MySQL database 3
  • MySQL/database 200 mb
  • UNLIMITED Email Account
  • Email Space 200 MB
  • US, European and Asia Data Center

More Info | Order Now!

Main Windows ASP.NET Hosting Features:

  • Support ASP.NET 1.0/2.0/3.5/4.0 Hosting and ASP.NET 4.5 Hosting
  • Support ASP.NET MVC 3 Hosting and ASP.NET MVC 4 Hosting
  • Support WCF RIA, Silverlight 4 and Silverlight 5 Hosting
  • Support Visual Studio 2010 Hosting and Visual Studio 2012 Hosting
  • Support SQL 2008, SQL 2008 R2, and SQL 2012 Hosting
  • Support Visual Studio LightSwitch Hosting
  • Support Web Deploy Hosting
  • FREE 100 Installation, such as Wordpress, Joomla, Umbraco, DotNetNuke, Orchard, Drupal, etc

Contact Us
If you have any questions, you can reach us via email [email protected] or send us a tweet @asphostportal

About Us
ASPHostPortal.com is a hosting company that best support in Windows and ASP.NET-based hosting. Services include shared hosting, reseller hosting, and sharepoint hosting, with specialty in ASP.NET, SQL Server, and architecting highly scalable solutions. As a leading small to mid-sized business web hosting provider, ASPHostPortal strive to offer the most technologically advanced hosting solutions available to all customers across the world. Security, reliability, and performance are at the core of hosting operations to ensure each site and/or application hosted is highly secured and performs at optimum level.



ASP.NET 4.5.1 - with ASPHostPortal.com :: SEO friendly URLs with ASP.NET

clock February 26, 2014 06:51 by author Kenny

Search engines like human-readable URLs with keywords in it, and hesitate to respect messy URLs with a lot of query-string parameters. So, to make our ASP.NET database-driven website SEO-friendly we have to get rid of our complex URLs.

SEO or Search Engine Optimization is the process of affecting the visibility of a website or a web page in a search engine's "natural" or un-paid ("organic") search results. In general, the earlier (or higher ranked on the search results page), and more frequently a site appears in the search results list, the more visitors it will receive from the search engine's users. SEO may target different kinds of search, including image search, local search, video search, academic search, news search and industry-specific vertical search engines.

Solution 1: Fake pages and "Server.Transfer".
As you can see the two URLs above point to the same page. Basically it is the same page and it works like this: the page mailjet-newsletter-software.aspx contains no code at all and performs a Server.Transfer (aka server-side redirect) to product.aspx like this:
Server.Transfer("product.aspx?ProductID=18");
That's it. We have one "product.aspx" page which expects a "ProductID" parameter and a lot of "fake pages" with SEO-friendly names like firstproduct.aspx, secondproduct.aspx etc., which simply perform a Server.Transfer to the "product.aspx" with the right ProductID.

Simple, isn't it?

But this solution requires a lot of hard-coding - we will have to create all these fake pages and add a Server.Transfer command. So let's go a little further: we will create one base class for all our "fake pages" and add a record to the "tblProducts" table in the database:

Now we have to create our fake pages, inherit them all from the ProductPage class and voi la - that's it! We can also optionally remove all the HTML-code from the aspx-files, leaving the "Page" directive only.

Solution 2: Virtual Pages.

This method is pretty similar, except that we don't need to create any pages at all. Instead, we will add an HttpModule, which intercepts HTTP requests, and the user requests a non-existent page, performs a Rewrite operation. First we will create our HttpModule:

Now we have to register our HttpModule in the web.config:

<httpModules>
<add type="URLRewrite.ProductPageModule, URLRewrite" name="ProductPageModule" />
<httpModules>



ASP.NET 4.5.1 - with ASPHostPortal.com :: How to Create Dynamic DropDownLists in ASP.NET 4.5.1

clock February 26, 2014 06:23 by author Kenny

Now i will tell you how to create Dynamic DropDownLists in ASP.NET 4.5.1

Object:

1. Create dropdownlist dynamically with autopostback property true
2. Keep dropdownlist during postback
3. Maintain selected value during postback.
Here is the sample for this.

In aspx page:
<form
id="form1" runat="server">

    <div>

        <asp:Table ID="tbl" runat="server">

        </asp:Table>

        <asp:Button ID="btnSet" runat="server" Text="Button" onclick="btnSet_Click" /> </div>

    </form>

To Create Dynamic Dropdownlist:

protected
void Page_Load(object sender, EventArgs e)

{

    if (!Page.IsPostBack)

    {

    CreateDynamicTable();

    }

}

    private void CreateDynamicTable()

    {  

        // Fetch the number of Rows and Columns for the table

        // using the properties

        int tblRows = 3;

        int tblCols = 3;

        // Now iterate through the table and add your controls

        for (int i = 0; i < tblRows; i++)

        {

            TableRow tr = new TableRow();

            for (int j = 0; j < tblCols; j++)

            {

                TableCell tc = new TableCell();

                DropDownList ddl = new DropDownList();

                ddl.ID = "ddl-" + i.ToString() + "-" + j.ToString();

                for (int k = 0; k < 5; k++)

                {

                    ddl.Items.Add(new ListItem("item-"+k.ToString(),k.ToString())); 

                }

                ddl.AutoPostBack = true;

                ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);

                // Add the control to the TableCell

                tc.Controls.Add(ddl);

                // Add the TableCell to the TableRow

                tr.Cells.Add(tc);

            }

            // Add the TableRow to the Table

            tbl.Rows.Add(tr);

            tbl.EnableViewState = true;

            ViewState["tbl"] = true;

        }

    }

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)

    {

    // what you want to perform    

    }

To retrieve value on button click:

protected
void btnSet_Click(object sender, EventArgs e)

    {

        foreach (TableRow tr in tbl.Controls )

        {

            foreach (TableCell tc in tr.Controls)

            {

                if (tc.Controls[0] is DropDownList)

                {

                    Response.Write(((DropDownList)tc.Controls[0]).SelectedItem.Text+" ");        

                }

            }

            Response.Write("<br/>"); 

        }

    }
Right Now, No output because dynamic controls are lost in postback then what to do.

So we need to save dynamic controls value and generate dynamic controls again.we need to maintain viewstate.

protected
override object SaveViewState()

{

    object[] newViewState = new object[2];

    List<string> txtValues = new List<string>();

    foreach (TableRow row in tbl.Controls)

    {

        foreach (TableCell cell in row.Controls)

        {

            if (cell.Controls[0] is DropDownList)

            {

                txtValues.Add(((DropDownList)cell.Controls[0]).SelectedIndex.ToString());

            }

        }

    }

    newViewState[0] = txtValues.ToArray();

    newViewState[1] = base.SaveViewState();

    return newViewState;

}

protected override void LoadViewState(object savedState)

{

    //if we can identify the custom view state as defined in the override for SaveViewState

    if (savedState is object[] && ((object[])savedState).Length == 2 && ((object[])savedState)[0] is string[])

    {

        object[] newViewState = (object[])savedState;

        string[] txtValues = (string[])(newViewState[0]);

        if (txtValues.Length > 0)

        {

            //re-load tables

            CreateDynamicTable();

            int i = 0;

            foreach (TableRow row in tbl.Controls)

            {

                foreach (TableCell cell in row.Controls)

                {

                    if (cell.Controls[0] is DropDownList && i < txtValues.Length)

                    {

                        ((DropDownList)cell.Controls[0]).SelectedIndex = Convert.ToInt32(txtValues[i++]);

                    }

                }

            }

        }

        //load the ViewState normally

        base.LoadViewState(newViewState[1]);

    }

    else

    {

        base.LoadViewState(savedState);

    }

}



ASP.NET 4.5.1- with ASPHostPortal.com :: How to Create Barcodes using ASP.NET App

clock February 26, 2014 05:09 by author Kenny

To create barcodes we will use ASP.NET web services. Not only that, we will also create Windows Forms and Console application to request barcode image.

What is The Benefits?

Well, web services provide a major benefit in integrating the software with external applications. With standardized request/response model, any client application that can utilize XML web service can benefit from it.Below is the brief visual representation of the barcode service. The clients do not need to refer to Aspose.BarCode for .NET. They will just send 2 string values (codetext and symbology) and will get the barcode image (byte array) from service.

Barcode Web Service
Now, open Microsoft Visual Studio. Create a new project of type “ASP.NET Web Service Application”. Name the project as “BarCodeService”. Add reference to the following .NET assemblies.

  1. System.Drawing from .NET tab of “Add Reference” dialog box
  2. Aspose.BarCode.

Browse to the location where Aspose.BarCode for .NET is installed and select. Visual Studio adds a default class “Service1” to the Web Service project in Service1.asmx file.
Open it and add the following method to this class.

The web method needs the following two parameters from client:

  1. Codetext
  2. Symbology

These parameters are of String type. The parameters are passed to the BarCodeBuilder class, which then creates the barcode and sends the barcode image in the form of byte array to the client.
This web method can be called by any kind of application that can consume a web service.


Consume Web Service from Windows Forms Application

Open Visual Studio and create a new project of type “Windows Application”. Name the project as “ GetBarCodeWinForms ”. Add reference to the web service by right clicking on “References” and then choosing “Add Service Reference” from the context menu. Type the address of web service or discover it. After getting the correct service, give “BarCodeService” in the Namespace and click on “Ok” button to add the reference.

Design the forms as follows.

It contains the following controls:

  1. Textbox: Input codetext from user
  2. Combobox: Input symbology type from user
  3. Button: Call web service
  4. Picturebox: Display the barcode image

Write the following code on click event of the button.

Run the application, specify some values and click on the “Get Barcode” button. The application will consume the barcode web service and get the barcode image from it. The image will then be displayed on the form as below.

Consume Web Service from a Console Application

Create a new project in Visual Studio and choose “Console Application” in project type. Name the project as “ GetBarCodeConsole ”. Add the reference to the barcode service, just as we gave above in the winforms application.Write the below code in the main() method.

Run the application, it will consume the barcode web service, get barcode image and save the image locally to disk.

Summary

Aspose.BarCode for .NET can easily be used in ASP.NET web services to generate the barcodes and serve the barcode image to various clients.



ASP.NET 4.5.1 Hosting - ASPHostPortal.com :: How to Create a Sign Up/Registration Page in ASP.NET

clock January 10, 2014 07:17 by author Ben

Here is the simple step to create a sign up/registration page in ASP.NET. Lets check this out :
1. Open the Microsoft Visual Studio
2. Select one New Asp.Net Web application
3. Open the Design Default.aspx page
4. Drag and Drop one DropDown list and button from the Tool box.
5. Add one new item( i.e., New Registration Page) for the Drop down list
6. Procedure for adding items : Right click on the DropDown List and select properties and select items and add NewRegistration in Text Field.
7. Change the properties of the Dropdown list
a.Kept AutopostBack = True;
b.select the SelectedIndexChanged Event for that..
8. Open the code page that is Default.aspx.cs and and create a method in SelectedIndexChanged event of dropdownlist

using System; 
using System.Collections; 
using System.Configuration; 
using System.Data; 
using System.Linq; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.HtmlControls; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Xml.Linq; 
using System.Data.SqlClient; 
 
public partial class Dynamic_controls : System.Web.UI.Page 

    SqlConnection con; 
    SqlCommand com; 
  protected void Page_Load(object sender, EventArgs e) 
    {        
        
    } 
protected void ddlist_SelectedIndexChanged(object sender, EventArgs e) 
    { 
        Createnewaccount();  
    } 

9. Create new methods for Different controls by using the main method(i.e., Createnewaccount)

private void Createnewaccount ()
         {
             CreateDynamicTextBoxes ();
             CreateDynamicTextBoxes1 ();
             CreateDynamicCheckBoxes ();
             CreateDynamicCheckBoxes1 ();
             CreateDynamicRadioButtons1 ();
             BindDropDownLists ();
         }

10. Create all types of dynamic controls

 protected void CreateDynamicTextBoxes ( )
        {
           
            int c = 1 ;
            TextBox [ ] textBoxArr = new TextBox [ c ] ;/ / array of textboxes
            for (int i = 0 ; i < c ; i + + )
            {
                 
                textBoxArr [ i ] = new TextBox ( ) ;
                textBoxArr [ i ] . ID = " txtBox " + i.ToString ( ) ;
                PH_Name.Controls.Add ( textBoxArr [ i ] ) ;
                RequiredFieldValidator reqfldVal = new RequiredFieldValidator ( ) ;
                reqfldVal.ID = " RequiredValidator " + i ;
                reqfldVal.ControlToValidate = " txtBox " + i ;
                reqfldVal.ErrorMessage = " Not Empty " ;
                reqfldVal.SetFocusOnError = true ;
                PH_Name.Controls.Add ( reqfldVal ) ;
            }
        }
        protected void CreateDynamicTextBoxes1 ( )
        {
            int c = 1 ;
            TextBox [ ] textBoxArr1 = new TextBox [ c ] ;/ / array of textboxes
            for (int i = 0 ; i < c ; i + + )
            {
      
                textBoxArr1 [ i ] = new TextBox ( ) ;
                textBoxArr1 [ i ] . ID = " txtBox1 " + i.ToString ( ) ;
                PH_pwd.Controls.Add ( textBoxArr1 [ i ] ) ;
                RequiredFieldValidator reqfldVal1 = new RequiredFieldValidator ( ) ;
                reqfldVal1.ID = " RequiredValidator1 " + i ;
                reqfldVal1.ControlToValidate = " txtBox1 " + i ;
                reqfldVal1.ErrorMessage = " Not Empty " ;
                reqfldVal1.SetFocusOnError = true ;
                PH_pwd.Controls.Add ( reqfldVal1 ) ;
                 
            }
        }
        private void BindDropDownLists ( )
        {
            SqlDataSource sqlDS = new SqlDataSource ( ) ;
            sqlDS.ConnectionString = ConfigurationManager.ConnectionStrings [ " SAMPLE_2 " ] . ToString ( ) ;
            sqlDS.SelectCommand = " Select CountryID , COUNTRY_NAME from countrynames " ;
            PH_country.Controls.Add ( sqlDS ) ;
            DropDownList ddl = new DropDownList ( ) ;
            ddl.ID = " ddlrank " ;
            ddl.DataSource = sqlDS ;
            ddl.DataTextField = " COUNTRY_NAME " ;
            ddl.DataValueField = " CountryID " ;
            PH_country.Controls.Add ( ddI ) ;
            foreach ( Control ctl in PH_country.Controls )
            {
                if ( ctl is DropDownList )
                {
                    ( ctl as DropDownList ) . DataBind ( ) ;
                }
            }
        }
        protected void CreateDynamicCheckBoxes ( )
        {
                   
                CheckBox chk ;
                chk = new CheckBox ( ) ;
                chk.ID = " chkhobbies " ;
                chk.Text = " savings " ;
                chk.AutoPostBack = false ;
                PH_trans.Controls.Add ( chk ) ;
             
        }
        protected void CreateDynamicCheckBoxes1 ( )
        {
           
            int c = 1 ;
            CheckBox [ ] chk = new CheckBox [ c ] ;
            for (int i = 0 ; i < c ; i + + )
            {
                chk [ i ] = new CheckBox ( ) ;
                chk [ i ] . ID = " chkhobbies1 " + i.ToString ( ) ;
                chk [ i ] . Text = " Current" ;
                chk [ i ] . AutoPostBack = false ;
                PH_trans.Controls.Add ( chk [ i ] ) ;
            }
        }
        protected void CreateDynamicRadioButtons ( )
        {
                Male = new RadioButton RadioButton ( ) ;
                Female = new RadioButton RadioButton ( ) ;
                male = new RadioButton ( ) ;
                female = new RadioButton ( ) ;
                male.Text = " Male " ;
                female.Text = " Female " ;
                male.Checked = false ;
                female.Checked = false ;
                male.GroupName = " unknown " ;
                female.GroupName = " unknown " ;
                male.ID = " malegender " ;
                female.ID = " unknown " ;
                male.AutoPostBack = false ;
                female.AutoPostBack = false ;
                PH_gender.Controls.Add ( male ) ;
                PH_gender.Controls.Add (female ) ;
        }
        protected void CreateDynamicRadioButtons1 ( )
        {
            RadioButtonList radio = new RadioButtonList ( ) ;
            radio.ID = " rblRow " ;
            radio.Items.Add ( new ListItem ( " Male " ) ) ;
            radio.Items.Add ( new ListItem ( " Female " ) ) ;
            PH_gender.Controls.Add ( radio ) ;
             
        }
        protected void CreateDynamicPanel ( )
        {
           
            int c = 1 ;
            TextPanel panel = new Panel ( ) ;
            for (int i = 0 ; i < c ; i + + )
            {
                TextPanel.ID = " txtPanel " + i.ToString ( ) ;
                PlaceHolder1.Controls.Add ( TextPanel ) ;
            }
        }

11. Add the following code to store the data in database

protected void btn_submit_Click ( object sender , EventArgs e )
        {
            for (int i = 0 ; i < 1 ; i + + )
            {
                 
                txtvalue string = " txtBox " + i.ToString ( ) ;
                txtvalue1 string = " txtBox1 " + i.ToString ( ) ;
                ddlvalue string = " ddlrank " ;
                chkvalue string = " chkhobbies " ;
                chkvalue1 string = " chkhobbies1 " + i.ToString ( ) ;
                rbvalue string = " rblRow " ;
                 
                TextBox txt = ( TextBox ) PlaceHolder1.FindControl ( txtvalue ) ;
                TextBox txt1 = ( TextBox ) PlaceHolder1.FindControl ( txtvalue1 ) ;
                DropDownList Dddl = ( DropDownList ) PlaceHolder1.FindControl ( ddlvalue ) ;
                CheckBox Dchk = ( CheckBox ) PlaceHolder1.FindControl ( chkvalue ) ;
                CheckBox Dchk1 = ( CheckBox ) PlaceHolder1.FindControl ( chkvalue1 ) ;
                RadioButtonList Drd = ( RadioButtonList ) PlaceHolder1.FindControl ( rbvalue ) ;
                if ( txt ! = null )
                {
                    try
                    {
                        string strText = txt.Text ;
                        strText1 string = txt1.Text ;
                        strddl string = Dddl.SelectedItem.Text ;
                        strchk string = Dchk.Text ;
                        strchk1 string = Dchk1.Text ;
                        strrdb string = Drd.Text ;
                        / / Store value in database textbox Cell
                        con = new SqlConnection ( ConfigurationManager.ConnectionStrings [ " SAMPLE_2 " ] . ToString ( ) ) ;
                        con.Open ( ) ;
                        com = new SqlCommand ( " insert into Dynamic_Form ( UserName , LastName , DropdownlistValue , Chksavings , Chkcurrent , Radiovalue ) values ​​( ' " + strText + " ' , ' " + strText1 + " ' , ' " + strddl + " ' , ' " strchk + + " ' , ' " + strchk1 + " ' , ' " + strrdb + " ' ) " , con ) ;
                        com.ExecuteNonQuery ( ) ;
                        con.Close ( ) ;
                        lbl_error.Text = " Account Successfully Created " ;
                         
                    }
                    catch ( Exception ex )
                    {
                        throw ex ;
                        / / lbl_error.Text = " There is a problem while creating Account " ;
                         
                    }
                }
            }
        }

Now, run your program and see the result :



ASP.NET 4.5 Free Trial Hosting - ASPHostPortal.com :: AJAX Control ToolKit DragPanel Tutorial ASP.NET C#

clock October 24, 2013 10:25 by author Ben

Ajax is Asynchronous JavaScript And Xml. Ajax is a group of interrelated web development techniques used on the client-side to create asynchronous web applications. With Ajax, web applications can send the data to, and retrieve the data from, a server asynchronously (in the background) without interfering with the display and behavior of the existing page.


Here i am describing how to use the Ajax Control Toolkit in our webpage.

1. Download from Ajax Ajax Control Toolkit site.

2. Extract the downloaded zip file.

3. Add Ajax refrence to you project through the menu bar click on the website and select add reffrence.

4. Go to the Browse tab and select the Ajax dll file and click ok.

5. Now open your webpage and add script manager roomates is present on you in the category of the toolbox and ajax extension.

6. After that open the Ajax Control Toolkit your category and add any webpage with Ajax control, and set its properties ajax control.


The extender DragPanel Easily Allows users to add "draggability" to their controls. The DragPanel targets any ASP.NET Panel and takes an additional parameter that signifies the control to use as the "drag handle". Once initialized, the user can freely drag the panel around the web page using the drag handle.

First add or open a new WebForm to this project and name it DragPanel.aspx

Next we will add a ToolScriptManager.

Now we can drag a PanelControl to the webform, we added some CSS styling to it, we kept it fairly simple, and we also added some text inside the panel.
Here is copy -paste this code on your workspace :



And now you can compile the program and see the result. Literally this DragPanel Control Extender is so easy to use that you will be tempted to use it all the time with all the panels. We hope you understood the AJAX Tutorial posted Today.



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in