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


13

Populate DetailsView From GridView Select DataKeyNames

Here i'm explaining how to Populate DetailsView From GridView In Asp.Net based on selection of a record in GridView using Multiple DataKeyNames

Populate multiple detailsview from gridview select
In this example GridView is populated from a table called Website using SqlDataSource.

I have defined multiple(3) comma separated DataKeyNames Property in GridView source.

These DataKeyNames properties will be used to fetch the record related to respective DataKey from 3 tables to populate 3 DetailsViews.

HTML SOURCE OF THE PAGE
   1:  <form id="form1" runat="server">
   2:  <div>
   3:  <asp:GridView ID="GridView1" runat="server" 
   4:                DataKeyNames="Record,ResponseID,Source_id"  
   5:                AutoGenerateColumns="False" 
   6:                DataSourceID="SqlDataSource1" 
   7:                OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
   8:  <Columns>
   9:  <asp:CommandField ShowSelectButton="True" />
  10:  <asp:BoundField DataField="Record" HeaderText="Record"/>
  11:  <asp:BoundField DataField="ResponseID" HeaderText="ResponseID"/>
  12:  <asp:BoundField DataField="Source_id" HeaderText="Source_id"/>
  13:  <asp:BoundField DataField="Remarks" HeaderText="Remarks"/>
  14:  </Columns>
  15:  </asp:GridView>
  16:   
  17:  <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
  18:  ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
  19:  SelectCommand="Select Record, App_id as ResponseID, 
  20:                 Source_id,Remarks from Website">
  21:  </asp:SqlDataSource>
  22:   
  23:  <table><tr><td>
  24:  <asp:DetailsView ID="DetailsView1" runat="server" 
  25:                   DataKeyNames="Record" AutoGenerateRows="False"
  26:                   DataSourceID="SqlDataSource2">
  27:  <Fields>
  28:  <asp:BoundField DataField="Record" HeaderText="Record"/>
  29:  <asp:BoundField DataField="Name" HeaderText="Name"/>
  30:  </Fields>
  31:  </asp:DetailsView>
  32:   
  33:  <asp:SqlDataSource ID="SqlDataSource2" runat="server" 
  34:  ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
  35:  SelectCommand="SELECT [Record], [Name] FROM 
  36:                 [Applications] WHERE ([Record] = @Record)">
  37:  <SelectParameters>
  38:  <asp:ControlParameter ControlID="GridView1" Name="Record" 
  39:                        PropertyName="SelectedValue"
  40:                        Type="String" />
  41:  </SelectParameters>
  42:  </asp:SqlDataSource></td>
  43:   
  44:  <td>
  45:  <asp:DetailsView ID="DetailsView2" runat="server" 
  46:                   DataKeyNames="App_id" AutoGenerateRows="False" 
  47:                   DataSourceID="SqlDataSource3">
  48:  <Fields>
  49:  <asp:BoundField DataField="App_id" HeaderText="App_id"/>
  50:  <asp:BoundField DataField="Details" HeaderText="Details"/>
  51:  </Fields>
  52:  </asp:DetailsView>
  53:   
  54:  <asp:SqlDataSource ID="SqlDataSource3" runat="server" 
  55:  ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
  56:  SelectCommand="SELECT [App_id], [Details] FROM [Response] 
  57:                 WHERE ([App_id] = @ResponseID)">
  58:  <SelectParameters>
  59:  <asp:ControlParameter ControlID="GridView1" 
  60:                        Name="ResponseID" 
  61:                        PropertyName="SelectedValue"
  62:                        Type="String" />
  63:  </SelectParameters>
  64:  </asp:SqlDataSource></td>
  65:          
  66:  <td>
  67:  <asp:DetailsView ID="DetailsView3" runat="server" 
  68:                   DataKeyNames="Source_id" 
  69:                   AutoGenerateRows="False" 
  70:                   DataSourceID="SqlDataSource4">
  71:  <Fields>
  72:  <asp:BoundField DataField="Source_ID" HeaderText="Source_ID"/>
  73:  <asp:BoundField DataField="LastName" HeaderText="LastName"/>
  74:  </Fields>
  75:  </asp:DetailsView>
  76:   
  77:  <asp:SqlDataSource ID="SqlDataSource4" runat="server" 
  78:  ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
  79:  SelectCommand="SELECT [Source_ID], [LastName] FROM [advt] 
  80:                 WHERE ([Source_ID] = @Source_ID)">
  81:  <SelectParameters>
  82:  <asp:ControlParameter ControlID="GridView1" 
  83:                        Name="Source_ID" 
  84:                        PropertyName="SelectedValue"
  85:                        Type="String" />
  86:  </SelectParameters>
  87:  </asp:SqlDataSource></td>
  88:  </tr></table>
  89:  </div>
  90:  </form>

Write below mentioned code in SelectedIndexChanged Event of Gridveiw.

C# CODE
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string App_id = GridView1.DataKeys[GridView1.SelectedIndex]["ResponseID"].ToString();
        SqlDataSource3.SelectParameters.Clear();
        SqlDataSource3.SelectParameters.Add("ResponseID", App_id);
        DetailsView2.DataBind();

        string Source_id = GridView1.DataKeys[GridView1.SelectedIndex]["Source_id"].ToString();
        SqlDataSource4.SelectParameters.Clear();
        SqlDataSource4.SelectParameters.Add("Source_id", Source_id);
        DetailsView3.DataBind();
    }


VB.NET CODE
Protected Sub GridView1_SelectedIndexChanged(sender As Object, e As EventArgs)
 Dim App_id As String = GridView1.DataKeys(GridView1.SelectedIndex)("ResponseID").ToString()
 SqlDataSource3.SelectParameters.Clear()
 SqlDataSource3.SelectParameters.Add("ResponseID", App_id)
 DetailsView2.DataBind()

 Dim Source_id As String = GridView1.DataKeys(GridView1.SelectedIndex)("Source_id").ToString()
 SqlDataSource4.SelectParameters.Clear()
 SqlDataSource4.SelectParameters.Add("Source_id", Source_id)
 DetailsView3.DataBind()
End Sub

Build and run the code.

Download Sample Code



Find More Articles