Search This Blog

Tuesday, August 31, 2010

Alphabet Paging in GridView

In this sample we can implement alphabetic paging for the gridview.

GridView Markup

<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" ShowFooter="True"OnRowCreated="GridView1_RowCreated"
OnRowCommand="GridView1_RowCommand">
</asp:GridView>
</div>
</form>
 
Code Behind

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

if
(!IsPostBack)
{
if (Session["strTemp"] != null)
{

GridView1.DataSource = Session["strTemp"] as DataTable;

GridView1.DataBind();

}
else
{
GridView1.DataSource = GetCustomMadeDataTable();
GridView1.DataBind();
}
}

}
public DataTable GetCustomMadeDataTable()
{

//Create a new DataTable object
System.Data.DataTable objDataTable = new System.Data.DataTable();
//Create three columns with string as their type
objDataTable.Columns.Add("Id", typeof(string));
objDataTable.Columns.Add("Column1", typeof(string));
objDataTable.Columns.Add("Column2", typeof(string));
objDataTable.Columns.Add("Column3", typeof(string));

//Adding some data in the rows of this DataTable
DataRow dr;
for (int i = 65; i <= (65 + 25); i++)
{

dr = objDataTable.NewRow();
dr[0] = i.ToString();
dr[1] = Char.ConvertFromUtf32(i)+"Column1Data" + i.ToString();
dr[2] = Char.ConvertFromUtf32(i+1)+"Column2Data" + i.ToString();
dr[3] = Char.ConvertFromUtf32(i+2)+"Column3Data" + i.ToString();
objDataTable.Rows.Add(dr);


}
DataColumn[] dcPk = new DataColumn[1];
dcPk[0] = objDataTable.Columns["Id"];
objDataTable.PrimaryKey = dcPk;
Session["strTemp"] = objDataTable;


return objDataTable;
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{

TableCell cell = e.Row.Cells[0];
cell.ColumnSpan = 2;

for (int i = 65; i <= (65 + 25); i++)
{
LinkButton lb = new LinkButton();

lb.Text = Char.ConvertFromUtf32(i) + " ";

lb.CommandArgument =
"%" + Char.ConvertFromUtf32(i) + "%";
lb.CommandName = "AlphaPaging";

cell.Controls.Add(lb);

}
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
//At first I check that if the CommandName is “AlphaPaging”
if (e.CommandName.Equals("AlphaPaging"))
{

GridView1.DataSource = GetById(e.CommandArgument.ToString());

GridView1.DataBind();
}
}

public DataView GetById(string id)
{

//Fetch record from database using like operator.
DataTable dt = new DataTable();
dt = Session["strTemp"] as DataTable;
DataView dv = dt.DefaultView;

dv.RowFilter = "Column1 LIKE '" + id + "'";
return dv;


}
}

Get CommandArgument on Click Event of Button in TemplateField

GridView Markups

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false">
    <Columns>
        <asp:TemplateField>
        <ItemTemplate>
           <asp:Button ID="Button1" runat="server" Text='<%#Eval("CustomerID")%>'
                  CommandArgument = "Button1"  OnClick = "Button1_Click" />
        </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
Many occasions you will need the properties of the Button like its CommandName, CommandArgument. So in that case you will need to get the reference of the Button using the sender parameter.  
Code Behind
protected void Button1_Click(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    string CommandName = btn.CommandName;
    string CommandArgument = btn.CommandArgument;
}

Get GridView Row and GridView Row Index on Click Event of Button in TemplateField

GridView Markup

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false">
    <Columns>
        <asp:TemplateField>
        <ItemTemplate>
           <asp:Button ID="Button1" runat="server" Text='<%#Eval("CustomerID")%>'
                  CommandArgument = "Button1"  OnClick = "Button1_Click" />
        </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView> 

Now when the Button is clicked the Click event of the Button is executed.

Code Behind

protected void Button1_Click(object sender, EventArgs e)
{
    GridViewRow gvRow = (GridViewRow)(sender as Control).Parent.Parent;
    int index = gvRow.RowIndex;
}
 
You will notice I am type casting the sender parameter to get the reference of the GridView Row. The sender is the Button Control, thus the parent of the Button Control is the Cell and the parent of the Cell is the GridView Row.
Button ----------> GridView Cell ----------> GridView Row
The same applies to LinkButton and ImageButton.

Get GridView Row and GridView Row Index on RowCommand Event

Below is a simple ASP.Net GridView Control with a ButtonField and an OnRowCommand Event

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false" 
    OnRowCommand = "OnRowCommand">
 <Columns>
  <asp:ButtonField CommandName = "ButtonField"  DataTextField = "CustomerID"
        ButtonType = "Button"/>
 </Columns>
</asp:GridView>
Now when the Button of the button is clicked the OnRowCommand event is executed.

protected void OnRowCommand(object sender, GridViewCommandEventArgs e)
{
    int index = Convert.ToInt32(e.CommandArgument);
    GridViewRow gvRow = GridView1.Rows[index]; 
}

The RowIndex of the GridView Row is contained in the CommandArgument Property. Thus with that index you can get the reference of the GridView Row

Monday, August 30, 2010

Using JavaScript with GridView Control CheckBox Column


In this code snippets we will discuss about to select all the checkboxes in the gridview by selecting the header checkbox. The functions we covered here is


1. Highlighting selected row
2. Check/Uncheck all records using single checkbox.

GridView Markup
<asp:GridView ID="GridView1" runat="server"  HeaderStyle-CssClass = "header"
AutoGenerateColumns = "false" Font-Names = "Arial"
OnRowDataBound = "RowDataBound"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B" >
<Columns>
<asp:TemplateField>
    <HeaderTemplate>
      <asp:CheckBox ID="checkAll" runat="server" onclick = "checkAll(this);" />
    </HeaderTemplate>
   <ItemTemplate>
     <asp:CheckBox ID="CheckBox1" runat="server" onclick = "Check_Click(this)" />
   </ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="150px" DataField="CustomerID" HeaderText="CustomerID"  />
<asp:BoundField ItemStyle-Width="150px" DataField="City"
HeaderText="City" />
<asp:BoundField ItemStyle-Width="150px" DataField="Country"
HeaderText="Country"/>
<asp:BoundField ItemStyle-Width="150px" DataField="PostalCode"  HeaderText= "PostalCode"/>
</Columns>
</asp:GridView>

Highlight Row when checkbox is checked
<script type = "text/javascript">
function Check_Click(objRef)
{
    //Get the Row based on checkbox
    var row = objRef.parentNode.parentNode;
    if(objRef.checked)
    {
        //If checked change color to Aqua
        row.style.backgroundColor = "aqua";
    }
    else
    {   
        //If not checked change back to original color
        if(row.rowIndex % 2 == 0)
        {
           //Alternating Row Color
           row.style.backgroundColor = "#C2D69B";
        }
        else
        {
           row.style.backgroundColor = "white";
        }
    }
   
    //Get the reference of GridView
    var GridView = row.parentNode;
   
    //Get all input elements in Gridview
    var inputList = GridView.getElementsByTagName("input");
   
    for (var i=0;i<inputList.length;i++)
    {
        //The First element is the Header Checkbox
        var headerCheckBox = inputList[0];
       
        //Based on all or none checkboxes
        //are checked check/uncheck Header Checkbox
        var checked = true;
        if(inputList[i].type == "checkbox" && inputList[i] != headerCheckBox)
        {
            if(!inputList[i].checked)
            {
                checked = false;
                break;
            }
        }
    }
    headerCheckBox.checked = checked;
   
}
</script>

The above function is invoked when you check / uncheck a checkbox in GridView row
First part of the function highlights the row if the checkbox is checked else it changes the row to the original color if the checkbox is unchecked.
The Second part loops through all the checkboxes to find out whether at least one checkbox is unchecked or not.
If at least one checkbox is unchecked it will uncheck the Header checkbox else it will check it

Check all checkboxes functionality

<script type = "text/javascript">
function checkAll(objRef)
{
    var GridView = objRef.parentNode.parentNode.parentNode;
    var inputList = GridView.getElementsByTagName("input");
    for (var i=0;i<inputList.length;i++)
    {
        //Get the Cell To find out ColumnIndex
        var row = inputList[i].parentNode.parentNode;
        if(inputList[i].type == "checkbox"  && objRef != inputList[i])
        {
            if (objRef.checked)
            {
                //If the header checkbox is checked
                //check all checkboxes
                //and highlight all rows
                row.style.backgroundColor = "aqua";
                inputList[i].checked=true;
            }
            else
            {
                //If the header checkbox is checked
                //uncheck all checkboxes
                //and change rowcolor back to original
                if(row.rowIndex % 2 == 0)
                {
                   //Alternating Row Color
                   row.style.backgroundColor = "#C2D69B";
                }
                else
                {
                   row.style.backgroundColor = "white";
                }
                inputList[i].checked=false;
            }
        }
    }
}
</script>
The above function is executed when you click the Header check all checkbox When the Header checkbox is checked it highlights all the rows and checks the checkboxes in all rows.
And when unchecked it restores back the original color of the row and unchecks the checkboxes.

Note:
The check all checkboxes checks all the checkboxes only for the current page of the GridView and not all.
 
 

 

Gridview RadioButton Column Single Select

In the gridview radiobutton column, if we need to select a single radio button as a single option then we need to do some javascript for that...

JavaScript for single select radio button:
<script type="text/javascript">
function RadioChecked(param)
{   
var frm = document.forms[0];              
for (i=0; i < frm.length; i++)  
    {      
    if (frm.elements[i].type == "radio")      
        {     
            if (param != frm.elements[i].id )     
            {        
                frm.elements[i].checked = false;     
            }      
        }  
    }
}
</script>

Code behind:
  protected void YourGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex != -1 && e.Row.DataItem != null)
        {
            //calling javascript function to restrict the user to select only one radiobutton
            RadioButton rd = (RadioButton)e.Row.FindControl("rdbGVRow");
            rd.Attributes.Add("onclick", "javascript:RadioChecked('" + rd.ClientID + "');");
        }
   }







Friday, August 27, 2010

Highlight GridView Row on mouseover event

The below JavaScript function accepts the reference of the GridView Row and the event which has triggered it.

Then based on the event type if event is mouseover it highlights the row by changing its color to orange else if the event is mouseout it changes the row’s color back to its original before the event occurred.

Javascript

<script type = "text/javascript">
function MouseEvents(objRef, evt)
{
   var checkbox = objRef.getElementsByTagName("input")[0];
   if (evt.type == "mouseover")
   {
        objRef.style.backgroundColor = "orange";
   }
   else
   {
        if (checkbox.checked)
        {
            objRef.style.backgroundColor = "aqua";
        }
        else if(evt.type == "mouseout")
        {
            if(objRef.rowIndex % 2 == 0)
            {
               //Alternating Row Color
               objRef.style.backgroundColor = "#C2D69B";
            }
            else
            {
               objRef.style.backgroundColor = "white";
            }
        }
   }
}
</script>

Code Behind

protected void YourGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow )
    {
        e.Row.Attributes.Add("onmouseover","MouseEvents(this, event)");
        e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
    }
}

Thursday, August 26, 2010

Maintaining State of CheckBoxes While Paging in a GridView Control

Every time its difficult to work with the checkbox control inside the gridview with paging, In this article, I will demonstrate how you can maintain the state of Check Boxes while paging in a GridView control.

You need to bind your gridview using your own method.
Here, I have used the method to bind the gridview is "BindData();"

Your grid view may want to be like this

<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" AllowPaging="True" 
PageSize="5" Width="324px" DataKeyNames="CategoryID"
OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Save Checked Values

private void GetOldValues()
{
  ArrayList categoryIDList = new ArrayList();
  int index = -1;
  foreach (GridViewRow row in GridView1.Rows)
  {
   index = (int) GridView1.DataKeys[row.RowIndex].Value;
   bool result = ((CheckBox)row.FindControl("CheckBox1")).Checked;

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

Re-Populate CheckBoxes

private void PopulateValues()
{
  ArrayList categoryIDList = (ArrayList)Session[CHECKED_ITEMS];
  if (categoryIDList != null && categoryIDList.Count > 0)
  {
  foreach (GridViewRow row in GridView1.Rows)
  {
   int index = (int)GridView1.DataKeys[row.RowIndex].Value;
  if (categoryIDList.Contains(index))
  {
   CheckBox myCheckBox = (CheckBox) row.FindControl("CheckBox1");
   myCheckBox.Checked = true;
  }
  }
  }
}

GridView Page_IndexChanging Event

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
  GetOldValues();
  GridView1.PageIndex = e.NewPageIndex;
  BindData();
  PopulateValues();
}

The above method first calls GetOldValues so that all primary keys of the checked CheckBoxes will be saved in a Session object. Next ,the page goes to the new GridView page, and finally, we populate the CheckBoxes using the PopulateValues method.

Wednesday, August 25, 2010

Resizable DropDownList

In this example, I will create a resizable DropDownList. The DropDownList control has a width property that is set to a fixed width. Using javascript, I am modifying the width of the DropDownList.
Inside the form tag,

<form id="form1" runat="server">
<asp:DropDownList ID="DropDownList1" runat="server" Width="50px">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
</asp:DropDownList>
</form>

I am adding a DropDownList with fixed width. Then in the Page_Load method,
protected void Page_Load(object sender, EventArgs e)
{
DropDownList1.Attributes.Add("onmouseover", "ddlMouseOver()");
DropDownList1.Attributes.Add("onmouseout", "ddlMouseOut()");
}

I am adding 2 attributes "onmouseover" and "onmouseout" javascript functions to the DropDownList In the actual javascript, I am changing the width of the control accordingly.

<script type="text/javascript">
function ddlMouseOver()
{
document.getElementById("<%= DropDownList1.ClientID %>").style.width = "200px";
}

function ddlMouseOut()
{
document.getElementById("<%= DropDownList1.ClientID %>").style.width = "50px";
}
</script>

GridView with DropDownList In all Type of Template Fields

Most of the coders have problem when they are binding a gridview with a dropdownlist within the gridview. And some problem may occur in the edit mode with the selected vlaue of the dropdownlist to solve the problem you can use like the following

In the GridView markup need to code like this:

<asp:TemplateField HeaderText="Event">
<EditItemTemplate>
<asp:DropDownList ID="ddlGvEditEvents" runat="server" AutoPostBack="True" DataSource='<%#getvalues() %>'
DataTextField="EventName" DataValueField="EventID" Font-Size="Small" Width="150px" SelectedValue='<%# Bind("EventId") %>'>
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlGvFooterEvents" runat="server" AutoPostBack="True" Font-Size="Small" DataSource='<%#getvalues() %>' DataTextField="EventName" DataValueField="EventID" Width="150px">
</asp:DropDownList>
</FooterTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddlGvItemEvents" runat="server" AutoPostBack="True" Font-Size="Small" DataSource='<%#getvalues() %>' DataTextField="EventName" DataValueField="EventID" Width="150px" SelectedValue='<%# Bind("EventId") %>'>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
 
C# Code Behind:
 
public DataSet getvalues()
{
try
   {
    DataSet dsEvents = new DataSet();
    //Your method to fill the dataset from the DataBase
    ViewState["EventTable"] = dsEvents;
    return dsEvents;
    }
catch (Exception ex)
{
  throw ex;
}
}