"Invalid Postback" exception on custom GridView with custom row events - c#

I think I have figured out what happens with this program.
This is part of the markup.
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:UpdatePanel ID="upGrid" runat="server">
<ContentTemplate>
<asp:GridView ID="dgvPeliculas" runat="server" AllowPaging="true" PagerStyle-CssClass="pgr"
CssClass="mGrid" EmptyDataText="No hay más películas" OnPageIndexChanging="dgvPeliculas_PageIndexChanging1"
EnableSortingAndPagingCallbacks="true" OnRowDataBound="dgvPeliculas_RowDataBound">
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<table class="LogIn">
<tr>
<td>
<asp:UpdatePanel ID="upAlquiler" runat="server">
<ContentTemplate>
<asp:Button ID="btnAlquilar" runat="server" Text="Alquilar" CssClass="AdminButtons"
OnClick="btnAlquilar_Click" OnClientClick="javascript: Click_Alquilar(); return false" />
</ContentTemplate>
</asp:UpdatePanel>
</td>
<td>
<asp:Button ID="btnNuevo" runat="server" Text="Nuevo" CssClass="AdminButtons" OnClick="btnNuevo_Click"
OnClientClick="javascript: Click_Nuevo(); return false" />
</td>
<td>
<asp:Button ID="btnEditar" runat="server" Text="Editar" CssClass="AdminButtons" OnClick="btnEditar_Click"
OnClientClick="javascript: Click_Editar(); return false" />
</td>
<td>
<asp:Button ID="btnBorrar" runat="server" Text="Borrar" OnClientClick="javascript: Click_Borrar(); return false"
CssClass="AdminButtons" />
</td>
</tr>
</table>
I have coded it in such a way that the buttons modify it when a row is selected. The rows are selected by changing the "onclick" event (changed during the RowDataBound function), and a Javascript function.
This is how I change the code behind:
protected void dgvPeliculas_RowDataBound(object sender, GridViewRowEventArgs e)
{
dgvPeliculas.CssClass = "mGrid";
if (e.Row.RowType == DataControlRowType.DataRow)
{
string rowID = String.Empty;
rowID = "row" + e.Row.RowIndex;
e.Row.Attributes.Add("id", rowID);
e.Row.Attributes.Add("onclick", "onClick(" + "'" + rowID + "'" + ")");
e.Row.Attributes.Add("onmouseover", "this.style.cursor='pointer'; this.style.backgroundColor = '#B0C5BB';");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor = '';");
}
}
This is the JavaScript function:
/
function onClick(rowID)
{
//Si no hay ninguna seleccionada
if (selected == '') {
index = rowID;
selected = document.getElementById(rowID);
selected.onmouseover = '';
selected.onmouseout = '';
selected.style.backgroundColor = 'yellow';
}
else {
//Si se deselecciona
if (selected == document.getElementById(rowID)) {
selected.onmouseover = onmouseover;
selected.onmouseout = onmouseout;
selected.style.backgroundColor = '';
selected = '';
index = '';
}
//Deseleccionar el actual y seleccionar el nuevo
else {
selected.onmouseover = onmouseover;
selected.onmouseout = onmouseout;
selected.style.backgroundColor = '';
index = rowID;
selected = document.getElementById(rowID);
selected.onmouseover = '';
selected.onmouseout = '';
selected.style.backgroundColor = 'yellow';
}
}
}
The New button shows a ModalPopupExtender, and from there it calls a JavaScript function to validate its contents, and then does a postback to code behind to check and update the database. It also appends the register on the Grid, obviously.
The Edit button and the rest through the exception. The Edit function is particular, because its functionality is similar to that of the New button. It shows the ModalPopupExtender, goes to the JavaScript function, does the postback, to the database and updates. But this one needs to have one of the rows in the Grid selected (otherwise, there's nothing to be edited). I believe this is the reason why it throws the "Invalid Postback or Callback" exception. The same condition applies to the other buttons, and all of them throw the same exception. All, except New, which doesn't need to have a row selected.
Do you think this is the reason why I'm having this problem? And if so, how can I fix it?
Sorry if you consider this a repost of one of my previous threads, but I haven't been able to fix the problem, and I think this gives me a new clue that I can't work out neither.
Thanks.

Related

Id could not be found in Datalist on click of upload button

I have one page where I am making use of Update panel, Datalist and file upload. I am using visual studio 2010.
My fileupload is in data list and I am binding data list with dynamic table to repeat the file upload control.
Please see below layout image:
Here Main upper red highlighted border is showing the repeated data list and in that I have file upload control.
Now the data list is in Update Panel so the file upload was not working So in data list I have taken another update panel to make file upload work and that was also working properly but on clicking of green add button issue started arising as
A control with ID 'Upload' could not be found for the trigger in
UpdatePanel 'UpdatePanel1'.
Below is my html code and please remember I am just giving the part where issue is arises:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="Uppanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:DataList ID="dtcustomerregistration" runat="server" RepeatDirection="Vertical"
Width="100%" OnItemCommand="dtcustomerregistration_ItemCommand">
<ItemTemplate>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<label class="col-md-4 control-label" for="Pic">
Upload Image:</label>
<asp:FileUpload ID="Pic" runat="server" accept="image/gif, image/jpg, image/jpeg, image/png" />
<asp:Button ID="Upload" CommandArgument='<%#Eval("uniqueId") %>' CommandName="Edit"
runat="server" Text="Upload" OnClick="Upload_Click" />
<asp:Label ID="StatusLabel" runat="server" CssClass="requiredvalidate" Text=""></asp:Label>
<asp:HiddenField ID="hdimagename" runat="server" Value='<%#Eval("UploadImage") %>' />
<asp:Image ID="imgpicuploaded" runat="server" ImageUrl='<%#System.Configuration.ConfigurationManager.AppSettings["ShowImagetemppath"].ToString().Replace("~/","") +Eval("UploadImage").ToString() %>'
Height="50px" />
</div>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="Upload" />
</Triggers>
</asp:UpdatePanel>
</ItemTemplate>
</asp:DataList>
<asp:ImageButton ID="imgplus" runat="server" ImageUrl="~/Image/Add.png" Height="50px" OnClick="imgplus_Click" />
</ContentTemplate>
</asp:UpdatePanel>
My code on imgplus click event is as below.
protected void imgplus_Click(object sender, ImageClickEventArgs e)
{
int n = (int)ViewState["n"];
n = n + 1;
BindData(n);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["data"] = null;
BindData(0);
}
}
public void BindData(int n)
{
DataTable dt = new DataTable();
dt.Columns.Add("uniqueId");
dt.Columns.Add("Invoice");
dt.Columns.Add("ReturnType");
dt.Columns.Add("ItemNumber");
dt.Columns.Add("ReturnQTY");
dt.Columns.Add("UnitofMeasure");
dt.Columns.Add("CreditPer");
dt.Columns.Add("ReasonCode");
dt.Columns.Add("InvoiceNumber");
dt.Columns.Add("Ordernumber");
dt.Columns.Add("Notes");
dt.Columns.Add("UploadImage");
if (ViewState["data"] == null)
{
dt = bindemptydata(dt, n);
}
else
{
foreach (DataListItem dli in dtcustomerregistration.Items)
{
HiddenField lblid = (HiddenField)dli.FindControl("lblid");
DropDownList RetCred = (DropDownList)dli.FindControl("RetCred");
DropDownList returntype = (DropDownList)dli.FindControl("returntype");
TextBox ItemNumber = (TextBox)dli.FindControl("ItemNumber");
TextBox ReturnQty = (TextBox)dli.FindControl("ReturnQty");
DropDownList Unit = (DropDownList)dli.FindControl("Unit");
TextBox Credit = (TextBox)dli.FindControl("Credit");
DropDownList ReasonCode = (DropDownList)dli.FindControl("ReasonCode");
TextBox Invoice = (TextBox)dli.FindControl("Invoice");
TextBox OrderNumber = (TextBox)dli.FindControl("OrderNumber");
TextBox Notes = (TextBox)dli.FindControl("Notes");
Image imgpicuploaded = (Image)dli.FindControl("imgpicuploaded");
HiddenField hdimagename = (HiddenField)dli.FindControl("hdimagename");
DataRow dr = dt.NewRow();
if (lblid.Value != "")
{
dr["uniqueId"] = lblid.Value;
}
else
{
dr["uniqueId"] = n;
}
dr["Invoice"] = RetCred.SelectedValue;
dr["ReturnType"] = returntype.SelectedValue;
dr["ItemNumber"] = ItemNumber.Text;
dr["ReturnQTY"] = ReturnQty.Text;
dr["UnitofMeasure"] = Unit.SelectedValue;
dr["CreditPer"] = Credit.Text;
dr["ReasonCode"] = ReasonCode.SelectedValue;
dr["InvoiceNumber"] = Invoice.Text;
dr["Ordernumber"] = OrderNumber.Text;
dr["Notes"] = Notes.Text;
dr["UploadImage"] = hdimagename.Value;
dt.Rows.Add(dr);
}
dt = bindemptydata(dt, n);
}
BindDatalist(dt);
ViewState["n"] = n;
}
public DataTable bindemptydata(DataTable dt, int n)
{
DataRow dr = dt.NewRow();
dr["uniqueId"] = n;
dr["Invoice"] = "Credit";
dr["ReturnType"] = "0";
dr["ItemNumber"] = "";
dr["ReturnQTY"] = "";
dr["UnitofMeasure"] = "Each";
dr["CreditPer"] = "100%";
dr["ReasonCode"] = "0";
dr["InvoiceNumber"] = "";
dr["Ordernumber"] = "";
dr["Notes"] = "";
dr["UploadImage"] = "";
dt.Rows.Add(dr);
return dt;
}
public void BindDatalist(DataTable dt)
{
dtcustomerregistration.DataSource = dt;
dtcustomerregistration.DataBind();// Here I am receiving error
ViewState["data"] = dt;
}
Here above I had given full code to create the dynamic data table and binding that with data list so that data list get repeated on click of imgplus button
But on click of button I am receiving error as :
Below is the error image.
How can I fix this?
On Click on Imgplus button I m receiving issue for upload button which exist in DataList.
And one more thing that if I normally click ImgPlus button without having use of Upload button click then it will repeat the DataList control without giving any issue but in case Once I made use of Upload click button exist in DataList and then after I click Imgplus button I receive error as:
A control with ID 'Upload' could not be found for the trigger in
UpdatePanel 'UpdatePanel1'.
Surround your button with another UpdatePanel upButton:
<asp:UpdatePanel ID="upButton" runat="server" UpdateMode="Conditional">
<asp:Button ID="Upload" CommandArgument='<%#Eval("uniqueId") %>' CommandName="Edit"
runat="server" Text="Upload" OnClick="Upload_Click" />
</ContentTemplate>
And then call your main UpdatePanel Uppanel.Update(); in your button click method Upload_Click.
Note: Remove UpdatePanel ID="UpdatePanel1".
You're error happens because of this code:
<Triggers>
<asp:PostBackTrigger ControlID="Upload" />
</Triggers>
You used PostBackTrigger while you are inside a nested pannel, while you shoud use
AsyncPostBackTrigger in this case as per this page.
So change that code segment to be:
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Upload" />
</Triggers>
or set the UpdateMode of UpdatePanel1 to be "Always"

identify selected checkboxes in asp listview object

I have been trying to understand the ListView object in ASP but I'm unable to programmatically get the selected checkboxes or iterate through them. Below are the two methods I'm seeing posted the most here on SO, but so far everything I've tried hasn't seemed to work for me.
Any help would greatly be appreciated.
.ASPX Page
<asp:ListView ID="courseListView" runat="server">
<LayoutTemplate>
<table><asp:PlaceHolder runat="server" ID="itemPlaceholder">
</asp:PlaceHolder></table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><asp:CheckBox ID="courseIdchk" Text='<%# Eval("CourseId") %>' runat="server" /></td>
<td><asp:Label ID="courseTitleLbl" Text='<%# Eval("title") %>' runat="server" /></td>
</tr>
</ItemTemplate>
</asp:ListView>
.CS Code Behind
//Method #1
string result = string.Join(", ", courseListView.Controls.OfType<CheckBox>()
.Select(chk => chk.Text));
string result = "";
//Method #2
foreach (CheckBox ctrl in courseListView.Controls.OfType<CheckBox>())
{
result2 += ctrl.Text;
}
Response.Write("<p>The result is " + result);
Response.Write("<p>The result is " + result2);
Response.End();
I'm not near the Visual Studio but off the top of my head I see 2 reasons why it does not iterate.
1. You should bind this ListView to a source in OnLoad method:
if (!IsPostback) {
courseListView.DataSource = GetCourses();
courseListView.DataBind();
}
2. courseListView.Controls does not contain items of type CheckBox, so OfType<CheckBox>() filters out all elements. If you debug and put a breakpoint over foreach (CheckBox ctrl in courseListView.Controls.OfType<CheckBox>()), you will see that CheckBox is one of the subchildren of courseListView., so build your logic depending on which control contain CheckBoxes write the appropriate logic to get it like:
var checkBox = courseListView.Controls.Cast<Control>().First().FindControl("courseIdchk");
Again, the code above assumes that checkbox is a child of a control, which is an only child of your courseListView.
UPDATE
var findCheckedQuery = courseListView.Controls[0]
.Controls
.Cast<Control>()
.Select(ctrl => ctrl.FindControl("chkBox") as CheckBox)
.Where(chk => chk != null && chk.Checked);
result = string.Join(":", findCheckedQuery.Select(x => x.Text).ToArray());
UPDATE2
ASPX:
<asp:Repeater ID="courseListView" runat="server">
<ItemTemplate>
<asp:CheckBox ID="chkBox" data-id="<%#((Course)Container.DataItem).CourseId %>" Text="<%#((Course)Container.DataItem).Title %>" runat="server" />
<br/>
</ItemTemplate>
</asp:Repeater>
<asp:Button runat="server" UseSubmitBehavior="True" Text="Submit"/>
Code-behind:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!IsPostBack)
{
courseListView.DataSource = GetCourses();
courseListView.DataBind();
}
else
{
var result = string.Empty;
var findCheckedQuery = courseListView
.Controls
.Cast<Control>()
.Select(x => (CheckBox)x.FindControl("chkBox"))
.Where(x => x.Checked)
.Select(x => x.Text);
result = string.Join(", ", findCheckedQuery.ToArray());
}
}

How to Validate Drop-down inside GridView using JavaScript

I am trying to validate a drop down inside a gridview on a button click. If the drop down has no selection then i want to fire the javascript but the code is not firing at all. I am not sure what am i doing wrong here so please help. thanks.
Here is the button code in the aspx file:
<asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="183px" Visible="true"
onclick="btnSubmit_Click"
OnClientClick="return validate();"
Font-Bold="True" Font-Size="Medium" Height="30px"
style="margin-right: 1px; margin-left: 185px;" ForeColor="#336699" />
here is the javascript in the head section of my page:
<script type="text/javascript">
function validate() {
var flag = true;
var dropdowns = new Array(); //Create array to hold all the dropdown lists.
var gridview = document.getElementById('<%=GridView1.ClientID%>'); //GridView1 is the id of ur gridview.
dropdowns = gridview.getElementsByTagName('--'); //Get all dropdown lists contained in GridView1.
for (var i = 0; i < dropdowns.length; i++) {
if (dropdowns.item(i).value == '--') //If dropdown has no selected value
{
flag = false;
break; //break the loop as there is no need to check further.
}
}
if (!flag) {
alert('Please select value in each dropdown');
}
return flag;
}
</script>
here is my drop-down in the aspx:
<ItemTemplate>
<asp:Label ID="lblAns" runat="server" Text='<%# Eval("DDL_ANS")%>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddl_Answer" runat="server" AutoPostBack="false">
</asp:DropDownList>
</ItemTemplate>
here is the code behind for the dropdown
ddl_Answer.DataSource = cmd1.ExecuteReader();
ddl_Answer.DataTextField = "DD_ANSWER";
ddl_Answer.DataValueField = "DD_ANSWER";
ddl_Answer.DataBind();
ddl_Answer.Items.Insert(0, new ListItem("--"));
How are you trying to select the dropdown using javascript. You probably want this
dropdowns = gridview.getElementsByTagName('select');

My javascript variable is becoming undefined between function calls

I have a form that calls some javascript and some code behind (C# for me) when a link button is pressed. Normal operation should act as such: Click on link button which gets text from a label on the form, opens an HTML editor, save the text by clicking 'Done' on the text editor and then displaying the text on the form again. It will do all of that, but I get an error (control is undefined) and then that prevents me from doing any other work on the form.
First, here is my aspx code, which is a window that hold the HTML editor, and the HTML editor.
<asp:Panel ID="EditCommentPopup" runat="server" SkinID="PopupPanel" HorizontalAlign="Center" Width="500px" Style="display:none;">
<div id="SendCommentHeader" class="modalPopupHeader">
<table width="100%" style="vertical-align: middle">
<tr>
<td style="width: 50%; text-align: left; padding-left: 5px;">
<asp:Label ID="EditCommentHeaderLBL" runat="server" Font-Bold="true" Text="Change Comment" ></asp:Label>
</td>
<td style="width: 50%; text-align: right; padding-right: 3px;">
<asp:Button SkinID="SubmitButton" ID="SaveComment" runat="server" Text="Done" OnClientClick="submitEditorPopup(); return true;" OnClick="SubmitCommentButton_Click"/>
<asp:Button SkinID="CancelButton" ID="cancelCommentButton" runat="server" Text="Cancel"/>
</td>
</tr>
</table>
</div>
<ajaxToolkit:ModalPopupExtender ID="EditCommentPopupExtender" runat="server" TargetControlID="EditCommentHeaderLBL"
PopupControlID="EditCommentPopup" BackgroundCssClass="modalBackground" PopupDragHandleControlID="EditCommentPopup"
DropShadow="False" CancelControlID="cancelCommentButton" BehaviorID="ChangeCommentsPopup" >
</ajaxToolkit:ModalPopupExtender>
<asp:Panel ID="EditCommentInnerPanel" SkinID="PopupInnerPanel" HorizontalAlign="Center" runat="server" >
<asp:Label ID="CommandArgLBL" runat="server" Visible="false"></asp:Label>
<custom:CustomTextEditor ID="EditCommentsTextBox" runat="server" Width="100%" Height="300px" NoScript="true" />
</asp:Panel>
</asp:Panel>
Here are my javascript functions
var contentLBL;
var editorControl;
var hiddenField;
function LoadEditorPopup(labelID, editorID, hiddenID, linkID) {
editorControl = document.getElementById(editorID);
contentLBL = document.getElementById(labelID);
hiddenField = document.getElementById(hiddenID);
editorControl.control.set_content(contentLBL.innerHTML);
var popup = $find("ChangeCommentsPopup");
popup.show();
}
function submitEditorPopup() {
var tmp = editorControl.control.get_content(); //error flags here
contentLBL.innerHTML = tmp;
var str= new String();
str = tmp;
str = str.replace(/</g, "{%");
str = str.replace(/>/g, "%}"); //stripping out html tags to prevent sql insertion
hiddenField.value = str;
var popup = $find("ChangeCommentsPopup");
popup.hide();
}
And here are my C# functions
protected void ShowEditCommentPopup(object sender, EventArgs e)
{
string arg = ((LinkButton)sender).CommandArgument;
string content = "";
string title = "";
switch (arg)
{
//doing stuff, setting content and title
}
EditCommentHeaderLBL.Text = title;
CommandArgLBL.Text = arg;
EditCommentsTextBox.Content = content;
EditCommentPopupExtender.Show();
EditModalPopupExtender.Show(); //this is the form
}
So, what's happening here, I click on a linkbutton (not shown in aspx code) and it fires the LoadEditorPopup function in the javascript. It does its stuff and I have a 'return true' in the onclientclick call so that the next function, ShowEditCommentPopup, in the code behind, will be called. The editor pops up and I can use it just fine. When I click 'Done' the SubmitEditorPopup event is fired in the javascript and I get an error saying that the variable EditorControl is undefined. I have found that if I do not call the ShowEditCommentPopup method, the error does not occur, but then I get back to another problem I had originally, which I'm hoping that will be fixed if this problem is fixed.
I really hope that was clear enough. Thanks in advance!
You have a snippet with your javascript functions. Where does that code live? It it inside a class or function that could be getting called a second time? If so, var editorControl; could be getting run again and override your previous editorControl variable. I would put an alert right about var editorControl; to make sure.
alert( 'Should only happen once' );
var editorControl;
Since that didn't help, I guess you could try replacing
var tmp = editorControl.control.get_content();
with
tmp = document.getElementById(editorID);
in submitEditorPopup.

Find checkbox and textbox placed inside gridview using javascript

I want to get the value of check box placed inside grid view. if check box is checked, it textbox in that row should be enable and if it is again uncheked, the textbox should get clear and disabled. I asked this question few hours back but still didn't get satisfactory answer.
I tried like this.
//My grid code.
<asp:GridView ID="DeptGrid" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="DeptId" HeaderText="ID"/>
<asp:BoundField DataField="DeptName" HeaderText="Department"/>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="addToCompanyBox" onClick="EnableHODBox()" runat="server" />
</ItemTemplate>
<HeaderTemplate>
Add
</HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="hodNameBox" runat="server" Width="200px" Enabled="false"></asp:TextBox>
</ItemTemplate>
<HeaderTemplate>
Dept Head
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
//My javascript code
<script type="text/javascript">
function EnableHODBox() {
//alert('hello');
var GridView = document.getElementById('<%=DeptGrid.ClientID %>');
//var GridView = document.getElementById('');
var DeptId;
if (GridView.rows.length > 0) {
for (Row = 1; Row < GridView.rows.length; Row++) {
// DeptId = GridView.rows.cell[0];
if (GridView.rows[Row].cell[3].type == "checkbox")
// var chkbox = GridView.rows[Row].cell[3].type == "checkbox"
(GridView.rows[Row].cell[3].type).checked = true;
}
}
}
</script>
This solution is tested and works using only JavaScript (no jQuery is required for this solution!).
1. C# Part (In 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 ) + ");");
}
}
This way, we are adding the JavaScript function call on the OnChange event of every CheckBox of our GridView. What is special and we can't achieve through the HTML is that we are passing the Row Index of each one in the JavaScript function, something that we need later.
2. Some important notes for the HTML Part
Make sure that both Checkbox control and Textbox control but more importantly your GridView Control has static id by using the ClientIDMode="Static" as shown bellow:
<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
Note that in the JavaScript code, at the line:
var currentGridViewRow = GridView.rows[Row + 1];
the [Row + 1] is important to make this work and should not change.
And finally:
The following lines:
var rowTextBox = currentGridViewRow.cells[2].getElementsByTagName("input")[0];
var rowCheckbox = currentGridViewRow.cells[0].getElementsByTagName("input")[0];
The .cells[2] and .cells[0] is maybe different for you, so you have to choose the correct number in the [].
Usually, this will be the column number of your GridView starting counting from 0.
So if your CheckBox was in the first column of the GridView then 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 therefore, I used .cells[2])
You can use the onclick JavaScript instead of the OncheckedChanged event which is a CheckBox server side event.
<asp:CheckBox ID="CheckBox2" runat="server" onclick="Javascript:JSfunctionName();" />
Edit:
var GridView = document.getElementById('<%=DeptGrid.ClientID %>')
Edit: Upon your request in comment
if (GridView.rows[Row].cell[2].type == "checkbox")
{
if (GridView.rows[Row].cell[2].childNodes[0].checked)
{
GridView.rows[Row].cell[3].childNodes[0].disabled=false;// Enable your control here
}
}
I also found that the statement if (GridView.rows[Row].cell[2].type == "checkbox") results in an error, GridView.rows[Row].cell[2].type is undefined. The code I have running now is as follows:
var grid = document.getElementById('<%=grdResults.ClientID%>');
if (grid.rows.length > 0) {
for (row = 1; row < grid.rows.length; row++) {
if (grid.rows[row].cells[0].childNodes[0].checked) {
// do something here
alert('function for row ' + row);
}
}
You can define your grid like this :
<div>
<asp:GridView ID="GridView1" runat="server" Width = "550px"
AutoGenerateColumns = "false" Font-Names = "Calibri"
Font-Size = "12pt" HeaderStyle-BackColor = "LightYellow" AllowPaging ="true" ShowFooter = "true" OnPageIndexChanging = "OnPaging" PageSize = "10" >
<Columns>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText = "Name">
<ItemTemplate>
<asp:TextBox ID="txtPeriod" runat="server" CssClass="css1 mycss" Text='<%# Eval("Period")%>'
onblur="SetPostingPeriod(this)"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="#C2D69B" />
</asp:GridView>
</div>
And your Javascript Function Would be :
<script language="javascript" type="text/javascript">
/* Populating same data to all the textboxes inside grid,
once change of text for one textbox - by using jquery
*/
function SetPostingPeriod(obj) {
var cntNbr = $("#" + obj.id).val();
// var cntNbr = document.getElementById(obj.id).value;
// alert(cntNbr);
//Access Grid element by using name selector
$("#<%=GridView1.ClientID %> input[name*='txtPeriod']").each(function (index) {
if ($.trim($(this).val()) != "")
if (!isNaN($(this).val())) {
$(this).val(cntNbr);
}
});
}
</script>
This Javascript function is called onblur event of the textbox.
When this function is called at the same time it passes a parameter
which is nothing but the textbox id.
Inside javascript function by using the parameter which is the
id of the textbox we are getting the vaue.
Here is the code :
var cntNbr = $("#" + obj.id).val();
Then For each of the "txtPeriod" controls available inside the grid, we need to assign
the value of current "txtPeriod" textbox value to them.
Looping Grid to identify each "txtPeriod" available :
Here is the code :
$("#<%=GridView1.ClientID %> input[name*='txtPeriod']").each(function (index) {
});
Inside this loop we need to assign the "txtPeriod"(current/Modified) value to other
"txtPeriod" textboxes.Before assign its good practice to check is it null or NAN.
Here is the code :
if ($.trim($(this).val()) != "")
if (!isNaN($(this).val())) {
$(this).val(cntNbr);
}
Hi here you are having very easy Solution
Suppose your grid is like this :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Height="64px"
Width="389px" EnableViewState="False">
<Columns>
<asp:TemplateField HeaderText="EmployeeId">
<ItemTemplate>
<asp:Label ID="lblEmployeeId" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FirstName">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastName">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#FF66FF" ForeColor="#660033" />
</asp:GridView>
and your javascript to find controls inside your grid is
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#btnAddToGrid").click(function () {
var $grid = $('#<%=GridView1.ClientID %>');
var $row = $grid.find('tr:last').clone().appendTo($grid);
var employeeId = $row.find("span[id*='lblEmployeeId']").text();
var firstname = $row.find("span[id*='lblFirstName']").text();
var lastname = $row.find("span[id*='lblLastName']").text();
alert("ID :" + employeeId +"\n" + "Name :" + firstname +" "+ lastname );
});
});
</script>
Find controls inside the grid using java script:
for (var r = 1; r < grid.rows.length; ++r) {
var indexValue = 0; //based on browser. //IE8
var txtPeriod= grid.rows[r].cells[2].childNodes[indexValue];
if (typeof (txtPeriod.value) == "undefined")//IE9
indexValue = 1
var txtPeriod= grid.rows[r].cells[2].childNodes[indexValue];
alert(txtPeriod.value);
}
var x = document.getElementById('<%=grdResults.ClientID%>').querySelectorAll("input");
var i;
var cnt = 0;
for (i = 0; i < x.length; i++) {
if(x[i].type== "checkbox" && x[i].checked)
cnt++;
}
alert("item selected=" + cnt);

Categories

Resources