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 Hosting - ASPHostPortal.com :: Simple Steps to Render ASP.NET MVC Layout

clock January 27, 2017 06:56 by author Dan

According to dotnettrick website. In Asp.Net MVC, Layouts are like as Master Pages in Asp.Net Web Forms. These helps us to maintain consistent look and feel across all the views within your Asp.Net MVC application. Like Master Pages, Layout may contains common CSS, jQuery files across the multiple Views and one or more placeholders for which Views provide content. For layout and its components refer this article Layouts, RenderBody, RenderSection and RenderPage in ASP.NET MVC.

In Asp.Net MVC, at application level we have _ViewStart file with in Views folder for defining the default Layout page for your Asp.Net MVC application. In this article, I am going to expose the different ways to apply layout pages for your application. Suppose we have to render the layouts as shown in the fig. by using various ways.

Method 1 : Control Layouts rendering by using _ViewStart file in the root directory of the Views folder

We can change the default rendering of layouts with in _ViewStart file by using the below code:

    @{
     var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
    
     string layout = "";
     if (controller == "Admin")
     {
     layout = "~/Views/Shared/_AdminLayout.cshtml";
     }
     else
     {
     layout = "~/Views/Shared/_Layout.cshtml";
     }
    
     Layout = layout;
    }

Method 2 : Return Layout from ActionResult

We can also override the default layout rendering by returning the layout from the ActionResult by using the below code:

    public ActionResult Index()
    {
     RegisterModel model = new RegisterModel();
     //TO DO:
     return View("Index", "_AdminLayout", model);
    }

Method 3 : Define Layout with in each view on the top

We can also override the default layout rendering by defining the layout on the view by using the below code:

    @{
     Layout = "~/Views/Shared/_AdminLayout.cshtml";
    }

Method 4 : Adding _ViewStart file in each of the directories

We can also set the default layout for a particular directory by putting _ViewStart file in each of the directories with the required Layout information as shown below:


    @{
     Layout = "~/Views/Shared/_AdminLayout.cshtml";
    }

Best ASP.NET Core 1.0 Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: Trick to Run Website in Many Browser in Visual Studio

clock January 13, 2017 11:12 by author Dan

According to dailydotnettips article, As a web developer, for performing cross browser testing, we need to run our web site in multiple browser from Visual Studio. Generally, in a common way, we select particular browser from browser selection menu and run the application. 

However, you can set multiple browser as your default browser. When you run the application with out debugging ( Ctrl+ F5) , Visual Studio will run the application in all the browser, in case of debugging (F5),  Visual Studio will prompt you to select particular browser from the selected default browser list. You can link this feature very much with Refreshing browsers directly from Visual Studio 2013, where you can refresh the browser directly from Visual Studio.

In the browser list drop-down, by default you will be able to see all the list of added browser, with default browser as checked.

When you select the “Browse With…” option, following dialog will appear, and you can see all the list of browser along with the browser which marked as “(Default)”.

Now, there can be more than one default browser, and same has been written in the dialog control as well – “Browsers (Select one or more):” . So, select all the browser in which you want run the application together, and click on “Set as Default”.  That’s all. Now if you click on “Browse” button in the same dialog control, you will find your web application starts on all the selected browser same time.

If you back to Visual Studio main menu, a new option “Multiple Browser” will appear.

Now, if you want to debug the application, and press “F5” or select the multiple browsers options, following dialog will appear, and you need to select a specific browser from the list of selected browsers.

If you run the application without debugging mode and wanted to run the application to verify the cross browser compatibility, Visual Studio will invoke all the browser for the same application.

This feature is really useful for web developer and who spends time on for cross browser testing ! and of courser – all the web developer spends time for the same !! So, from next time, apply this feature!

Note: This is note new features with Visual Studio 2013, it was available in previous version as well.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides our customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server 2012. We offers Windows hosting starts from $5/month only. We also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable Windows server 2012 Hosting, we should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: How to Stop AutoFill Browser in TextBox with ASP.NET

clock January 8, 2017 04:03 by author Dan

According to dotmettrick's website. Today’s browsers like Chrome, Firefox, Internet Explorer and Safari has functionality of auto complete values in TextBoxes. If you have enabled this features in your browser, then each and every time when you start to enter value in TextBox you get a drop down of prefilled values in that TextBox. This feature of browser can be disabled by the programming for a specific web form like payment form and other confidential information form of a web application.

In chrome browser, we can enable auto-fill as shown below:

Suppose we have a below form for online payment of product by credit card or debit card then it is mandatory to stop auto complete functionality of browser so that browser doesn’t save the confidential information of a customer’s credit card or debit card.


We can turn off auto-fill for our complete form by setting autocomplete attribute value to off as shown below:

     <form id="Form1" method="post" runat="server" autocomplete="off">
     .
     .
    </form>


We can also turn off auto-fill for a particular TextBox by setting autocomplete attribute value to off as shown below:

     <asp:TextBox Runat="server" ID="txtConfidential" autocomplete="off"></asp:TextBox>

We can also do this from code behind also like as:

     txtConfidential.Attributes.Add("autocomplete", "off");

After doing one of above code you will see that there is no auto-fill.


Summary

In this article, I explain how can you stop auto-complete in TextBox by programming. I hope you will use this trick in your web form. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: All About ASP.NET Master Pages

clock November 11, 2016 10:31 by author Dan

According to venkataspinterview blog, What are Master Pages in ASP.NET? or What is a Master Page? ASP.NET master pages allow you to create a consistent layout for the pages in your application. A single master page defines the look and feel and standard behavior that you want for all of the pages (or a group of pages) in your application. You can then create individual content pages that contain the content you want to display. When users request the content pages, they merge with the master page to produce output that combines the layout of the master page with the content from the content page.

What are the 2 important parts of a master page?
The following are the 2 important parts of a master page
1. The Master Page itself
2. One or more Content Pages

Can Master Pages be nested?
Yes, Master Pages be nested.

What is the file extension for a Master Page?
.master

How do you identify a Master Page?
The master page is identified by a special @ Master directive that replaces the @ Page directive that is used for ordinary .aspx pages.

Can a Master Page have more than one ContentPlaceHolder?
Yes, a Master Page can have more than one ContentPlaceHolder

What is a ContentPlaceHolder?
ContentPlaceHolder is a region where replaceable content will appear.

How do you bind a Content Page to a Master Page?
MasterPageFile attribute of a content page's @ Page directive is used to bind a Content Page to a Master Page.

Can the content page contain any other markup outside of the Content control?
No.

What are the advantages of using Master Pages?
1. They allow you to centralize the common functionality of your pages so that you can make updates in just one place.
2. They make it easy to create one set of controls and code and apply the results to a set of pages. For example, you can use controls on the master page to create a menu that applies to all pages.
3. They give you fine-grained control over the layout of the final page by allowing you to control how the placeholder controls are rendered.
4. They provide an object model that allows you to customize the master page from individual content pages.

What are the 3 levels at which content pages can be attached to Master Page?
At the page level - You can use a page directive in each content page to bind it to a master page

At the application level - By making a setting in the pages element of the application's configuration file (Web.config), you can specify that all ASP.NET pages (.aspx files) in the application automatically bind to a master page.

At the folder level - This strategy is like binding at the application level, except that you make the setting in a Web.config file in one folder only. The master-page bindings then apply to the ASP.NET pages in that folder.

What is @MasterType directive used for?
@MasterType directive is used to create a strongly typed reference to the master page.

Are controls on the master page accessible to content page code?
Yes, controls on the master page are accessible to content page code.

At what stage of page processing master page and content page are merged?
During the initialization stage of page processing, master page and content page are merged.

Can you dynaimically assign a Master Page?
Yes, you can assign a master page dynamically during the PreInit stage using the Page class MasterPageFile property as shown in the code sample below.
void Page_PreInit(Object sender, EventArgs e)
{
this.MasterPageFile = "~/MasterPage.master";
}


Can you access non public properties and non public methods of a master page inside a content page?
No, the properties and methods of a master page must be public in order to access them on the content page.

From the content page code how can you reference a control on the master page?
Use the FindControl() method as shown in the code sample below.
void Page_Load()
{
// Gets a reference to a TextBox control inside
// a ContentPlaceHolder
ContentPlaceHolder ContPlaceHldr = (ContentPlaceHolder)Master.FindControl ("ContentPlaceHolder1");
if(ContPlaceHldr != null)
{
TextBox TxtBox = (TextBox)ContPlaceHldr.FindControl("TextBox1");
if(TxtBox != null)
{
TxtBox.Text = "TextBox Present!";
}
}
// Gets a reference to a Label control that not in
// a ContentPlaceHolder
Label Lbl = (Label)Master.FindControl("Label1");
if(Lbl != null)
{
Lbl.Text = "Lable Present";
}

}

Can you access controls on the Master Page without using FindControl() method?
Yes, by casting the Master to your MasterPage as shown in the below code sample.
protected void Page_Load(object sender, EventArgs e)
{
MyMasterPage MMP = this.Master;
MMP.MyTextBox.Text = "Text Box Found";
}

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice



ASP.NET Hosting - ASPHostPortal.com :: Easy Steps to Use Method Overloading in C# ASP.NET

clock October 7, 2016 22:26 by author Dan

If a class have multiple methods by same name but different parameters, it is known as Method Overloading.

string sum(int A)
string sum(int A, int B)

C# no need to use any keyword while overloading a method either in same class or in derived class.

While overloading methods, a rule to follow is the overloaded methods must differ either in number of arguments they take or the data type of at least one argument.

Example

using System;
namespace MethodOverloading
{
    class Class1
    {
        public int Sum(int A, int B)
        {
            return A + B;
        }
        public float Sum(int A, float B)
        {
            return A + B;
        }
    }
    class MainClass
    {
        static void Main()
        {
            Class1 obj = new Class1();
            Console.WriteLine(obj.Sum(20, 30));
            Console.WriteLine(obj.Sum(20, 15.70f));
            Console.Read();
        }
    }
}

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: Easy Ways to avoid multiple database request in ASP.NET

clock October 3, 2016 20:23 by author Dan

It is not good to execute multiple db request for loading single page.  Review your database code to see if you have request paths that go to the database more than once. Each of those round-trips decreases the number of requests per second your application can serve. By returning multiple resultsets in a single database request, you can cut the total time spent communicating with the database.

In order to improve performance you should execute single stored proc and bring multiple resultset in to single db request.  In this article i will explain you how to avoid multiple database request and how to bring multiple resultset into single db request.

Consider a scenario of loading a Product Page, which displays

  • Product Information and
  • Product Review Information

In order to bring 2 database request in single db request, your sql server stored proc should be declared as below.

SQL Server Stored Proc

CREATE PROCEDURE GetProductDetails
 @ProductId bigint,
AS
SET NOCOUNT ON

--Product Information
Select ProductId,
 ProductName,
 ProductImage,
 Description,
 Price
From Product
Where ProductId = @ProductId

--Product Review Information
Select  ReviewerName,
 ReviewDesc,
 ReviewDate
From ProductReview
Where ProductId = @ProductId

Asp.net, C# Code to bring multiple db request into single db request

Code Inside Data Access Class Library (DAL)

public DataSet GetProductDetails()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "GetProductDetails";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataSet dsResultSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);

try
{
    var conString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnStr"];
    string strConnString = conString.ConnectionString;
    SqlConnection conn = new SqlConnection(strConnString);

    cmdToExecute.Connection = conn;

    cmdToExecute.Parameters.Add(new SqlParameter("@ ProductId", SqlDbType.BigInt, 8, ParameterDirection.Input, false, 19, 0, "", DataRowVersion.Proposed, _productId));

    //Open Connection
    conn.Open();

    // Assign proper name to multiple table
    adapter.TableMappings.Add("Table", "ProductInfo");
    adapter.TableMappings.Add("Table1", "ProductReviewInfo");
    adapter.Fill(dsResultSet);

    return dsResultSet;             
}
catch (Exception ex)
{
    // some error occured.
    throw new Exception("DB Request error.", ex);
}
finally
{
    conn.Close();
    cmdToExecute.Dispose();
    adapter.Dispose();
}
}

Code Inside Asp.net .aspx.cs page

protected void Page_Load(object sender, EventArgs e)
{
   if (Request.QueryString[ProductId] != null)
   {
      long ProductId = Convert.ToInt64(Request.QueryString[ProductId].ToString()); 
  
      DataSet dsData = new DataSet();

      //Assuming you have Product class in DAL
      ProductInfo objProduct = new ProductInfo();
      objProduct.ProductId = ProductId;
      dsData = objProduct.GetProductDetails();

      DataTable dtProductInfo = dsData.Tables["ProductInfo"];
      DataTable dtProductReviews = dsData.Tables["ProductReviewInfo"];

      //Now you have data table containing information
      //Make necessary assignment to controls
      .....
      .....
      .....
      .....
      ..... 

    }
}


Hope above code gave you basic idea of why it is important to avoid multiple db request and how to bring multiple recordset with single db request.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: How to prevent Button Click in ASP.NET ( Until Insert Query Done)

clock September 19, 2016 21:22 by author Dan

In this post you will see how to do some simple prevention on Asp.net page button click until long time inserting query done.

If you work a lot with SQL Store procedure, or other ways of T-SQL communication between your Asp.net page and database, it's so possible that you have to do some prevention when user try to insert or update some long data to SQL .

With this line of code when user make first click button become a disabled until inserting,updating done!.

protected void Page_Load(object sender, EventArgs e)
{
        Button1.Attributes.Add("onclick", " this.disabled = true; " + ClientScript.GetPostBackEventReference(Button1, null) + ";");   // C#
}

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Button.Attributes.Add("onclick", " this.disabled = true; " &
ClientScript.GetPostBackEventReference(Button1, Nothing) & ";") // VB.NET
End Sub

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Core 1.0 Hosting - ASPHostPortal.com :: How to Create Connection Polling in ASP.NET

clock September 2, 2016 23:23 by author Dan

I will explain what is connection pooling in asp.net using c#, vb.net with example or how to use connection pooling in ado.net with example or asp.net understand connection pooling with example in c#, vb.net with example. Connection pooling in asp.net is the place where it maintains set of active connections to database based on configuration and it reduce the cost of opening and closing connection to database.

What is Connection Pooling in Asp.NET?

Generally connecting to database server is a time consuming process because whenever we request to connect database first it will establish network handshaking with server and then connection string will be parsed and it will check whether given connection credentials correct or not to connect server and so on.

In our applications mostly we use one or two connection configurations and repeatedly same connection configuration will be opened and closed, automatically huge time will be consumed to open and close same database connection.

To reduce the cost of opening and closing the same connection repeatedly, ADO.NET uses an optimization technique called connection pooling.

Connection pooling is the place where it will maintain all the active database connections in one place to reduce the cost of opening and closing database connections. Whenever user send new request to Open a database connection the pooler will looks for an available connection in the pool in case if a pooled connection available then it will return pooled connection instead of opening new connection otherwise the new connection pool is created with the connection string in the connection for next time reuse.

Once we finished operations on database we need to Close the connection then that connection will be returned to the pool and its ready to be reused on the next Open call.

Create Connection Pooling in Asp.Net

To enable this connection pooling in asp.net we don’t need to do anything by default connection pooling is enabled in ADO.NET. Unless we manually disable the connection pooling, the pooler will optimize the connections when they are opened and closed in our application.

First time if we are opening a new connection, a distinct new connection pool is created based on the matching connection string in the connection. While creating connection pool it will check is there any connection pool created with that connection string or not by using keywords supplied in connection. In case if we send connection strings keywords in different order then it will treat it as separate connection string and same connection will be pooled separately.

C# Code

using (SqlConnection con = new SqlConnection("Data Source=Suresh;Integrated security=SSPI;Initial Catalog=SampleDB"))
{
con.Open();
// Connection Pool A will be created.
}
using (SqlConnection con = new SqlConnection("Data Source=Suresh;Integrated security=SSPI;Initial Catalog=aspdotnetDB"))
{
con.Open();
// Separate connection pool B will create because connection string different.
}
using (SqlConnection con = new SqlConnection("Data Source=Suresh;Initial Catalog=aspdotnetdb;Pooling=false;"))
{
con.Open();
// No connection pool will create because we defined Pooling = false.
}
using (SqlConnection con = new SqlConnection("Data Source=Suresh;Integrated security=SSPI;Initial Catalog=SampleDB"))
{
con.Open();
// This connection string matches with Connection Pool A.
}

VB.NET Code

Using con As New SqlConnection("Data Source=Suresh;Integrated security=SSPI;Initial Catalog=SampleDB")
' Connection Pool A will be created.
con.Open()
End Using
Using con As New SqlConnection("Data Source=Suresh;Integrated security=SSPI;Initial Catalog=aspdotnetDB")
' Separate connection pool B will create because connection string different.
con.Open()
End Using
Using con As New SqlConnection("Data Source=Suresh;Initial Catalog=aspdotnetdb;Pooling=false;")
' No connection pool will create because we defined Pooling = false.
con.Open()
End Using
Using con As New SqlConnection("Data Source=Suresh;Integrated security=SSPI;Initial Catalog=SampleDB")
' This connection string matches with Connection Pool A.
con.Open()
End Using


The connections pooler will remove connections from the pool after it has been idle for approximately 4-8 minutes.

Following are the connection pooler properties which we can add to connection string based on our requirements.

Max Pool Size: We can define maximum number of connections can be created in the pool. By default its 100 and we can add property like Max Pool Size=100.

Min Pool Size: We can define minimum number of connections maintained in the pool. The default is 0. We can add property like Min Pool Size=0.

Pooling: It will allow us to set condition to add connection string to pool or not. By default its true. In case we don’t want to add it into pool then we need to define property like Pooling=false.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Core 1.0 Hosting - ASPHostPortal.com :: Asp.Net Repeater with Paging and Sorting Example in C#, VB.NET

clock August 29, 2016 21:26 by author Dan

Introduction:

Here I will explain how to implement paging and sorting in repeater control in asp.net using c#, vb.net with example or asp.net repeater control with paging and sorting in c#, vb.net with example or asp.net repeater paging with numbers and sort columns with example in c#, vb.net. To implement paging and sorting in asp.net repeater control we need to write custom logic because we don’t have any properties available for enabling pagination and sorting for repeater control.

Description:
 
In previous articles I explained asp.net repeater with paging example, Repeater Control Example in asp.net, sort columns in repeater control in asp.net, jQuery load more data in repeater on button click in asp.net, asp.net scrollable repeater with fixed header, use of using statement in c# and many articles relating to asp.net, css, c#, vb.net and jQuery. Now I will explain how to implement paging and sorting in repeater control in asp.net using c#, vb.net with example.

To implement pagination and sorting in repeater control in asp.net using c#, vb.net first write the code following code in your aspx page

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Asp.Net Repeater Control with Paging & Sorting in C#, VB.NET</title>
<style type="text/css">
.hrefclass
{
color:White;
font-weight:bold;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="rptUserData" runat="server" OnItemCommand="rptUserData_ItemCommand">
<HeaderTemplate>
<table id="tbDetails" style="width:500px; border-collapse: collapse;" border="1" cellpadding="5" cellspacing="0" >
<tr style="background-color: #df5015; height: 30px;"
align="left">
<th>
<asp:LinkButton ID="lnkUserId" runat="server" CommandName="UserId" CssClass="hrefclass">UserId</asp:LinkButton></th>
<th>
<asp:LinkButton ID="lnkUserName" runat="server" CommandName="UserName" CssClass="hrefclass">UserName</asp:LinkButton></thalign>
<th>
<asp:LinkButton ID="lnkEducation" runat="server" CommandName="Education" CssClass="hrefclass">Education</asp:LinkButton></th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr style="height: 25px;">
<td >
<%#Eval("UserId").ToString()%>
</td>
<td >
<%#Eval("UserName").ToString()%>
</td>
<td>
<%#Eval("Education").ToString()%>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div><br />
<asp:Repeater ID="rptPaging" runat="server" onitemcommand="rptPaging_ItemCommand">
<ItemTemplate>
<asp:LinkButton ID="lnkPage"
style="padding:8px; margin:2px; background:#B34C00; border:solid 1px #666; color:#fff; font-weight:bold"
CommandName="Page" CommandArgument="<%# Container.DataItem %>"
runat="server" Font-Bold="True"><%# Container.DataItem %>
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
</form>
</body>
</html>


Now open code behind file and write following code

C# Code

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

public partial class RepeaterwithPagingSorting : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Set View State Value for Initial Sort Order
ViewState["Column"] = "UserId";
ViewState["Sortorder"] = "ASC";
BindRepeater();
}
}
// Binding Repeater Control with Paging and Sorting
private void BindRepeater()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId", typeof(Int32));
dt.Columns.Add("UserName", typeof(string));
dt.Columns.Add("Education", typeof(string));
dt.Rows.Add(1, "Suresh Dasari", "B.Tech");
dt.Rows.Add(2, "Rohini Dasari", "Msc");
dt.Rows.Add(3, "Madhav Sai", "MS");
dt.Rows.Add(4, "Praveen", "B.Tech");
dt.Rows.Add(6, "Sateesh", "MD");
dt.Rows.Add(7, "Mahesh Dasari", "B.Tech");
dt.Rows.Add(8, "Mahendra", "CA");
DataView dvData = new DataView(dt);
PagedDataSource pageds = new PagedDataSource();
DataView dv = new DataView(dt);
//Sorting Filter
dv.Sort = ViewState["Column"] + " " + ViewState["Sortorder"];
pageds.DataSource = dv;
pageds.AllowPaging = true;
pageds.PageSize = 3;
if (ViewState["PageNumber"] != null)
pageds.CurrentPageIndex = Convert.ToInt32(ViewState["PageNumber"]);
else
pageds.CurrentPageIndex = 0;
if (pageds.PageCount > 1)
{
rptPaging.Visible = true;
ArrayList pages = new ArrayList();
for (int i = 0; i < pageds.PageCount; i++)
pages.Add((i + 1).ToString());
rptPaging.DataSource = pages;
rptPaging.DataBind();
}
else
{
rptPaging.Visible = false;
}


rptUserData.DataSource = pageds;
rptUserData.DataBind();
}
// Bind Data for Column Sort
protected void rptUserData_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == ViewState["Column"].ToString())
{
if (ViewState["Sortorder"].ToString() == "ASC")
ViewState["Sortorder"] = "DESC";
else
ViewState["Sortorder"] = "ASC";
}
else
{
ViewState["Column"] = e.CommandName;
ViewState["Sortorder"] = "ASC";
}
BindRepeater();
}
// Binding Data on Page Item Change
protected void rptPaging_ItemCommand(object source, RepeaterCommandEventArgs e)
{
ViewState["PageNumber"] = Convert.ToInt32(e.CommandArgument) - 1;
BindRepeater();
}
}


VB.NET Code

Imports System.Collections
Imports System.Data
Imports System.Web.UI.WebControls

Partial Class VBCode
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
'Set View State Value for Initial Sort Order
ViewState("Column") = "UserId"
ViewState("Sortorder") = "ASC"
BindRepeater()
End If
End Sub
' Binding Repeater Control with Paging and Sorting
Private Sub BindRepeater()
Dim dt As New DataTable()
dt.Columns.Add("UserId", GetType(Int32))
dt.Columns.Add("UserName", GetType(String))
dt.Columns.Add("Education", GetType(String))
dt.Rows.Add(1, "Suresh Dasari", "B.Tech")
dt.Rows.Add(2, "Rohini Dasari", "Msc")
dt.Rows.Add(3, "Madhav Sai", "MS")
dt.Rows.Add(4, "Praveen", "B.Tech")
dt.Rows.Add(6, "Sateesh", "MD")
dt.Rows.Add(7, "Mahesh Dasari", "B.Tech")
dt.Rows.Add(8, "Mahendra", "CA")
Dim dvData As New DataView(dt)
Dim pageds As New PagedDataSource()
Dim dv As New DataView(dt)
'Sorting Filter
dv.Sort = ViewState("Column") + " " + ViewState("Sortorder")
pageds.DataSource = dv
pageds.AllowPaging = True
pageds.PageSize = 3
If ViewState("PageNumber") IsNot Nothing Then
pageds.CurrentPageIndex = Convert.ToInt32(ViewState("PageNumber"))
Else
pageds.CurrentPageIndex = 0
End If
If pageds.PageCount > 1 Then
rptPaging.Visible = True
Dim pages As New ArrayList()
For i As Integer = 0 To pageds.PageCount - 1
pages.Add((i + 1).ToString())
Next
rptPaging.DataSource = pages
rptPaging.DataBind()
Else
rptPaging.Visible = False
End If

rptUserData.DataSource = pageds
rptUserData.DataBind()
End Sub
' Bind Data for Column Sort
Protected Sub rptUserData_ItemCommand(ByVal source As Object, ByVal e As RepeaterCommandEventArgs)
If e.CommandName = ViewState("Column").ToString() Then
If ViewState("Sortorder").ToString() = "ASC" Then
ViewState("Sortorder") = "DESC"
Else
ViewState("Sortorder") = "ASC"
End If
Else
ViewState("Column") = e.CommandName
ViewState("Sortorder") = "ASC"
End If
BindRepeater()
End Sub
' Binding Data on Page Item Change
Protected Sub rptPaging_ItemCommand(ByVal source As Object, ByVal e As RepeaterCommandEventArgs)
ViewState("PageNumber") = Convert.ToInt32(e.CommandArgument) - 1
BindRepeater()
End Sub
End Class

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Core 1.0 Hosting - ASPHostPortal.com :: Easy Steps to Modify Your ASP.NE Controls at Runtime

clock August 26, 2016 22:48 by author Dan

Lets say you are working in a fairly large asp.net application. Now because of situation (or clients request) you want to change all the textbox or button control to some server control or user control. This can be very very tedious JOB if you are using Asp.net 1.X. But if you are using Asp.net 2.0 , there is a very easy way to get this done using tagMapping

it’s a way to turn all instances of a type into another type at compile time. In human language it means that it can turn all e.g. System.Web.UI.WebControls.Textbox (in our example ) instances in the entire website into another control.That is so cool that I had to do a little example. I’ve created a very simple control that inherits from a TextBox and overrides the Text property so that it HTML encodes the text. I placed it in the App_Code folder and called it SafeTextBox.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
///
/// Summary description for SafeTextBox
///
public class SafeTextBox : System.Web.UI.WebControls.TextBox
{
    public override string Text
    {
        get
        {
            return base.Text;
        }
        set
        {
            base.Text = System.Web.HttpUtility.HtmlEncode(value);
        }
    }
}



Then I needed to hook the tag mapping up in the web.config to convert all the text boxes into SafeTextBox instances. It simply converts all TextBox instances on the entire site. Here is what’s needed in the web.config:

<pages> <tagMapping> <add tagType="System.Web.UI.WebControls.TextBox" mappedTagType="SafeTextBox"/> </tagMapping> </pages>

After we add the following line of code in the web.config file all the TextBox control will be mapped to the TextBox.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



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