Introduction
This sample explains how to attach JavaScript methods/functions to an ASP.NET GridView
control at row level. The user experience here is far better, and the client handles user actions, and there are fewer postbacks. In this sample, there is a checkbox on the grid. When the user checks the checkbox, the row color changes, indicating the user that the particular record is selected. When the user selects an option in the column 'Discontinued?', the text box in the column 'Reason to Discontinue?' for that row shows up.
function ColorRow(CheckBoxObj)
{
if (CheckBoxObj.checked == true) {
CheckBoxObj.parentElement.parentElement.style.backgroundColor='#88AAFF';
}
else
{
CheckBoxObj.parentElement.parentElement.style.backgroundColor='#FFFFFF';
}
}
This method is attached to checkbox on the rowDatabound
event of the GridView
.
if (e.Row.RowType == DataControlRowType.DataRow)
{
((CheckBox)e.Row.FindControl("CheckMark")).Attributes.Add(
"onClick", "ColorRow(this)");
}
The other functionality demonstrated here is how to make the control visible and invisible based on user selection. When the user selects the Yes option in the column Discontinued, the textbox for the explanation becomes visible. The JavaScript to toggle control visibility is as follows:
function ShowHideField(DecisionControl, ToggleControl)
{
var DecisionValue = getRadioSelectedValue(DecisionControl);
if (DecisionValue =='True')
{
ToggleControl.style.visibility='visible';
}
else
{
ToggleControl.style.visibility='hidden';
}
}
This JavaScript method/function is attached in the RowDataBound
event of the GridView
as follows:
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox txtReasonDiscontinue =
((TextBox)e.Row.FindControl("ReasonDiscontinue"));
RadioButtonList rblDiscontinue =
((RadioButtonList)e.Row.FindControl("rblDiscontinued"));
string strDicontinued = rblDiscontinue.SelectedValue;
if (String.Compare(strDicontinued.Trim(), "False", true) == 0)
{
txtReasonDiscontinue.Attributes.Add("Style", "visibility:hidden");
}
rblDiscontinue.Attributes.Add("onClick",
"ShowHideField(this," + txtReasonDiscontinue.ClientID + ")");
}