5

Change Mode Of DetailsView FormView From Default Mode Insert

Change Mode Of DetailsView FormView From Default Mode set to Insert If you have a DetailsView or FormView on your aspx page and set it's Default mode to Insert than after record insertion it's mode can be changed to default mode by writing following code in ItemInserted Event

protected void DetailsView1_ItemInserted
(object sender, DetailsViewInsertedEventArgs e)
{
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
}


But this code doesn't work , reason being DefaultMode is applied after the call to change the mode , to get it working or to get the mode changed, u need to write code like this
protected void DetailsView1_ItemInserted
(object sender, DetailsViewInsertedEventArgs e)
{
e.KeepInInsertMode = true;
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);

}


Now mode will be changed , similarly you can change the mode to edit.

16

Hide GridView Columns In ASP.NET

This example shows how to Hide GridView Columns in normal mode in asp.net and set them to visible when gridview is in edit mode. I am hiding the ID column when gridview loads and setting this column to visible when user clicks on the edit link button.

For this i am using ObjectDataSource to populate the grid and hiding columns in RowDataBound Event.

Hide GridView Columns In ASP.NET


<asp:GridView ID="GridView1" runat="server"
              AutoGenerateColumns="False"
              DataSourceID="ObjectDataSource1"
              OnRowDataBound="GridView1_RowDataBound"
              OnRowEditing="GridView1_RowEditing">
<Columns>
<asp:CommandField ShowEditButton="true"/>
 
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#Eval("ID")%>'/>
</ItemTemplate>
<EditItemTemplate >
<asp:TextBox ID="txtID" Visible="true" runat="server"
             Text='<%#Eval("ID")%>'/>
</EditItemTemplate>
</asp:TemplateField>
 
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#Eval("Name")%>'/>
</ItemTemplate>
<EditItemTemplate >
<asp:TextBox ID="txtName" Visible="true" runat="server"
             Text='<%#Eval("Name")%>'/>
</EditItemTemplate>
</asp:TemplateField>
 
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" 
           Text='<%#Eval("Location")%>'/>
</ItemTemplate>
<EditItemTemplate >
<asp:TextBox ID="txtLocation" Visible="true" runat="server"
             Text='<%#Eval("Location")%>'/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
 
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
                      InsertMethod="Insert"
                      OldValuesParameterFormatString="original_{0}"
                      SelectMethod="GetData"
                      TypeName="DataSet1TableAdapters.TestTableAdapter"
                      UpdateMethod="UpdateQuery">
<InsertParameters>
<asp:Parameter Name="ID" Type="Decimal" />
<asp:Parameter Name="Name" Type="String" />
<asp:Parameter Name="Location" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="Name" Type="String" />
<asp:Parameter Name="Location" Type="String" />
<asp:Parameter Name="ID" Type="Decimal" />
</UpdateParameters>
</asp:ObjectDataSource>


We need to write following code to hide columns in RowDataBound event

C# CODE
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //Check whether gridview is in edit mode or nor 
        if (GridView1.EditIndex >= 0)
        { return; }
        //Check row state of gridview whether it is data row or not
        if ((e.Row.RowState == DataControlRowState.Normal
        || e.Row.RowState == DataControlRowState.Alternate)
        && (e.Row.RowType == DataControlRowType.DataRow
        || e.Row.RowType == DataControlRowType.Header))
        {
            //Now set the visibility of cell we want to hide to false 
            e.Row.Cells[1].Visible = false;
        }
    }

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        GridView1.DataBind();
    }

VB.NET
Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs)
 'Check whether gridview is in edit mode or nor 
 If GridView1.EditIndex >= 0 Then
  Return
 End If
 'Check row state of gridview whether it is data row or not
 If (e.Row.RowState = DataControlRowState.Normal OrElse e.Row.RowState = DataControlRowState.Alternate) AndAlso (e.Row.RowType = DataControlRowType.DataRow OrElse e.Row.RowType = DataControlRowType.Header) Then
  'Now set the visibility of cell we want to hide to false 
  e.Row.Cells(1).Visible = False
 End If
End Sub

Protected Sub GridView1_RowEditing(sender As Object, e As GridViewEditEventArgs)
 GridView1.EditIndex = e.NewEditIndex
 GridView1.DataBind()
End Sub


Download Sample Code


93

Export GridView To Pdf-ASP.NET

In this example i'm explaining how to Export GridView To PDF Using iTextsharp In Asp.Net 2.0,3.5,4.0 Using C# VB.NET i am exporting Gridview populated with SqlDataSource to Pdf using iTextSharp in click event of Button

I have populated gridview with SqlDataSource and placed one button on the page to create pdf from gridview.






   1:  <asp:GridView ID="GridView1" runat="server" 
   2:                AutoGenerateColumns="False" 
   3:                DataSourceID="SqlDataSource1">
   4:  <Columns>
   5:  <asp:BoundField DataField="Name" HeaderText="Name"/>
   6:  <asp:BoundField DataField="Location" HeaderText="Location"/>
   7:  </Columns>
   8:  </asp:GridView>
   9:   
  10:  <asp:Button ID="btnExport" runat="server" 
  11:              OnClick="btnExport_Click" Text="Export to PDF" />
  12:              
  13:  <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
  14:  ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
  15:  SelectCommand="SELECT [Name], [Location] FROM [Test]">
  16:  </asp:SqlDataSource>

To use iTextSharp , we need to add these namspaces in the code behind and itextsharp.dll in Bin folder of Application
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using System.IO;
using System.Collections;
using System.Net;

Now in Click event of button i m creating a new HtmlForm and adding the gridview control to this form in code behind , than creating instance of StringWriter class and HtmlTextWriter to write strings and than rendernig these to form created earlier
protected void btnExport_Click
(object sender, EventArgs e)
{
HtmlForm form = new HtmlForm();
form.Controls.Add(GridView1);
StringWriter sw = new StringWriter();
HtmlTextWriter hTextWriter = new HtmlTextWriter(sw);
form.Controls[0].RenderControl(hTextWriter);
string html = sw.ToString();

In next lines of code i m creating a new Document in specified location and opening it for writing
Document Doc = new Document();

If u wanna save the pdf in application's root folder in server
than use Requesr.PhysicalApplicationPath

//PdfWriter.GetInstance
//(Doc, new FileStream(Request.PhysicalApplicationPath 
//+ "\\AmitJain.pdf", FileMode.Create));

And if u wanna save the PDF at users Desktop than use
Environment.GetFolderPath(Environment.SpecialFolder.Desktop

PdfWriter.GetInstance
(Doc, new FileStream(Environment.GetFolderPath
(Environment.SpecialFolder.Desktop)
+ "\\AmitJain.pdf", FileMode.Create));
Doc.Open();

Now i m adding a paragraph to this document to be used as
Header by creating a new chuck and adding it to paragraph

Chunk c = new Chunk
("Export GridView to PDF Using iTextSharp \n",
FontFactory.GetFont("Verdana", 15));
Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_CENTER;
p.Add(c);
Chunk chunk1 = new Chunk
("By Amit Jain, amit_jain_online@yahoo.com \n",
FontFactory.GetFont("Verdana", 8));
Paragraph p1 = new Paragraph();
p1.Alignment = Element.ALIGN_RIGHT;
p1.Add(chunk1);

Doc.Add(p);
Doc.Add(p1);

Now i m reading the html string created above through 
xmlTextReader and htmlParser to parse html elements

System.Xml.XmlTextReader xmlReader =
new System.Xml.XmlTextReader(new StringReader(html));
HtmlParser.Parse(Doc, xmlReader);

Doc.Close();
string Path = Environment.GetFolderPath
(Environment.SpecialFolder.Desktop)
+ "\\AmitJain.pdf";


ShowPdf(Path);


The complete code looks like this

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;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using System.IO;
using System.Collections;
using System.Net;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnExport_Click(object sender, EventArgs e)
{
HtmlForm form = new HtmlForm();
form.Controls.Add(GridView1);
StringWriter sw = new StringWriter();
HtmlTextWriter hTextWriter = new HtmlTextWriter(sw);
form.Controls[0].RenderControl(hTextWriter);
string html = sw.ToString();
Document Doc = new Document();

//PdfWriter.GetInstance
//(Doc, new FileStream(Request.PhysicalApplicationPath 
//+ "\\AmitJain.pdf", FileMode.Create));

PdfWriter.GetInstance
(Doc, new FileStream(Environment.GetFolderPath
(Environment.SpecialFolder.Desktop)
+ "\\AmitJain.pdf", FileMode.Create));
Doc.Open();

Chunk c = new Chunk
("Export GridView to PDF Using iTextSharp \n",
FontFactory.GetFont("Verdana", 15));
Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_CENTER;
p.Add(c);
Chunk chunk1 = new Chunk
("By Amit Jain, amit_jain_online@yahoo.com \n",
FontFactory.GetFont("Verdana", 8));
Paragraph p1 = new Paragraph();
p1.Alignment = Element.ALIGN_RIGHT;
p1.Add(chunk1);

Doc.Add(p);
Doc.Add(p1);

System.Xml.XmlTextReader xmlReader =
new System.Xml.XmlTextReader(new StringReader(html));
HtmlParser.Parse(Doc, xmlReader);

Doc.Close();
string Path = Environment.GetFolderPath
(Environment.SpecialFolder.Desktop)
+ "\\AmitJain.pdf";


ShowPdf(Path);


}

private void ShowPdf(string strS)
{
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader
("Content-Disposition","attachment; filename=" + strS);
Response.TransmitFile(strS);
Response.End();
//Response.WriteFile(strS);
Response.Flush();
Response.Clear();

}

}

This code doesn't work if paging is enabled in GridView and the other this is cloumns become of variable width in PDF document , to fix these issues read my next Post Exporting Paging enabled GridView to PDF using iTextSharp

Download the sample Code


Other Gridview articles you would like to read:

1. Populating dropdown based on the selection of first drop down in DetailsView using FindControl and ItemTemplate

2. Pouplating Multiple DetailsView based on single GridView using DataKeyNames in ASP.NET

3. Merging GridView Headers to have multiple Headers in GridView using C# ASP.NET

14

Find IP Address In ASP.NET Behind Proxy

Find IP Address Behind Proxy Or Client Machine In ASP.NET, If you want to find the IP address of visitors to your aspx page or application or wanna retrieve IP for other users than u need to write this code

Using this code we can find IP address of visitor even if visitor is behind any proxy

public string IpAddress()
{
string strIpAddress;
strIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (strIpAddress == null)
{
strIpAddress = Request.ServerVariables["REMOTE_ADDR"];
}
return strIpAddress;
}

To find IP address of a machine behind LAN you can use this code
string strHostName = System.Net.Dns.GetHostName();
string clientIPAddress = System.Net.Dns.GetHostAddresses
(strHostName).GetValue(1).ToString();


10

OpenFileDialog In WinForms Windows Forms Application C# VB.NET

OpenFileDialog In WinForms Windows Forms Application Using C# And VB.NET

In this example i m creating a Open file dialog box to browse and select a file to open in .NET windows applications using C# and winforms




Start a new Windows Application project and drag a button, double click on the button to generate it's click event

Now create a new openFileDialog

OpenFileDialog fDialog = new OpenFileDialog();

To set the title of window
fDialog.Title = "Open Image Files";

To apply filter, which only allows the files with the name or extension specified to be selected. in this example i m only using jpeg and GIF files
fDialog.Filter = "JPEG Files|*.jpeg|GIF Files|*.gif";

To set the Initial Directory property ,means which directory to show when the open file dialog windows opens
fDialog.InitialDirectory = @"C:\";

if the user has clicked the OK button after choosing a file,To display a MessageBox with the path of the file:
if(fDialog.ShowDialog() == DialogResult.OK)
{
MessageBox.Show(fDialog.FileName.ToString());
}


If you want to select multiple files ,set the Multiselect property to true and to return the name of the files use fDialog.FileNames instead of fDialog.FileName. This will return a string array with the name of the files.
Other properties which we can use are :
If a user types the name of a file but doesn't specify the extension you can set the AddExtension property to true:
fDialog.AddExtension = true;

if a user types the name of a file or path that does not exist we can give him an warning:
fDialog.CheckFileExists = true;
fDialog.CheckPathExists = true;


32

User Validation Authentication Using Session In ASP.NET

This post explains how to use User Validation Authentication Using Session In ASP.NET to validate users, Consider a scenario where you don't want to use membership class or Form Authentication techniques provided by .NET 2.0, in those situation this example might be helpful

In this example i m showing how to validate a user across different pages whether user is logged in or not using session variables in Global.asax through Session_Start event and Application_OnPostRequestHandlerExecute event which checks for the login validation which occurs when an asp.net event handler finish execution

For Forms Authentication, read this Forms Authentication with C# and managing folder lavel access with multiple web.config files in ASP.NET

Here is my login page, i've used hard coded values to login

<div style="text-align:left">
<table width="40%" style="text-align: center">
<tr><td style="width: 20%">
<asp:Label ID="lblUserName" runat="server" Text="Enter UserName:"/></td>
 
<td style="width: 20%">
<asp:TextBox ID="txtUserName" runat="server"/></td></tr>
 
<tr><td style="width: 20%">
<asp:Label ID="lblPassword" runat="server" Text="Enter Password:"/></td>
 
<td style="width: 20%" >
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"/></td>
</tr><tr>
 
<td colspan="2" align="right">
<asp:Button ID="btnLogin" runat="server" Text="Sign in" OnClick="btnLogin_Click"/>
</td></tr></table>
<asp:Label ID="Label1" runat="server" Text="Label"/><br />
</div>


After checking the username and password i m creating a new Session variable and setting the flag kindaa value in it , which is "Yes" in this example, this session value will be checked when ever user go to other pages and if it's null than user in not logged in

protected void btnLogin_Click(object sender, EventArgs e)
{
if (txtUserName.Text == "amit" && txtPassword.Text == "amit")
{
Session["Authenticate"] = "Yes";
Response.Redirect("Default2.aspx");
}
else
Label1.Text = " login failed";
}

In Global.asax, in Session_Start event i m assigning null value to the session variable created at the time of Login and than calling the method to check the login, same is in Application_OnPostRequestHandlerExecute event as well

void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Session["Authenticate"] = "";
CheckLogin();

}
void Application_OnPostRequestHandlerExecute()
{
CheckLogin();
}

void CheckLogin()
{
string Url = Request.RawUrl;
int count = Url.Length - 10 ;
string TestUrl = Url.Substring(count);
string SessionData = Session["Authenticate"].ToString();
if (SessionData == "" && TestUrl != "Login.aspx")
{
Response.Redirect("~/Login.aspx");
}
}


13

ASP.NET Search Records In GridView Footer And Highlight Results

Search Records In GridView Footer And Highlight Results using ajax in asp.net, In this example i am populating Gridview by creating Sqlconnection and SqlCommand.

I've put a textbox in FooterTemplate of gridview for text to search, and the search results are highlighted using regular expression, i m using AJAX for partial postback and update progress template to show search progress

   1:  <style type="text/css">
   2:  .highlight {text-decoration:none; font-weight:bold;
   3:  color:black; background:yellow;}
   4:  </style>
   5:  </head>
   6:  <body>
   7:  <form id="form1" runat="server">
   8:  <asp:ScriptManager ID="ScriptManager1" runat="server"/>
   9:  <asp:UpdatePanel ID="UpdatePanel1" runat="server">
  10:  <ContentTemplate>
  11:  <div>
  12:  <asp:GridView ID="grdSearch" runat="server" 
  13:                ShowFooter="True"
  14:                OnRowCommand="grdSearch_RowCommand" 
  15:                AutoGenerateColumns="False">
  16:   
  17:  <Columns>
  18:  <asp:TemplateField HeaderText="FirstName">
  19:  <ItemTemplate>
  20:  <asp:Label ID="lblFIrstName" runat="server"
  21:             Text='<%# Highlight(Eval("FirstName").ToString()) %>'/>
  22:  </ItemTemplate>
  23:   
  24:  <FooterTemplate>
  25:  <asp:TextBox ID="txtSearch" runat="server"/>
  26:  <asp:Button ID="btnSearch" CommandName="Search" 
  27:              runat="server" Text="Search"/>
  28:  </FooterTemplate>
  29:  </asp:TemplateField>
  30:   
  31:  <asp:BoundField DataField="LastName" HeaderText="LastName"/>
  32:  </Columns>
  33:  </asp:GridView>
  34:  </div>
  35:  </ContentTemplate>
  36:  </asp:UpdatePanel>
  37:   
  38:  <asp:UpdateProgress ID="UpdateProgress1" runat="server">
  39:  <ProgressTemplate>
  40:  <br />
  41:  <img src="Images/ajax.gif" alt="Searchig"/>
  42:  </ProgressTemplate>
  43:  </asp:UpdateProgress>
  44:  </form>
  45:  </body>

Populate GridView by making SqlConnection and SqlCommand to fetch data from database, then bind the data to Grid in Page_Load event.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }

    private DataTable GetRecords()
    {
        SqlConnection conn = new SqlConnection(strConnection);
        conn.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "Select * from Employees";
        SqlDataAdapter dAdapter = new SqlDataAdapter();
        dAdapter.SelectCommand = cmd;
        DataSet objDs = new DataSet();
        dAdapter.Fill(objDs);
        return objDs.Tables[0];

    }

    private void BindGrid()
    {
        DataTable dt = GetRecords();
        if (dt.Rows.Count > 0)
        {
            grdSearch.DataSource = dt;
            grdSearch.DataBind();
        }
    }

Now i've written a method to search GridView rows or records for the text entered in footer textbox by user

private void SearchText(string strSearchText)
    {
        DataTable dt = GetRecords();
        DataView dv = new DataView(dt);
        string SearchExpression = null;
        if (!String.IsNullOrEmpty(strSearchText))
        {
            SearchExpression =
            string.Format("{0} '%{1}%'",
            grdSearch.SortExpression, strSearchText);

        }
        dv.RowFilter = "FirstName like" + SearchExpression;
        grdSearch.DataSource = dv;
        grdSearch.DataBind();
    }

Next step is to check the command in RowCommand event of gridview,if it is what u've defined in while creating the button in footer of grid by assigning the commandname property, if yes than get the text entered by user in textbox placed in footer of gridview by using findcontrol method and pass this text to the search method written earlier by making a call to that method

protected void grdSearch_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        System.Threading.Thread.Sleep(2000);
        if (e.CommandName == "Search")
        {
            TextBox txtGrid =
            (TextBox)grdSearch.FooterRow.FindControl("txtSearch");
            SearchText(txtGrid.Text);
        }
    }

To highlight search results use regular expression and replace the the words found with highlighted in yellow color

public string Highlight(string InputTxt)
    {
        GridViewRow gvr = grdSearch.FooterRow;
        if (gvr != null)
        {
            TextBox txtExample =
            (TextBox)grdSearch.FooterRow.FindControl("txtSearch");

            if (txtExample.Text != null)
            {
                string strSearch = txtExample.Text;
                Regex RegExp =
                new Regex(strSearch.Replace(" ", "|").Trim(),
                RegexOptions.IgnoreCase);
                return
                RegExp.Replace(InputTxt, new MatchEvaluator(ReplaceKeyWords));
                RegExp = null;
            }
            else
                return InputTxt;
        }
        else
        {
            return InputTxt;
        }
    }

    public string ReplaceKeyWords(Match m)
    {
        return "" + m.Value + "";
    }


3

Register Dlls Assembly Custom User Controls Ascx In ASP.NET

This post explains how to Register Assembly, Custom Controls, Dlls And User Control Ascx In Asp.Net 2.0,3.5,4.0. To register these we need to add reference in page directive of aspx html source

<%@ Register TagPrefix="MyControl" TagName="HeaderControl"
Src="Header.ascx" %>
<%@ Register TagPrefix="MyControl" TagName="footerControl"
Src="Footer.ascx" %>
<%@ Register TagPrefix="MyAssembly" Assembly="Myassembly" %>


Or like this

<%@ Register Assembly="AjaxControlToolkit"
             Namespace="AjaxControlToolkit"
             TagPrefix="ajaxToolkit" %>

But using this we need to register our ascx control or dll in every page we want to use , if we need to use control or dll in more than one page or in several pages than we can register controls and dlls in web.config file

<configuration>
    <system.web>
      <pages>
        <controls>
          <add tagPrefix="MyControl" src="~/Header.ascx" 
                                     tagName="HeaderControl"/>
 
          <add tagPrefix="ControlName" src="~/Footer.ascx" 
                                       tagName="FooterControl"/>
 
          <add tagPrefix="MyAssembly" assembly="MyAssembly"/>
 
          <add tagPrefix="asp" namespace="System.Web.UI" 
               assembly="System.Web.Extensions, 
               Version=3.5.0.0, Culture=neutral,
               PublicKeyToken=31BF3856AD364E35"/>
        </controls>
      </pages>
    </system.web>
</configuration>


8

ASP.NET TextBox Submit Form On Enter Key DefaultButton

TextBox Submit Form On Enter Key press Using DefaultButton In Asp.Net 2.0,3.5,4.0, We can set Defaultbutton property either in Form or in panel Whenever we want user to submit a form by pressing enter key after filing out some textboxes on the aspx page, though we provide the button to submit the form but user prefer to press enter and expect the form to be submitted

But in ASP.NET when user press enter key the page gets post back but the button event doesn't get fired hence whatever code u've written in the click event doesn't get executed and it just like refreshing the page , to handle this situation in ASP.NET 2.0 ,we need to set the Defaultbutton property which indicates which button events should get fired when user press enter key to submit the form.

<form id="form1" runat="server" defaultbutton="Button1">
<div>
<asp:TextBox ID="TextBox1" runat="server"/>
 
<asp:TextBox ID="txtTest" runat="server"/>
 
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit"/>
</div>
</form>
 
or if we use panel than
<asp:Panel ID="Panel1" runat="server" defaultbutton="Button1">


16

Search Records In GridView And Highlight Results Asp.Net Ajax

In this example i am Explaining how to Search Records In GridView And Highlight Results Using Ajax In Asp.Net 2.0,3.5,4.0 based on text entered in textbox.



Add following CSS style in head section of page.

HTML SOURCE
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
    
Enter first name to search:
 
<asp:TextBox ID="txtSearch" runat="server" AutoPostBack="True"
             OnTextChanged="txtSearch_TextChanged"/>
 
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="grdSearch" runat="server"
              AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="FirstName">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" 
           Text='<%# Highlight(Eval("FirstName").ToString()) %>'/>
</ItemTemplate>
</asp:TemplateField>
 
<asp:TemplateField HeaderText="LastName">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text='<%#(Eval("LastName")) %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" Text='<%#(Eval("Location")) %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtSearch" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>

Write following code in code behind
C# CODE
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }
    private DataTable GetRecords()
    {
        SqlConnection conn = new SqlConnection(strConnection);
        conn.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "Select * from Employees";
        SqlDataAdapter dAdapter = new SqlDataAdapter();
        dAdapter.SelectCommand = cmd;
        DataSet objDs = new DataSet();
        dAdapter.Fill(objDs);
        return objDs.Tables[0];

    }
    private void BindGrid()
    {
        DataTable dt = GetRecords();
        if (dt.Rows.Count > 0)
        {
            grdSearch.DataSource = dt;
            grdSearch.DataBind();
        }
    }
    private void SearchText()
    {
        DataTable dt = GetRecords();
        DataView dv = new DataView(dt);
        string SearchExpression = null;
        if (!String.IsNullOrEmpty(txtSearch.Text))
        {
            SearchExpression = string.Format("{0} '%{1}%'",
            grdSearch.SortExpression, txtSearch.Text);

        }
        dv.RowFilter = "FirstName like" + SearchExpression;
        grdSearch.DataSource = dv;
        grdSearch.DataBind();

    }
    public string Highlight(string InputTxt)
    {
        string Search_Str = txtSearch.Text.ToString();
        // Setup the regular expression and add the Or operator.
        Regex RegExp = new Regex(Search_Str.Replace(" ", "|").Trim(),
        RegexOptions.IgnoreCase);

        // Highlight keywords by calling the 
        //delegate each time a keyword is found.
        return RegExp.Replace(InputTxt,
        new MatchEvaluator(ReplaceKeyWords));

        // Set the RegExp to null.
        RegExp = null;

    }

    public string ReplaceKeyWords(Match m)
    {

        return "" + m.Value + "";

    }

    protected void txtSearch_TextChanged(object sender, EventArgs e)
    {
        SearchText();
    }

VB.NET
Protected Sub Page_Load(sender As Object, e As EventArgs)
 If Not IsPostBack Then
  BindGrid()
 End If
End Sub
Private Function GetRecords() As DataTable
 Dim conn As New SqlConnection(strConnection)
 conn.Open()
 Dim cmd As New SqlCommand()
 cmd.Connection = conn
 cmd.CommandType = CommandType.Text
 cmd.CommandText = "Select * from Employees"
 Dim dAdapter As New SqlDataAdapter()
 dAdapter.SelectCommand = cmd
 Dim objDs As New DataSet()
 dAdapter.Fill(objDs)
 Return objDs.Tables(0)

End Function
Private Sub BindGrid()
 Dim dt As DataTable = GetRecords()
 If dt.Rows.Count > 0 Then
  grdSearch.DataSource = dt
  grdSearch.DataBind()
 End If
End Sub
Private Sub SearchText()
 Dim dt As DataTable = GetRecords()
 Dim dv As New DataView(dt)
 Dim SearchExpression As String = Nothing
 If Not [String].IsNullOrEmpty(txtSearch.Text) Then

  SearchExpression = String.Format("{0} '%{1}%'", grdSearch.SortExpression, txtSearch.Text)
 End If
 dv.RowFilter = "FirstName like" & SearchExpression
 grdSearch.DataSource = dv
 grdSearch.DataBind()

End Sub
Public Function Highlight(InputTxt As String) As String
 Dim Search_Str As String = txtSearch.Text.ToString()
 ' Setup the regular expression and add the Or operator.
 Dim RegExp As New Regex(Search_Str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase)

 ' Highlight keywords by calling the 
 'delegate each time a keyword is found.
 Return RegExp.Replace(InputTxt, New MatchEvaluator(AddressOf ReplaceKeyWords))

 ' Set the RegExp to null.
 RegExp = Nothing

End Function

Public Function ReplaceKeyWords(m As Match) As String

 Return "" & Convert.ToString(m.Value) & ""

End Function

Protected Sub txtSearch_TextChanged(sender As Object, e As EventArgs)
 SearchText()
End Sub

12

Detect Browser Refresh Avoid Events Fire In ASP.NET

Detect Browser Refresh In Asp.Net 2.0,3.5,4.0 To Avoid Events Getting Fired Or Event Firing,If you are inserting some data in database in Click event of button, After click if user refresh the page than click event gets fired again resulting data insertion to database again.

To stop event fire on browser refresh we need to write bit of code.

In this example i've put a Label and a Button on the page, on click the label Text becomes Hello and when i refresh the page label's text again becomes Hello

HTML SOURCE
   1:  <asp:Label ID="Label1" runat="server" Text=""/>
   2:   
   3:  <asp:Button ID="Button1" runat="server" 
   4:              OnClick="Button1_Click" Text="Button"/>


In Page_Load event i m creating a Session Variable and assigning System date and time to it , and in Page_Prerender event i am creating a Viewstate variable and assigning Session variable's value to it.

Than in button's click event i am checking the values of Session variable and Viewstate variable if they both are equal than page is not refreshed otherwise it has been refreshed

C# CODE
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["CheckRefresh"] =
            Server.UrlDecode(System.DateTime.Now.ToString());
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (Session["CheckRefresh"].ToString() == ViewState["CheckRefresh"].ToString())
        {
            Label1.Text = "Hello";
            Session["CheckRefresh"] =
            Server.UrlDecode(System.DateTime.Now.ToString());
        }
        else
        {
            Label1.Text = "Page Refreshed";
        }
    }

    protected void Page_PreRender(object sender, EventArgs e)
    {
        ViewState["CheckRefresh"] = Session["CheckRefresh"];
    }

VB.NET
Protected Sub Page_Load(sender As Object, e As EventArgs)
 If Not IsPostBack Then
  Session("CheckRefresh") = Server.UrlDecode(System.DateTime.Now.ToString())
 End If
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs)
 If Session("CheckRefresh").ToString() = ViewState("CheckRefresh").ToString() Then
  Label1.Text = "Hello"
  Session("CheckRefresh") = Server.UrlDecode(System.DateTime.Now.ToString())
 Else
  Label1.Text = "Page Refreshed"
 End If
End Sub

Protected Sub Page_PreRender(sender As Object, e As EventArgs)
 ViewState("CheckRefresh") = Session("CheckRefresh")
End Sub


16

Merge Merging GridView Header Columns Multiple Headers ASP.NET

In this example i m explaining how to Merging Or Merge GridView Header Columns Or Combine Multiple Headers using C# VB.NET In ASP.NET 2.0,3.5,4.0.

For this you need to create GridView header row in RowCreated Event

<asp:GridView ID="grvMergeHeader" runat="server" 
              AutoGenerateColumns="False" 
              DataSourceID="SqlDataSource1" 
              OnRowCreated="grvMergeHeader_RowCreated">
<Columns>
<asp:BoundField DataField="DepartMentID" HeaderText="DepartMentID"/>
<asp:BoundField DataField="DepartMent" HeaderText="DepartMent"/>
<asp:BoundField DataField="Name" HeaderText="Name"/>
<asp:BoundField DataField="Location" HeaderText="Location"/>
</Columns>
</asp:GridView>
 
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [DepartMentID], [DepartMent], [Name], 
              [Location] FROM [Employee]">
</asp:SqlDataSource>

Now In Code behind, in RowCreated Event of grid view i m creating a new gridview row of header type and than in this row i m adding 2 cells

C# CODE
protected void grvMergeHeader_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            GridView HeaderGrid = (GridView)sender;
            GridViewRow HeaderGridRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
            TableCell HeaderCell = new TableCell();
            HeaderCell.Text = "Department";
            HeaderCell.ColumnSpan = 2;
            HeaderGridRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "Employee";
            HeaderCell.ColumnSpan = 2;
            HeaderGridRow.Cells.Add(HeaderCell);

            grvMergeHeader.Controls[0].Controls.AddAt(0, HeaderGridRow);

        }
    }

VB.NET
Protected Sub grvMergeHeader_RowCreated(sender As Object, e As GridViewRowEventArgs)
 If e.Row.RowType = DataControlRowType.Header Then
  Dim HeaderGrid As GridView = DirectCast(sender, GridView)
  Dim HeaderGridRow As New GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert)
  Dim HeaderCell As New TableCell()
  HeaderCell.Text = "Department"
  HeaderCell.ColumnSpan = 2
  HeaderGridRow.Cells.Add(HeaderCell)

  HeaderCell = New TableCell()
  HeaderCell.Text = "Employee"
  HeaderCell.ColumnSpan = 2
  HeaderGridRow.Cells.Add(HeaderCell)


  grvMergeHeader.Controls(0).Controls.AddAt(0, HeaderGridRow)
 End If
End Sub


Download Sample Code


18

Mozilla Firefox JavaScript Window.Close() Not Working

Mozilla firefox JavaScript window.close() not working, If you are developing a ASP.NET application and have written javascript to close browser window using window.close, this won't work in Mozilla firefox

The reason for this is, This method is only allowed to be called for windows that were opened by a script using the window.open method.

If the window was not opened by a script, the following error appears in the JavaScript Console: Scripts may not close windows that were not opened by script.

https://developer.mozilla.org/En/DOM:window.close

To get around this problem we will have to fool the firefox to thin it window is opened by window.open

We can use this code

<script>

function closeMe()
{
var win=window.open("","_self");
win.close();
}
</script>

<html>
<body>
<form>
<input type="button" name="Close"
onclick="closeMe()" />
</form>
</body>
</html>
We can also write script like this
function winClose()
{
window.top.opener=null;
window.close();
}

or

function closeWindow()
{
window.open('','_parent',''); 
window.close();
}



if it doesn't works

please set your firefox browser:

1.input "about:config " to your firefox address bar and enter;

2.make sure your "dom.allow_scripts_to_close_windows" is true



Related Posts:

1. Disable copy paste cut and right click in textbox on aspx page using javascript

2. Highlight gridview row on mouse over using javascript in asp.net and C# c-sharp

3. Disable browser back button functionality using javascript in ASP.NET

16

Detecting Session Timeout And Redirect To Login Page In ASP.NET

This is example of Detecting Session Timeout and Redirect to Login Page in ASP.NET, session timeout occurs when user is idle for the time specified as in web.config file.

For this i've set time out value in web.config to 1 minute.

1st Method
In web.config file, set the sessionstate mode to inproc and authentication mode to Forms
<system.web>
<compilation debug="true"/>
<authentication mode="Forms"/>
<sessionState mode="InProc" cookieless="false" timeout="1">
</sessionState>
</system.web> 


I've created three pages in this example , one is login page , when session expires , i redirect to this page , one is navigation page where i'll check if session is valid or not , if it is valid than only user will see this page other wise he gets redirected to login page.

Add Global.asax class file in root of your application or website.
This method works only if Global.asax is present in application.


Write below mentioned code in Page_Init event of the page where we want to check for session timeout.

we can also put this code in in a class and inherit all pages of application from this class acting as base class for all pages to check for session timeout.

C# CODE
protected void Page_Init(object sender, EventArgs e)
    {
        if (Context.Session != null)
        {
            if (Session.IsNewSession)
            {
                HttpCookie newSessionIdCookie = Request.Cookies["ASP.NET_SessionId"];
                if (newSessionIdCookie != null)
                {
                    string newSessionIdCookieValue = newSessionIdCookie.Value;
                    if (newSessionIdCookieValue != string.Empty)
                    {
                        // This means Session was timed Out and New Session was started
                        Response.Redirect("Login.aspx");
                    }
                }
            }
        }
    }

VB.NET
Protected Sub Page_Init(sender As Object, e As EventArgs)
 If Context.Session IsNot Nothing Then
  If Session.IsNewSession Then
   Dim newSessionIdCookie As HttpCookie = Request.Cookies("ASP.NET_SessionId")
   If newSessionIdCookie IsNot Nothing Then
    Dim newSessionIdCookieValue As String = newSessionIdCookie.Value
    If newSessionIdCookieValue <> String.Empty Then
     ' This means Session was timed Out and New Session was started
     Response.Redirect("Login.aspx")
    End If
   End If
  End If
 End If
End Sub


2nd Method.
Code for Default.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnSessionStart"
runat="server"
OnClick="btnSessionStart_Click"
Text="Start Session" /><br />
<br />
<br />
<asp:Button ID="btnCheck"
runat="server"
OnClick="btnCheck_Click"
Text="Check Session ID" />
<br />
<asp:TextBox ID="txtSession"
runat="server"
Width="266px">
</asp:TextBox><br />
<br />
<asp:Button ID="btnGO"
runat="server"
OnClick="btnGO_Click"
Text="Go to Other Page" />
<br />
<br />
</div>
</form>
</body>
</html>

And the code behind for this page is like
protected void btnSessionStart_Click
(object sender, EventArgs e)
{
Guid Session_id = Guid.NewGuid();
Session["SessionID"]
= Session_id.ToString();

}
protected void btnCheck_Click
(object sender, EventArgs e)
{
if (Session["SessionID"] != null)
txtSession.Text =
Session["SessionID"].ToString();
else
txtSession.Text =
"Session has expired";
}
protected void btnGO_Click
(object sender, EventArgs e)
{
Response.Redirect("Default2.aspx");
}

On the page where we want to check the session has timed out or not, we need to check it in the Page_Init event of the page , if session is not null than user will be able to go to the page other wise he will be redirected to login page.

In this page I've just put a button to go to home page
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnHome"
runat="server" OnClick="btnHome_Click"
Text="Home" /></div>
</form>
</body>
</html>

And the Code behind for this page is

protected void Page_Init(object sender, EventArgs e)
{
CheckSession();
}
protected void btnHome_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}

private void CheckSession()
{
if (Session["SessionID"] == null)
{
Response.Redirect("Login.aspx");
}

}

If we need to check this in all the pages of application than we can create a BaseClass and write the above mentioned code of CheckSession and Page_Init part and drive all ur pages from this class by typing BaseClassName in place of System.Web.UI.Page and it will check all pages for session timeout every time page is loaded


Find More Articles