All About ASP.NET and ASP.NET Core 2 Hosting BLOG

Tutorial and Articles about ASP.NET and the latest ASP.NET Core

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.



ASP.NET Hosting - ASPHostPortal.com :: How to call multiple validation group in ASP.NET

clock August 8, 2016 20:15 by author Dan

Recently I had this requirement where in a single button click I need to call multiple Validation groups. The scenario is something like this. I had a ASP.NET page where there were 5 user controls and each had their own validation controls embedded in them. Each user control had its own validation controls and they had their own Validation group defined. All these user controls were placed in a single page which only had two button “Submit” and “Canel”. On click of the “Submit” button all the validation controls in the form should execute.

The problem here is that there are five different validation groups in the same page. To top it all you can only assign one validation group to a button’ ValidationGroup property. If you don’t assign any validation group then on click of the submit button the validation controls which don’t have any validation group defined for them will only be fired. Validation controls which have validation group property defined will not get fired. This is the default behavior of validation controls. So how to call the validation controls of different groups? The answer lies in calling the “Page_ClientValidate” javascript method with the validation group name.

Lets try to understand how this all words with some code.The HTML code of the page looks something like this.

 <table width="100%">

         <tr>

             <td>

                 <asp:TextBox ID="TextBox1"

 runat="server"></asp:TextBox>

                 <asp:RequiredFieldValidator

 ID="RequiredFieldValidator1" runat="server"

 ErrorMessage="RequiredFieldValidator"

 ValidationGroup="Group1" ControlToValidate="TextBox1">

 </asp:RequiredFieldValidator>

             </td>           

         </tr>

         <tr>

             <td>

                 <asp:TextBox ID="TextBox2"

 runat="server"></asp:TextBox>

                 <asp:RequiredFieldValidator

 ID="RequiredFieldValidator2" runat="server"

 ErrorMessage="RequiredFieldValidator"

 ValidationGroup="Group2" ControlToValidate="TextBox2">

 </asp:RequiredFieldValidator>

             </td>
         </tr>

         <tr>

             <td>

                     <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>                   
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="RequiredFieldValidator"

 ValidationGroup="Group3" ControlToValidate="TextBox3">

 </asp:RequiredFieldValidator>

             </td>

         </tr>

         <tr>

             <td>
                 <asp:TextBox ID="TextBox4"

 runat="server"></asp:TextBox>

                 <asp:RequiredFieldValidator

 ID="RequiredFieldValidator4" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="TextBox4">

 </asp:RequiredFieldValidator>

             </td>

         </tr>

         <tr>

             <td>

                 <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="javascript:return

 validatePage();" />

                 <asp:Button ID="btnCancel" runat="server" Text="Cancel" />

             </td>

         </tr>

 </table>


From the above markup you can make out that there are four required field validators and out of the four validators three have validation group property defined. In such a scenario when you click the submit button only the validator which doesn’t have validation group will be executed i.e. RequiredFiedlValidator4 will only be executed. Since there are more than one validation group assigning button’ ValidationGroup wont work as it will execute only validator controls which belong to the assigned validaiton group. Other validator controls belonging to other validation group won’t execute. Also there is no way to specify multiple validaiton group using the ValidationGroup property of the button control.

The way to solve this problem is to call Page_ClientValidate javascript function. Page_ClientValidate is a javascript function generated by ASP.NET. The function takes validation group name as an argument. The javascript function which gets called when the submit button is clicked is pasted below.

 <script language="javascript" type="text/javascript">

 function validatePage()

 {

     //Executes all the validation controls associated with group1 validaiton Group1.

     var flag = Page_ClientValidate('Group1');

     if (flag)

     //Executes all the validation controls associated with group1 validaiton Group2.

         flag = Page_ClientValidate('Group2');

     if (flag)

     //Executes all the validation controls associated with group1 validaiton Group3.

         flag = Page_ClientValidate('Group3');

     if (flag)

     //Executes all the validation controls which are not associated with any validation group.

         flag = Page_ClientValidate();

     return flag;

 }

 </script>


In the above code you can see the Page_ClientValidate function is called four times, first by passing the first validation group name, second time passing on the second validation group name and so on. If you see the last call to Page_ClientValidate, it is called with an empty argument. When call Page_ClientValidate with no argume/validation group name it executes all the validation controls in the page which don’t have a validation group assigned to them. So if one wants to execute validation controls which are not having any validation group associated with them you can call the Page_ClientValidate without any parameter.

So using Page_ClientValidate javascript function one can execute all the validation controls in the page by passing the validation group name or without any validation group name.

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 Core 1.0 Hosting - ASPHostPortal.com :: Easy Steps to avoid multiple database request in ASP.NET

clock July 22, 2016 20:09 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 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.



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

 photo ahp banner aspnet-01_zps87l92lcl.png

 

Corporate Address (Location)

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

Tag cloud

Sign in