Thursday, 1 September 2016

Maintaining State of CheckBoxes to checked While Paging in a GridView Control

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Maintaining State of CheckBoxes to checked  While Paging in a GridView Control</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView runat="server" ID="gvdetails" AllowPaging="true" AllowSorting="true" AutoGenerateColumns="false" onpageindexchanging="gvdetails_PageIndexChanging" PageSize="8" DataKeyNames="UserId">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="UserId" HeaderText="UserId" />
<asp:BoundField DataField="UserName" HeaderText="UserName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Location" HeaderText="Location" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
 ---------------
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGridData();
}
}
//This method is used to bind the gridview
protected void BindGridData()
{
SqlConnection con = new SqlConnection("Data Source=.;Integrated Security=true;Initial Catalog=MySampleDB");
SqlCommand cmd = new SqlCommand("select * from UserInfo", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvdetails.DataSource = ds;
gvdetails.DataBind();
}
protected void gvdetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
SaveCheckedValues();
gvdetails.PageIndex = e.NewPageIndex;
BindGridData();
PopulateCheckedValues();
}
//This method is used to populate the saved checkbox values
private void PopulateCheckedValues()
{
ArrayList userdetails = (ArrayList)Session["CHECKED_ITEMS"];
if (userdetails != null && userdetails.Count > 0)
{
foreach (GridViewRow gvrow in gvdetails.Rows)
{
int index = (int)gvdetails.DataKeys[gvrow.RowIndex].Value;
if (userdetails.Contains(index))
{
CheckBox myCheckBox = (CheckBox)gvrow.FindControl("chkSelect");
myCheckBox.Checked = true;
}
}
}
}
//This method is used to save the checkedstate of values
private void SaveCheckedValues()
{
ArrayList userdetails = new ArrayList();
int index = -1;
foreach (GridViewRow gvrow in gvdetails.Rows)
{
index = (int)gvdetails.DataKeys[gvrow.RowIndex].Value;
bool result = ((CheckBox)gvrow.FindControl("chkSelect")).Checked;

// Check in the Session
if (Session["CHECKED_ITEMS"] != null)
userdetails = (ArrayList)Session["CHECKED_ITEMS"];
if (result)
{
if (!userdetails.Contains(index))
userdetails.Add(index);
}
else
userdetails.Remove(index);
}
if (userdetails != null && userdetails.Count > 0)
Session["CHECKED_ITEMS"] = userdetails;
}
 

Monday, 15 February 2016

Simple JavaScript/CSS Lightbox

 JavaScript Lightbox script

CSS Code:
body
{
    font-family:Verdana, Arial, Helvetica, sans-serif;
}
#outer
{
    display: none;
    position: absolute;
    top: 0;
    left: 0;
    width: 100‰;
    height: 100‰;
    background-color:#000000;
    z-index:1001;
    -moz-opacity: 0.7;
    opacity:.7;
    filter: alpha(opacity=70);
    padding:10px;
}
#inner
{
    display: none;
    position: fixed;
    top: 100px;
    left: 300px;
    width: 50‰;
    height: 50‰;
    padding: 5px;
    border: 10px solid #FF8000;
    background-color: white;
    z-index:1002;
    overflow: auto;
}
#content
{
    font-size:24px;
    color:#CCCCCC;
}
#close
{
    float:right;
    width:20px;
    height:20px;
    top:0;
    cursor:pointer;
    text-align:center;
    vertical-align:middle;
    font-weight:bold;
}
 
JavaScript Code:
function showId(id)
{
    var obj = document.getElementById(id);
    obj.style.display = 'block';
    return false;
}
function hideId(id)
{
    var obj = document.getElementById(id);
    obj.style.display = 'none';
    return false;
}
function showLightBox()
{
    showId('outer');
    showId('inner');
}
function hideLightbox()
{
    hideId('inner');
    hideId('outer');
}   
 
HTML Body Content:
<div id="outer"></div>
<div id="inner">
    <div id="close" onclick="hideLightbox()">X</div>
    <span id="content">Content Will Come Here</span>
</div>
<a href="javascript: void(0);" onclick="showLightBox();">Click Here</a> to view Lightbox
 
 

Friday, 4 December 2015

Server.MapPath

Server.MapPath(".") returns the current physical directory of the page that you are running
Server.MapPath("..") returns the parent physical directory of the page that you are running
Server.MapPath("~") returns the physical path of the root directory of the application 

Binding an asp.net dropdownlist with an XML file

First add an XML file, to the web application project. To do this 
1. Right click on the web application project, and select Add => New Item.
2. In the Add New Item dialog box, select XML File.
3. Give the XML file a meaningful name. In our case let's name it Countries.xml and click Add.
4. In the Countries.xml file, copy and paste the following
<?xml version="1.0" encoding="utf-8" ?>
<Countries>
  <Country>
    <CountryId>101</CountryId>
    <CountryName>India</CountryName>
  </Country>
  <Country>
    <CountryId>102</CountryId>
    <CountryName>USA</CountryName>
  </Country>
  <Country>
    <CountryId>103</CountryId>
    <CountryName>Australia</CountryName>
  </Country>
  <Country>
    <CountryId>104</CountryId>
    <CountryName>Africa</CountryName>
  </Country>
</Countries> 


Drag and drop a DropDownList on the webform. Copy and paste the following code in the code behind page.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        //Create a new DataSet
        DataSet DS = new DataSet();
        //Read the xml data from the XML file using ReadXml() method
        DS.ReadXml(Server.MapPath("Countries.xml"));
        DropDownList1.DataTextField = "CountryName";
        DropDownList1.DataValueField = "CountryId";
        DropDownList1.DataSource = DS;
        DropDownList1.DataBind();
        ListItem li = new ListItem("Select""0");
        DropDownList1.Items.Insert(0, li);
    }
}

The important thing to notice here is that, we are using ReadXml() method of the DataSet object, to read the data from the Countries.xml file into a DataSet.Server.MapPath() method returns the physical path of the file from the provided virtual path. We will discuss about this method in a later video session.

To insert a ListItem at a specific location use the Insert() method specifying the index of the location where you want to insert, and the listitem object.

IsPostBack in asp.net

IsPostBack is a Page level property, that can be used to determine whether the page is being loaded in response to a client postback, or if it is being loaded and accessed for the first time. 

In real time there are many situations where IsPostBack property is used. For example, consider the webform used to register employee details. A sample form that we will use for this example is shown below. The form has First Name, Last Name and City fields.  

If you want to follow along with me, copy and paste the following HTML in a web form.
<table style="font-family: Arial">
    <tr>
        <td colspan = "2"><b>Employee Details Form</b></td>
    </tr>
    <tr>
        <td>First Name: </td>
        <td> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </td>
    </tr>
    <tr>
        <td>Last Name: </td>
        <td> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> </td>
    </tr>
    <tr>
        <td>City:</td>
        <td>
            <asp:DropDownList ID="ddlCity" runat="server">
            </asp:DropDownList>
        </td>
    </tr>
    <tr>
        <td></td>
        <td>
            <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
                Text="Register Employee" />
        </td>
    </tr>
</table>

Copy and Paste the following code in the code behind file of the web form.
protected void Page_Load(object sender, EventArgs e)
{
    LoadCityDropDownList();
}
public void LoadCityDropDownList()
{
    ListItem li1 = new ListItem("London");
    ddlCity.Items.Add(li1);

    ListItem li2 = new ListItem("Sydney");
    ddlCity.Items.Add(li2);

    ListItem li3 = new ListItem("Mumbai");
    ddlCity.Items.Add(li3);
}
protected void Button1_Click(object sender, EventArgs e)
{
} 

Now run the application. Look at the City DropDownList. The cities, (London, Sydney and Mumbai) are correctly shown as expected. Just click the button once. Notice, that the city names in the DropDownList are duplicated. So, every time you click the button, the city names are again added to the DropDownList.

Let's now understand the cause for this duplication.
We know that all ASP.NET server controls retain their state across postback. These controls make use of ViewState. So, the first time, when the webform load. the cities get correctly added to the DropDownList and sent back to the client.

Now, when the client clicks the button control, and the 
webform is posted back to the server for processing. During the Page initialization, ViewState restoration happens. During this stage, the city names are retrieved from the viewstate and added to the DropDownList. PageLoad event happens later in the life cycle of the webform. During page load we are again adding another set of cities. Hence, the duplication.

How to solve the DropDownList items duplication
There are several ways to solve this. One of the best ways to do this, is to use IsPostBack property. So, in the Page_Load, call LoadCityDropDownList() method, if the request, is not a postback request. That is, only if the webform is being loaded and accessed for the first time.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        LoadCityDropDownList();
    }
}

Another way to solve, this problem is to simply disable the ViewState of the DropDownlist control. To disable the viewstate, right click the DropDownList control, and set EnableViewState property to false. Now run the project, and the cities duplication issue is gone.

But the problem, with 
this approach is that, the DropDownList list, does not remember your selecttion across postback. That is, Select "Mumabi" as the city, and submit the form. When the page rerenders, observer that selection is set back to "London". Another problem with, disabling the viewstate is that, the DropDownList events may not work correctly as expected.

Another way to solve this, is to clear all the DropDownList items, before calling LoadCityDropDownList() method. But this not efficient from a performance perspective. The modified code is shown below.
protected void Page_Load(object sender, EventArgs e)
{
    ddlCity.Items.Clear();
    LoadCityDropDownList();
}