3

DataBinder.Eval Container.DataItem Performance Asp.Net

Using DataBinder.Eval Container.DataItem Method Slow Down The Performance Of Asp.Net Web Applications noticeably.

DataBinder.Eval Container.DataItem Performance

It is mentioned in MSDN site as -

"Because this method performs late-bound evaluation, using reflection at run time, it can cause performance to noticeably slow compared to standard ASP.NET data-binding syntax."

So one should avoid using this method as much as possible.


We use DataBinder.Eval method quite frequently in controls like GridView, Detailsview, DataList or Repeater to evaluate data binding expressions at run time because of simplicity like i used for Running Total in GridView.

decimal rowTotal = Convert.ToDecimal
              (DataBinder.Eval(e.Row.DataItem, "Amount"));

Or in General context
<%# DataBinder.Eval (Container.DataItem, "Price") %>


Now as Eval method is performance hungry we can avoid using it by writing code like mentioned below.

<%# ((DataRowView)Container.DataItem)["FirstName"] %>

Casting Container.DataItem as DataRowView explicitly performs better then Using Eval method.


3

AllowDefinition MachineToApplication Beyond Application Level Error

It is an error to use a section registered as allowDefinition ='MachineToApplication' beyond application level.

allowDefinition=MachineToApplication Error

This error can be caused by a virtual directory not being configured as an application in IIS.

This error is caused mainly for two reasons.









1. Virtual directory not configured in IIS.


If you have not Configured your application to run on IIS then Create a virtual directory and assign permissions to Application (Read,Write).

Open IIS manager by typing INETMGR by clicking start menu > Run on windows

This will open IIS manager, now right click on the folder containing ur web application files and select properties.

In directory tab click on create button associated with Application name section.

Create Virtual Directory


Click on apply and this should fix the problem.


2. Two or more web.config files.


Chekc whether u r having two or more web.config files in ur application ?

If yes than remove one, web.config file should be in root under virtual directory.

Remove any backup folders if you have which may contain web.config file.


Hope this helps


2

Remove Delete Duplicate Records Or Rows-Sql Server

This post explains how to Remove Delete Duplicate Records Or Rows From Ms Sql Server Database Table.

Different methods of deleting duplicate records.

Delete Duplicate Records In Sql Server
I am using Employees table with FirstName and Department columns.







Remove Duplicate Rows In Sql
First Method.

Delete duplicate records/rows by creating identity column.


duplicate records in table looks like shown in first image.

First of all we need to create a identity column in our table by using code mentioned below.

And table will look like image on the left.



ALTER TABLE dbo.Employees ADD ID INT IDENTITY(1,1) 

Now write this query to delete duplicate rows.

DELETE FROM dbo.Employees
WHERE ID NOT IN (SELECT MIN(ID)
FROM dbo.Employees GROUP BY FirstName,Department) 

This should remove all duplicate records from table.


Second Method.

Delete duplicate records using Row_Number()


If you do not want to make any changes in table design or don't want to create identity column on table then you can remove duplicate records using Row_Number in sql server 2005 onwards.

for this write below mentioned code and execute.

WITH DuplicateRecords AS
(
SELECT *,row_number() OVER(PARTITION BY FirstName,Department ORDER BY 

FirstName) 
AS RowNumber FROM dbo.Employees
)
DELETE FROM DuplicateRecords WHERE RowNumber>1

This should remove all duplicate records from table.


Third Method.

Remove duplicate rows/Records using temporary table


Use below mentioned code to delete duplicates by moving them to temporary table using DISTINCT.

SELECT DISTINCT * INTO TempTable FROM dbo.Employees
GROUP BY FirstName,Department
HAVING COUNT(FirstName) > 1

DELETE dbo.Employees WHERE FirstName
IN (SELECT FirstName FROM TempTable)

INSERT dbo.Employees SELECT * FROM TempTable
DROP TABLE TempTable


Remove delete Duplicate Rows In Sql
And result will be as shown.

Have fun.


18

jQuery Fixed Header Scrollable GridView

In this example i'm explaining how to create Fixed Header Scrollable Gridview Using jQuery in ASP.NET. add JQuery library and fixed header scrollable gridview plugin in solution and add reference to it between <head></head> section of HTML source of aspx page.

Jquery fixed header scrollable gridview in asp.net
I have used northwind database to populate gridview.

you can also create Scrollable GridView With Fixed Headers Using CSS if you don't want to use jQuery or JavaScript.

<head runat="server">
<title>jQuery Fixed Header Scrollable GridView</title>
<script src="jquery-1.4.1.min.js" type="text/javascript">
</script>
<script src="ScrollableGrid.js" type="text/javascript">
</script>
</head>

Add this JQuery function call between <head></head> section

<script type="text/javascript" language="javascript">
$(document).ready(function() 
{
$('#<%=fixedHeaderScrollableGridView.ClientID %>').Scrollable();
}
)
</script>

Add gridview on aspx page and populate it.

<asp:GridView ID="fixedHeaderScrollableGridView" runat="server" 
              DataSourceID="SqlDataSource1" 
              AutoGenerateColumns="False" 
              DataKeyNames="ProductID" 
              AllowPaging="True" 
              PageSize="30">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="ProductID"/>
<asp:BoundField DataField="ProductName" HeaderText="ProductName" /> 
<asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" /> 
<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" /> 
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" /> 
</Columns>
</asp:GridView>
        
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
SelectCommand="SELECT [ProductID], [ProductName], [QuantityPerUnit], 
[UnitPrice], [CategoryName] FROM [Alphabetical list of products]">
</asp:SqlDataSource>

Build and Run the application.

If your application uses Master Page then add reference to library and plugin in head ContentPlaceHolder of master page
<head runat="server">
<title>Fixed Header Scrollable GridView With Master Page</title>
<asp:ContentPlaceHolder id="head" runat="server">
 
<script src="jquery-1.4.1.min.js" type="text/javascript"/>
<script src="ScrollableGrid.js" type="text/javascript"/>
 
</asp:ContentPlaceHolder>
  
</head>
<body>
<form id="form1" runat="server">
  
Add Master Page Content And Design Here 
 
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
        
</asp:ContentPlaceHolder>
</form>
</body>
</html>


Call Scrollable() function of jquery plugin in Head ContentPlaceHolderID of content page.
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
 
<script type="text/javascript" language="javascript">
$(document).ready(function() 
{
  $('#<%=fixedHeaderScrollableGridView.ClientID %>').Scrollable();
}
)
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div>
Put Gridview Source Here 
</div>
</asp:Content>


Download Sample Code


0

Export Selected GridView Rows To Excel

This example explains how to Export Selected GridView Rows To Ms Excel Using CheckBox In Asp.Net 2.0,3.5,4.0 C# And VB.NET.
Place a gridview on aspx page, add checkbox control in it using TemplateField and ItemTemplate to select rows and populate gridview from database, add one button for exporting gridview rows to excel.

Export Selected GridView Rows to excel
I have used Northwind Database and customers table to populate gridview.
you can follow link to know how to install it on sql server 2008.

in one of my previous posts Export Gridview To Excel, i described how to export gridview containing controls like linkbutton, checkbox,dropdown etc to excel. I'll be using this code further to export selected rows.

Set DataKeyNames property of gridview to CustomerID.

HTML MARKUP
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
              DataSourceID="sqlDataSourceGridView" 
              DataKeyNames="CustomerID" 
              AutoGenerateColumns="False"
              onpageindexchanging="GridView1_PageIndexChanging" 
              onrowdatabound="GridView1_RowDataBound" >
<Columns>
<asp:TemplateField>
     <ItemTemplate>
          <asp:CheckBox ID="chkSelect" runat="server" />
     </ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Customer ID">
     <ItemTemplate>
          <asp:LinkButton ID="lButton" runat="server" 
                          Text='<%#Eval("CustomerID") %>' 
                          PostBackUrl="~/Default.aspx" >
          </asp:LinkButton>
     </ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CompanyName" HeaderText="Company">
</asp:BoundField>
<asp:BoundField DataField="ContactName" HeaderText="Name">
</asp:BoundField>
<asp:BoundField DataField="City" HeaderText="city">
</asp:BoundField>
<asp:BoundField DataField="Country" HeaderText="Country" 
&lt;/asp:BoundField>
</Columns>
</asp:GridView>
       
<asp:SqlDataSource ID="sqlDataSourceGridView" runat="server" 
ConnectionString="<%$ ConnectionStrings:northWindConnectionString %>" 
SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], 
               [City], [Country] FROM [Customers]">
</asp:SqlDataSource>

<asp:Button ID="btnExportToExcel" runat="server" 
            Text="Export To Excel" 
            onclick="btnExportToExcel_Click"/>


We need to write a method to find checked rows and maintane their state across postbacks or across gridview paging.

This method stores to customerID of selected row in viewstate using arraylist.

C#
private void FindCheckedRows()
    {
        ArrayList checkedRowsList;
        if (ViewState["checkedRowsList"] != null)
        {
            checkedRowsList = (ArrayList)ViewState["checkedRowsList"];
        }
        else
        {
            checkedRowsList = new ArrayList();
        }

        foreach (GridViewRow gvRow in GridView1.Rows)
        {
            if (gvRow.RowType == DataControlRowType.DataRow)
            {
                string rowIndex = 

Convert.ToString(GridView1.DataKeys[gvRow.RowIndex]["CustomerID"]);
                //int rowIndex = Convert.ToInt32(gvRow.RowIndex) + 

Convert.ToInt32(GridView1.PageIndex);
                CheckBox chkSelect = 

(CheckBox)gvRow.FindControl("chkSelect");
                if ((chkSelect.Checked) && 

(!checkedRowsList.Contains(rowIndex)))
                {
                    checkedRowsList.Add(rowIndex);
                }
                else if ((!chkSelect.Checked) && 

(checkedRowsList.Contains(rowIndex)))
                {
                    checkedRowsList.Remove(rowIndex);
                }
            }

        }
        ViewState["checkedRowsList"] = checkedRowsList;
    }

VB.NET
Private Sub FindCheckedRows()
 Dim checkedRowsList As ArrayList
 If ViewState("checkedRowsList") IsNot Nothing Then
  checkedRowsList = 

DirectCast(ViewState("checkedRowsList"), ArrayList)
 Else
  checkedRowsList = New ArrayList()
 End If

 For Each gvRow As GridViewRow In GridView1.Rows
  If gvRow.RowType = DataControlRowType.DataRow Then
   Dim rowIndex As String = 

Convert.ToString(GridView1.DataKeys(gvRow.RowIndex)("CustomerID"))
   'int rowIndex = Convert.ToInt32(gvRow.RowIndex) 

+ Convert.ToInt32(GridView1.PageIndex);
   Dim chkSelect As CheckBox = 

DirectCast(gvRow.FindControl("chkSelect"), CheckBox)
   If (chkSelect.Checked) AndAlso (Not 

checkedRowsList.Contains(rowIndex)) Then
    checkedRowsList.Add(rowIndex)
   ElseIf (Not chkSelect.Checked) AndAlso 

(checkedRowsList.Contains(rowIndex)) Then
    checkedRowsList.Remove(rowIndex)
   End If

  End If
 Next
 ViewState("checkedRowsList") = checkedRowsList
End Sub


Call this method whenever gridview pageindex changes.

protected void GridView1_PageIndexChanging(object sender, 

GridViewPageEventArgs e)
    {
        FindCheckedRows();
    }


Find the checkbox state and implement it whenever gridview is refreshed while paging.

To implement this write code in RowDataBound event of gridview.

C#
protected void GridView1_RowDataBound(object sender, 

GridViewRowEventArgs e)
    {
        if (ViewState["checkedRowsList"] != null)
        {
            ArrayList checkedRowsList = 

(ArrayList)ViewState["checkedRowsList"];
            GridViewRow gvRow = e.Row;
            if (gvRow.RowType == DataControlRowType.DataRow)
            {
                CheckBox chkSelect = 

(CheckBox)gvRow.FindControl("chkSelect");
                string rowIndex = 

Convert.ToString(GridView1.DataKeys[gvRow.RowIndex]["CustomerID"]);
                //int rowIndex = Convert.ToInt32(gvRow.RowIndex) + 

Convert.ToInt32(GridView1.PageIndex);
                if(checkedRowsList.Contains(rowIndex))
                {
                    chkSelect.Checked = true;
                }


            }
        }

        
    }

VB.NET
Protected Sub GridView1_RowDataBound(sender As Object, e As 

GridViewRowEventArgs)
 If ViewState("checkedRowsList") IsNot Nothing Then
  Dim checkedRowsList As ArrayList = 

DirectCast(ViewState("checkedRowsList"), ArrayList)
  Dim gvRow As GridViewRow = e.Row
  If gvRow.RowType = DataControlRowType.DataRow Then
   Dim chkSelect As CheckBox = 

DirectCast(gvRow.FindControl("chkSelect"), CheckBox)
   Dim rowIndex As String = 

Convert.ToString(GridView1.DataKeys(gvRow.RowIndex)("CustomerID"))
   'int rowIndex = Convert.ToInt32(gvRow.RowIndex) 

+ Convert.ToInt32(GridView1.PageIndex);
   If checkedRowsList.Contains(rowIndex) Then
    chkSelect.Checked = True


   End If
  End If
 End If


End Sub


To export these selected rows to excel write following code in Click event of export button.

C#
protected void btnExportToExcel_Click(object sender, EventArgs e)
    {
        FindCheckedRows();
        GridView1.ShowHeader = true;
        GridView1.GridLines = GridLines.Both;
        GridView1.AllowPaging = false;
        GridView1.DataBind();
        GridView1.HeaderRow.Cells.RemoveAt(0);
        if (ViewState["checkedRowsList"] != null)
        {
            ArrayList checkedRowsList = 

(ArrayList)ViewState["checkedRowsList"];
            foreach (GridViewRow gvRow in GridView1.Rows)
            {
                gvRow.Visible = false;
                if (gvRow.RowType == DataControlRowType.DataRow)
                {
                    string rowIndex = 

Convert.ToString(GridView1.DataKeys[gvRow.RowIndex]["CustomerID"]);
                    if(checkedRowsList.Contains(rowIndex))
                    {
                        gvRow.Visible = true;
                        gvRow.Cells[0].Visible = false;
                        
                    }
                }
            }
        }

        ChangeControlsToValue(GridView1);
        Response.ClearContent();

        Response.AddHeader("content-disposition", "attachment; 

filename=GridViewToExcel.xls");

        Response.ContentType = "application/excel";

        StringWriter sWriter = new StringWriter();

        HtmlTextWriter hTextWriter = new HtmlTextWriter(sWriter);

        HtmlForm hForm = new HtmlForm();

        GridView1.Parent.Controls.Add(hForm);

        hForm.Attributes["runat"] = "server";

        hForm.Controls.Add(GridView1);

        hForm.RenderControl(hTextWriter);

        Response.Write(sWriter.ToString());

        Response.End();
    }

VB.NET
Protected Sub btnExportToExcel_Click(sender As Object, e As EventArgs)
 FindCheckedRows()
 GridView1.ShowHeader = True
 GridView1.GridLines = GridLines.Both
 GridView1.AllowPaging = False
 GridView1.DataBind()
 GridView1.HeaderRow.Cells.RemoveAt(0)
 If ViewState("checkedRowsList") IsNot Nothing Then
  Dim checkedRowsList As ArrayList = 

DirectCast(ViewState("checkedRowsList"), ArrayList)
  For Each gvRow As GridViewRow In GridView1.Rows
   gvRow.Visible = False
   If gvRow.RowType = DataControlRowType.DataRow 

Then
    Dim rowIndex As String = 

Convert.ToString(GridView1.DataKeys(gvRow.RowIndex)("CustomerID"))
    If checkedRowsList.Contains(rowIndex) 

Then
     gvRow.Visible = True

     gvRow.Cells(0).Visible = False
    End If
   End If
  Next
 End If

 ChangeControlsToValue(GridView1)
 Response.ClearContent()

 Response.AddHeader("content-disposition", "attachment; 

filename=GridViewToExcel.xls")

 Response.ContentType = "application/excel"

 Dim sWriter As New StringWriter()

 Dim hTextWriter As New HtmlTextWriter(sWriter)

 Dim hForm As New HtmlForm()

 GridView1.Parent.Controls.Add(hForm)

 hForm.Attributes("runat") = "server"

 hForm.Controls.Add(GridView1)

 hForm.RenderControl(hTextWriter)

 Response.Write(sWriter.ToString())

 Response.[End]()
End Sub




This is how exported rows will look like in excel.


Download Sample Code


Find More Articles