Thursday, September 3, 2009

DataGrid Checkbox to Select the Rows

The main intend of this datagrid checkbox column is to select all the rows of the datagrid using a single click. If for example you want to choose all the rows or else if you want to select 8 out of 10 rows, instead of selecting each time a row you can select all the rows by clicking the header checkbox and deselect the two rows by unchecking the checkbox which you might not need to select. Now, to Select the rows in a datagrid using checkbox add a Checkbox column to the datagrid as follows.

<asp:DataGrid ID="dgrdcheck" DataKeyField="UserID" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateColumn>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkdatas" runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="UserID">
<HeaderStyle />
<ItemStyle />
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem,"UserID") %>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Username">
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem,"UserName") %>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Password">
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem,"Password") %>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

So now, in the above example the first column of the datagrid is checkbox column with a header checkbox.

Note:- The above code should be placed in .aspx i.e) the source file.

Place the following javascript to the same (.aspx) source file.


<script type="text/javascript">

var dgrdtest = document.getElementById('<%=dgrdcheck.ClientID %>');

function CheckAll(event)
{
var dgrdRows = dgrdtest.childNodes(0).childNodes;
var srcControl = event.srcElement || event.target;
for(index = 1; index < dgrdRows.length; index++)
{
try
{
if(srcControl.checked)
{
dgrdRows(index).childNodes(0).childNodes(0).checked=true;
}
else
{
dgrdRows(index).childNodes(0).childNodes(0).checked=false;
}
}
catch(e)
{
}
}
}

</script>


Add the following event to the .cs file i.e) the code behind file for the header checkbox to function properly.

protected void dgrdcheck_ItemCreated(object sender, DataGridItemEventArgs e)
{
switch (e.Item.ItemType)
{
case ListItemType.Header:
TableCell objcell = e.Item.Cells[0];
CheckBox objcheck = (CheckBox)objcell.Controls[1];
objcheck.Attributes.Add("onClick", "CheckAll(event)");
break;
}
}

Note:- You have to place the below Event Handler code in Page_Load or Page_Init method for the event "dgrdcheck_ItemCreated" to get fired.

this.dgrdcheck.ItemCreated +=new DataGridItemEventHandler(this.dgrdcheck_ItemCreated);


For Example:

protected void Page_Init(object sender, EventArgs e)
{
this.dgrdcheck.ItemCreated +=new DataGridItemEventHandler(this.dgrdcheck_ItemCreated);

}

0 comments:

.