onclick for checkbox returning undefined - javascript

I have a GridView where a column is a checkbox. In the database these checkboxes are dafaulted to one. So if the user unticks the checkbox I call a web method to update the database.
GridView code:
<asp:GridView style="width:75%"
ID="gvCVRTDetails"
ShowHeaderWhenEmpty="true"
CssClass="tblResults"
runat="server"
OnRowDataBound="gvCVRTDetails_RowDataBound"
DataKeyField="ID"
AutoGenerateColumns="false"
allowpaging="false"
AlternatingRowStyle-BackColor="#EEEEEE">
<HeaderStyle CssClass="tblResultsHeader" />
<Columns>
<asp:BoundField DataField="ChecklistID" HeaderText="ID" ></asp:BoundField>
<asp:BoundField DataField="Description" HeaderText="Checklist Items"></asp:BoundField>
<asp:BoundField DataField="Checked" HeaderText="OK"></asp:BoundField>
</asp:GridView>
Code behind:
protected void gvCVRTDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
lookupCVRT work = (lookupCVRT)e.Row.DataItem;
GridView gv = sender as GridView;
e.Row.Attributes.Add("ID", "gvCVRTDetails_" + work.ID);
e.Row.Cells[0].Attributes.Add("onclick", "event.stopPropagation();");
HtmlGenericControl lnkShowHide = (HtmlGenericControl)e.Row.FindControl("lnkShowHide");
HyperLink ChecklistItem = (HyperLink)e.Row.FindControl("ID");
bool bAll = work.Checked;
e.Row.Cells[4].Text = "<input type=\"checkbox\" " + ((bAll) ? "checked" : "") + "/>";
e.Row.Cells[4].Attributes.Add("onclick", "UpdateCheckedBox(" + work.ID.ToString() + ", this.Checked);");
}
}
Javascript function:
function UpdateCheckedBox(ID, Checked) {
alert(Checked);
PageMethods.UpdateCheckUserControl(ID, Checked, OnUpdateSuccess, OnUpdateFail);
}
But calling this.Checked is returning undefined instead of true or false. I also tried this.Value but that doesn't work either

You should change the last line to following
e.Row.Cells[4].Attributes.Add("onclick", "UpdateCheckedBox('" + work.ID.ToString() + "', this.checked);");
Because if you don't cover quotes around work.ID.ToString(), it will be treated as a variable there and its wrong. Also as others suggested, use checked instead of 'Checked'.
UPDATE
e.Row.Cells[4].Text = "<input onclick=UpdateCheckedBox('" + work.ID.ToString() + "', this.checked) type=\"checkbox\" " + ((bAll) ? "checked" : "") + "/>";

Answer is changing from the checkbox from boundfield to TemplateField:
<asp:TemplateField HeaderText ="OK?" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkChecked" runat="server" Checked='<%# Convert.ToBoolean(DataBinder.Eval(Container.DataItem, "Checked")) %>' ></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
Then in the code behind use:
CheckBox chkChecked = e.Row.FindControl("chkChecked") as CheckBox;
chkChecked.Attributes.Add("onclick", "UpdateCheckedBox(" + work.ID.ToString() + ", this.checked);");
Much easier to select the checkbox instead of the cell like I was trying to do.

Related

How to get JavaScript variable value in C# code behind

I have a gridview with a column with customised button.
When I click the button, user contact is asked for through JavaScript and then the contact is passed on to rowCommand event of gridview for some operation.
I am using Hiddenfield as a gridview column but there is something going wrong in setting and getting the value.
JavaScript code:
<script type="text/javascript">
function validateContact()
{
var contact = prompt("Please enter your contact number.");
if (isEmpty(contact) && !isNumber(contact) && contact.length != 10)
alert("Invalid contact.");
return;
else
document.getElementById("hiddenCustomerContact.ClientID").value = contact;
}
</script>
asp code:
<asp:GridView ID="gridSearchWorker" runat="server" AutoGenerateColumns="false" OnRowCommand="gridSearchWorker_OnRowCommand" OnRowDataBound="gridSearchWorker_RowDataBound">
<Columns>
<asp:BoundField DataField="WORKER" HeaderText="WORKER" SortExpression="WORKER">
<ItemStyle Width="12%" />
</asp:BoundField>
<asp:TemplateField HeaderText = "" ItemStyle-Width="5%">
<ItemTemplate>
<asp:Button ID="btnGetContact" runat="server" Text="Get Contact" CommandName="GetContact" OnClientClick="validateContact();" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CONTACT" HeaderText="CONTACT" SortExpression="CONTACT">
<ItemStyle Width="12%" />
</asp:BoundField>
<asp:TemplateField HeaderText = "" ItemStyle-Width="5%">
<ItemTemplate>
<asp:HiddenField ID="hiddenCustomerContact" runat="server"/>
</ItemTemplate>
<ItemStyle Width="0.0001%" />
</asp:TemplateField>
</Columns>
</asp:GridView>
c# code behind:
protected void gridSearchWorker_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "GetContact")
{
OleDbConnection conn = new OleDbConnection(cs);
//ask for contact and check if any feedback pending
HiddenField hiddenCustomerContact =
e.Row.FindControl("hiddenCustomerContact") as HiddenField; //getting error in this line
string score = hiddenCustomerContact.Value;
int n = Int32.TryParse(score, out val);
string customerContact = "";
//check if any feedback pending
int pendingCount;
if (pendingCount > 0)
{
//ask to give feedback
}
else
{
//show worker contact
}
}
}
Hi it should work like this:
you can assign some value to the hidden variable as
<script type="text/javascript">
var somefunction = function () {
var hdnfldVariable = document.getElementById('hdnfldVariable');
hdnfldVariable.value = 'value from javascript';
}
</script>
in code behind you can read this field variable:
string variable = hdnfldVariable.Value;

How to enable double and single click for GridView row in Asp.net c#

I have a GridView row in Asp.net, single click event is working on it
I need to add a Double Click event on my Grid rows.
How can I do that?
Please help me.
Pease follow the below post, this will be really very helpful to you.
Clickable and Double Clickable Rows with GridView and DataList Controls
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Get the LinkButton control in the first cell
LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
// Get the javascript which is assigned to this LinkButton
string _jsSingle = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "");
// To prevent the first click from posting back immediately
// (therefore giving the user a chance to double click) pause the
// postback for 300 milliseconds by using setTimeout
_jsSingle = _jsSingle.Insert(11, "setTimeout(\"");
_jsSingle += "\", 300)";
// Add this javascript to the onclick Attribute of the row
e.Row.Attributes["onclick"] = _jsSingle;
// Get the LinkButton control in the second cell
LinkButton _doubleClickButton = (LinkButton)e.Row.Cells[1].Controls[0];
// Get the javascript which is assigned to this LinkButton
string _jsDouble = ClientScript.GetPostBackClientHyperlink(_doubleClickButton, "");
// Add this javascript to the ondblclick Attribute of the row
e.Row.Attributes["ondblclick"] = _jsDouble;
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridView _gridView = (GridView)sender;
// Get the selected index and the command name
int _selectedIndex = int.Parse(e.CommandArgument.ToString());
string _commandName = e.CommandName;
switch (_commandName)
{
case ("SingleClick"):
_gridView.SelectedIndex = _selectedIndex;
this.Message.Text += "Single clicked GridView row at index " + _selectedIndex.ToString() + "<br />";
break;
case ("DoubleClick"):
Response.Write("<script type='text/javascript'>detailedresults=window.open('Patient//PatientDicomViewPage.aspx');</script>");
// Response.Redirect("ViewPatient.aspx");
this.Message.Text += "Double clicked GridView row at index " + _selectedIndex.ToString() + "<br />";
break;
}
}
Design of grid
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#DEDFDE"
BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical"
OnRowDataBound="GridView1_RowDataBound" OnRowCommand="GridView1_RowCommand">
<FooterStyle BackColor="#CCCC99" />
<Columns>
<asp:ButtonField Text="SingleClick" CommandName="SingleClick" Visible="false"/>
<asp:ButtonField Text="DoubleClick" CommandName="DoubleClick" Visible="false"/>
</Columns>
<RowStyle BackColor="#F7F7DE" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
<asp:Label id="Message" runat="server" ForeColor="Red" Font-Bold="true"></asp:Label>
Here is another solution that just handles double clicks:
On the front end add these
OnRowDataBound="YourGrid_RowDataBound" OnRowEditing="YourGrid_RowEditing"
On the backend
protected void YourGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["ondblclick"] = Page.ClientScript.GetPostBackClientHyperlink(YourGrid, "Edit$" + e.Row.RowIndex);
e.Row.Attributes["style"] = "cursor:pointer";
}
}
protected void YourGrid_RowEditing(object sender, GridViewEditEventArgs e)
{
// Excecute your code here
// Example:
// get the grid
GridView gv1 = (GridView)sender;
//get the row
GridViewRow gvr1 = (GridViewRow)gv1.Rows[e.NewEditIndex];
// get data from a cell for the row
string dataInCellOne= gvr1.Cells[1].Text.ToString();
}

ASP.NET Gridview how to Access Checkbox on field

I have an ASP.NET Web Forms page and I have a field where I load some data from a SQL Server Database.
I also add a Checkbox control to the field this way:
if (!e.Row.Cells[8].Text.Equals("---"))
{
CheckBox chkbox = new CheckBox();
chkbox.ID = "SelectedTel8_" + e.Row.Cells[1].Text;
chkbox.Text = e.Row.Cells[8].Text;
e.Row.Cells[8].Controls.Add(chkbox);
chkbox.Attributes.Add("OnClick", "javascript:selectCheckBox(this);");
chkbox = null;
}
if (!e.Row.Cells[9].Text.Equals("---"))
{
CheckBox chkbox = new CheckBox();
chkbox.ID = "SelectedTel9_" + e.Row.Cells[1].Text;
chkbox.Text = e.Row.Cells[9].Text;
e.Row.Cells[9].Controls.Add(chkbox);
chkbox.Attributes.Add("OnClick", "javascript:selectCheckBox(this);");
chkbox = null;
}
if (!e.Row.Cells[10].Text.Equals("---"))
{
CheckBox chkbox = new CheckBox();
chkbox.ID = "SelectedTel10_" + e.Row.Cells[1].Text;
chkbox.Text = e.Row.Cells[10].Text;
e.Row.Cells[10].Controls.Add(chkbox);
chkbox.Attributes.Add("OnClick", "javascript:selectCheckBox(this);");
chkbox = null;
}
On this page, I also create a button row:
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="ButtonSendSMS" runat="server" Text="EnviarSms" CommandName="EnviarSms1" OnClientClick="javascript:SendSmsTel(this);" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
It calls a javascript function called "SendSmsTel".
What I need to do is:
Whenever the user clicks the button, I need to retrieve the information from the other fields on that row to use it in other operations.
the problem is that I cant find a way to access that elements of that row. When I have controls on a given row, I ID'ed them and then I Could use
window.document.getElementById()
But what about data fields without controls?
[link]I tried a lot of things but none work. Don't know what I have been doing wrong:
[link]How to access gridview cell value with javascript
[link]How to get Column Value for a given Row within GridView using javascript in asp.net?
[link]Why is Container.DataItem being passed as a string literal?
How do I access the content of the row where the button was clicked?
If you could, teach me in C# and JavaScript.
Thanks.
In C# :
- you can fire a OnClick Event, for example
<asp:TemplateField HeaderText="Product>
<ItemTemplate>
<asp:LinkButton ID="lb_filter" ToolTip="Product" runat="server" CommandArgument='<%#Eval("ProductID") %>'
OnClick="lb_filter_Click"><img src="resources/images/search_button.png" style="width:22px;" /></asp:LinkButton>
</ItemTemplate>
<HeaderStyle HorizontalAlign="center" Width="70px" />
<ItemStyle HorizontalAlign="center" Width="70px" />
</asp:TemplateField>
In code :
protected void lb_filter_Click(object sender, EventArgs e)
{
var linkbuntton = (LinkButton)sender;
if (linkbuntton != null)
{
int ProductId =int.Parse(linkbuntton.CommandArgument);
var objProduct = _entities.Products.Where(o => o.ProductID == ProductId).FirstOrDefault();
//TODO : so now you have got content of that row
}
}
or you can foreach in gridview, for example with checkbox :
foreach (GridViewRow row in gvAwards.Rows)
{
var cb = (CheckBox)row.FindControl("cbCheck");
if (cb.Checked)
{
int _ID = int.Parse(gvAwards.DataKeys[row.RowIndex].Value.ToString());
var item = _entities.Awards.Where(c => c.AwardsID == _ID).FirstOrDefault();
//TODO: so now, you can get contents of that row
}
}
In code Javascript :
you can add unique class for each control in a row with prefix/surfix is keyId
for example :
<asp:TemplateField HeaderText="add">
<ItemTemplate>
<a href="#" class="href_<%# Eval("BannerLocationID") %>" onclick="ShowinsertlistForm('<%# Eval("BannerLocationID") %>')" >
<img src="resources/images/add.png" style="width:22px;" /></a>
</ItemTemplate>
<HeaderStyle HorizontalAlign="center" Width="60px" />
<ItemStyle HorizontalAlign="center" Width="60px" />
</asp:TemplateField>
in javascript code :
you can easy get element by css class
function ShowinsertlistForm(Id)
{
var href = document.getElementsByClassName('href_'+Id);
var checkbox = document.getElementsByClassName('checkbox_'+Id);
//TODO : some thing like that
}

getElementByID for templateField TextBox

i have used RowDataBound for gridview. Below is my C# code
protected void gvParameterValue_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblLocID = (Label)e.Row.FindControl("lblLocationID");
if(condition)
{
TextBox txtBox = (TextBox)e.Row.FindControl("txtValue");
txtBox.Attributes.Add("onchange", "ValueOnChange();");
}
}
}
Asp.Net code for gridview
<asp:UpdatePanel ID="updatePanel" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSave" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:GridView ID="gvParameterValue" SkinID="GridView" runat="server" OnRowDataBound ="gvParameterValue_RowDataBound" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Location Name">
<asp:TemplateField HeaderText="Parameter Value">
<ItemTemplate>
<asp:TextBox ID="txtValue" SkinID="fineLineTextBox" TabIndex="1" runat="server" AutoPostBack="false"></asp:TextBox>
<%--<asp:TextBox ID="TextBox1" SkinID="fineLineTextBox" TabIndex="1" runat="server" OnTextChanged="textBox1_textChanged" AutoPostBack="true"></asp:TextBox>--%>
<asp:Label ID="lblPreDayVal" runat="server" Text='<%# Bind("PreviousValue") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate >
</asp:UpdatePanel>
js function as below and i have a problem
function ValueOnChange()
{
var val = document.getElementById('lblPreDayValue').value;
}
It gives error "Microsoft JScript runtime error: Object required"
i have tried all possible solutions from net but nothing works...
You've called getElementById on the ID lblPreDayValue. In your ASP.NET markup you've called it lblPreDayVal.
You might also want to use ClientID to ensure you get the correct ID generated by .NET
You can pass the ClientID from the server-side during the binding step in the gvParameterValue_RowDataBound method like this :-
TextBox txtBox = (TextBox)e.Row.FindControl("txtValue");
Label lblVal = (Label)e.Row.FindControl("lblPreDayVal");
txtBox.Attributes.Add("onchange", "ValueOnChange('" + lblVal.ClientID + "');");
And then inside the ValueOnChange method definition, pass the argument as cid (lets say).
function ValueOnChange(cid)
{
var val = document.getElementById(cid).innerHTML;
}
Try passing values at the RowBound event of gridview , You are trying to access getElementbyId('lblLocID') is not going to work because it's id will be change when row renders .
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblLocID = (Label)e.Row.FindControl("lblLocationID");
Label lblPreDayValue =(Label)e.Row.FindControl("lblPreDayValue");
if (lblLocID.Text.Equals("154") || lblLocID.Text.Equals("168") || lblLocID.Text.Equals("178"))
{
TextBox txtBox = (TextBox)e.Row.FindControl("txtValue");
txtBox.Attributes.Add("onchange", "ValueOnChange(" + lblPreDayValue.ClientID + ");");
}
}
After passing ClientID to function
//Or you can directly pass the value of label and assign .
function ValueOnChange(ClntID)
{
var val = document.getElementById('ClntID').innerHTML;
}
Try to use
function ValueOnChange()
{
var val = document.getElementById('#<%= lblPreDayVal.ClientID %>').innerHTML;
}
If the above din work then
function ValueOnChange()
{
var val = document.getElementById('lblPreDayVal').innerHTML;
}

set value of dropdown lists in Gridview with javascript

I have a dropdownlist and a gridview with a drop down list in every row. I have removed other cols in Grid for simplicity.
Whenever a new value in the dropdownlist is selected I would like to set all of the dropdownlists in the gridview to that same value via javascript. (Yea both the dropdownlist outside the gird and the ones inside the grid are populated by the same data source)
The dropdownlist:
<asp:DropDownList onchange="javascript:onJDSelection();" ID="DropDownList3" runat="server"
DataSourceID="SqlDataSource4" DataTextField="circt_cstdn_nm"
DataValueField="circt_cstdn_user_id">
</asp:DropDownList>
The GridView:
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" onrowdatabound="GridView2_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Change to Job Designer" SortExpression="circt_Cstdn_nm">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("circt_Cstdn_nm") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddl_jd" runat="server" DataSourceID="SqlDataSource4" DataTextField="CIRCT_CSTDN_NM"
DataValueField="CIRCT_CSTDN_user_id"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My current attempt:
function onJDSelection() {
var jd = document.getElementById('ctl00_MAIN_DropDownList3').Text;
var grid = document.getElementById('ctl00_MAIN_GridView2');
for (var i = 1; i < grid.rows.length; i++) {
grid.rows[i].cells[0].getElementsByTagName("*")[1].selectedText = jd;
}
}
any ideas?
Thanks!
Update: I tried this.
<script type="text/javascript">
function onJDSelection() {
var jd = document.getElementById('ctl00_MAIN_DropDownList3').Text;
var dropDowns = jQuery('input[id^=ctl00_MAIN_GridView2_ddl_jd]');
alert("test");
alert(dropDowns);
var i = 0;
dropDowns.each(function () {
alert(i);
i++;
jQuery('#' + jQuery(this) + ':first-child').text(jd);
});
}
</script>
When clicking on the dropdown I get an alert that says "test" and an alert that says "[Object object]" However nothing happens with the dropdowns in the grid and the alert(i) never fires.
I suggest to change the selected values for the dropdownlists from code behind like this:
protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (GridViewRow gvRow in GridView2.Rows)
{
Control ctrl = gvRow.FindControl("ddl_jd");
DropDownList ddl = ctrl as DropDownList;
if (ddl != null)
ddl.SelectedIndex = DropDownList3.SelectedIndex;
}
}
Also make sure to set AutoPostBack="true" for DropDownList3.
Another approach (that is not very clean or simple) is to add the following code into the Page_Load method (and remove the script block containing onJDSelection function from the .aspx file):
if (!Page.IsPostBack)
{
string functionContent = "<script language=javascript> function onJDSelection()" +
"{ var selectedIndex = document.getElementById('" + DropDownList3.ClientID + "').selectedIndex;" +
"var grid = document.getElementById('" + GridView2.ClientID + "'); " +
"for (var i = 1; i < grid.rows.length; i++) " +
"{ var selObj = grid.rows[i].cells[0].getElementsByTagName(\"*\")[0]; selObj[selectedIndex].selected = true;} "+
"}</script>";
Page.RegisterStartupScript("MyScript", functionContent);
DropDownList3.Attributes.Add("onchange", "onJDSelection()");
}.
Note that is this case the ID used for retrieving DropDownList3 and GridView2 in javascript are sent from code behind as is not very safe to rely on server control ID's generated by ASP .NET. In case you want to save the dropdownlists values (that are changed using javascript) you will also need additional code.
It works based on the following body for aspx page:
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList3" runat="server"
DataSourceID="SqlDataSource1" DataTextField="circt_cstdn_nm"
DataValueField="circt_cstdn_user_id" onselectedindexchanged="DropDownList3_SelectedIndexChanged">
</asp:DropDownList>
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
onrowdatabound="GridView2_RowDataBound" DataKeyNames="circt_cstdn_user_id">
<Columns>
<asp:TemplateField HeaderText="Change to Job Designer" SortExpression="circt_Cstdn_nm" >
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("circt_Cstdn_nm") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddl_jd" runat="server" DataSourceID="SqlDataSource1" DataTextField="CIRCT_CSTDN_NM"
DataValueField="CIRCT_CSTDN_user_id"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"
SelectCommand="SELECT * FROM [test]"></asp:SqlDataSource>
</div>
</form>
If possible, I'd suggest that you use jQuery. It has a multitude of partial name selectors and input selectors that you can use to get all of your DropDowns. You could use something like:
function onJDSelection() {
var jd = document.getElementById('ctl00_MAIN_DropDownList3').Text;
var dropDowns = jQuery('input[id^=ctl00_MAIN_GridView2_ddl_jd]');
dropDowns.each(function() {
jQuery('#' + jQuery(this) + ':first-child').text(jd);
});
}

Categories