2

DataBinder.Eval Container.DataItem Performance Asp.Net

DataBinder.Eval Container.DataItem Performance
DataBinder.Eval Container.DataItem Method Performance In Asp.Net.

Using DataBinder.Eval method Slow down the performance of Asp.Net website or application noticeably.

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

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

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

Delete Duplicate Records In Sql
Remove or Delete duplicate records or rows from ms sql server database table.

In this post i am going to describe different methods of deleting duplicate records or rows from sql server database table.

I am using Employees table with FirstName and Department columns.







Remove Duplicate Records 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.


5

jQuery Fixed Header Scrollable GridView

Jquery fixed header scrollable gridview in asp.net
Fixed Header Scrollable Gridview Using jQuery in ASP.NET.

In this example im going to describe how to create fixed header scrollable gridview using jquery.

I have used northwind database to populate gridview and jquery fixed header plugin.



Read Scrollable GridView With Fixed Headers Using CSS if you want to create scrollable fixed header gridview without using jQuery or JavaScript.

First of all add jquery library and fixed header scrollable gridview jquery plugin in project and add reference to it between <head></head> section of HTML source of aspx page.

<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>

Now 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.

have fun.


Download Sample Code



0

Export Selected GridView Rows To Excel

Export Selected GridView Rows to excel
Export Selected GridView Rows To Excel in asp.net 2.0,3.5,4.0 using C# and VB.NET.

In this post i am going to explain how to export selected gridview rows to ms excel in asp.net.

I have used northwind database and customers table to populate gridview.



read how to install northwind database for northwind database installation in 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.



First of all 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.

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"/>


Now 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# CODE
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 CODE
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();
    }


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

for this to implement we need to write code in RowDataBound event of gridview.

C# CODE
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 CODE
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


Now to export these selected rows to excel write below mentioned code in Click event of export button.

C# CODE
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 CODE
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




Popular Posts

Find More Articles