This solution has been tested and works using only JavaScript ( jQuery is required for this solution!).
1. C # part ( Page_Load method)
In Page_Load we need to add a small hack:
foreach(GridViewRow row in YourGridViewControlID.Rows) { if (row.RowType == DataControlRowType.DataRow ) { ((CheckBox) row.FindControl("YourCheckBoxID")).Attributes.Add("onchange", "javascript:TextboxAutoEnableAndDisable(" + (row.RowIndex ) + ");"); } }
Thus, we add a JavaScript function call to the OnChange event of each CheckBox our GridView . What is special, and we cannot achieve through HTML , is that we pass the Row Index each of the JavaScript functions, which we need later.
2. Some important notes for the HTML part
Make sure the controls are CheckBox and Textbox , but more importantly your GridView control has a static identifier using ClientIDMode="Static" , as shown below:
<asp:CheckBox ID="YourCheckBoxID" runat="server" ClientIDMode="Static"/> <asp:TextBox ID="YourTextBoxID" TextMode="SingleLine" runat="server" ClientIDMode="Static" />
And for the GridView control:
<asp:GridView ID="YourGridViewControlID" ...... ClientIDMode="Static" runat="server">
3. Javascript Part
And then in your JavaScript file / code:
function TextboxAutoEnableAndDisable(Row) { // Get current "active" row of the GridView. var GridView = document.getElementById('YourGridViewControlID'); var currentGridViewRow = GridView.rows[Row + 1]; // Get the two controls of our interest. var rowTextBox = currentGridViewRow.cells[2].getElementsByTagName("input")[0]; var rowCheckbox = currentGridViewRow.cells[0].getElementsByTagName("input")[0]; // If the clicked checkbox is unchecked. if( rowCheckbox.checked === false) { // Empty textbox and make it disabled rowTextBox.value = ""; rowTextBox.disabled = true; return; } // To be here means the row checkbox is checked, therefore make it enabled. rowTextBox.disabled = false; }
4. Some notes for the above implementation
- Notice that in the JavaScript code in the line:
var currentGridViewRow = GridView.rows[Row + 1];
[Row + 1] itβs important to do this job and not change it. - And finally:
The following lines:
var rowTextBox = currentGridViewRow.cells[2].getElementsByTagName("input")[0]; var rowCheckbox = currentGridViewRow.cells[0].getElementsByTagName("input")[0];
.cells[2] and .cells[0] may be different for you, so you need to select the correct number in [] .
This will usually be the column number of your initial GridView count from 0 .
So, if your CheckBox was in the first column of the GridView, you need .cells[0] .
If your Textbox is in the second column of your GridView , then you need .cells[1] (in my case above, Textbox was in the third column of my GridView , and so I used .cells[2] )