Access OwnerTableView ParentItem - javascript

It is my Vb.net code it works perfectly.
Protected Sub ChkTaxCheckedChanged1(ByVal sender As Object, ByVal e As EventArgs)
Dim chkTax As CheckBox
Dim gv1 As GridDataItem
chkTax = TryCast(sender, CheckBox)
gv1 = DirectCast(chkTax.NamingContainer, GridDataItem)
Dim txtAmount1 As Label = CType(gv1.OwnerTableView.ParentItem.FindControl("lblItemAmount"), Label)
End Sub
But now I want to achieve the same functionality in clientside using JavaScript.
Like :
function ChkTaxCheckedChanged1(sender, args) {
var check = sender.get_parent()..??????
}
Any one know how can I do this?

Try this.
<script>
function handleClick(sender,args) {
//i have used jquery so do not forgot add jquery reference
var checkboxid = sender.get_id();
var parentRow = checkboxid.parent().parent().parent().parent().parent().parent()[0].previousSibling;
$(parentRow).find('span').html('Your text comes here');
}
</script>

Related

Issues with onclick/onserverclick with buttons, HtmlButtons, and LinkButtons

I'm having an issue with the functions to be called not firing off.
I have moved from hardcoding the buttons on HTML, to using the add controls method in the cs; and I have shifted from using Button and HtmlButton to using LinkButton. However none of these seem to work. In Onserverclick and onclick not work Anup Sharma recommends using the LinkButton, and Keyvan Sadralodabai indicates that if the runat="server" is displayed in the insect element, then he control was set up wrong.
So here's a stripped down simplified version of what I'm working with:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Services;
using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;
public partial class backCodeExper : System.Web.UI.Page
{
protected void saveRecord(string recordID, string buttonId, string dropdownId)
{
PlaceHolder db = Page.FindControl("TestingCS") as PlaceHolder;
HtmlTable tbl = db.FindControl("TestTable") as HtmlTable;
HtmlTableRow tr = tbl.FindControl("TheRow") as HtmlTableRow;
HtmlTableCell tc = tr.FindControl("TheCell2") as HtmlTableCell;
DropDownList ddl = tc.FindControl(dropdownId) as DropDownList;
var status = ddl.SelectedValue.ToString();
HttpContext context = HttpContext.Current;
MySqlConnection conn = new MySqlConnection();
conn.ConnectionString = "Server=localhost; Database********; User=********; Password=********; Port=3306";
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "updatetesttable";
cmd.Parameters.AddWithValue("#param", status);
cmd.ExecuteNonQuery();
}
protected void Page_Load(object sender, EventArgs e)
{
HtmlTable myTable = new HtmlTable();
myTable.ID = "TestTable";
myTable.BorderColor = "teal";
myTable.BgColor = "black";
TestingCS.Controls.Add(myTable);
HtmlTableRow newRow;
HtmlTableCell cell;
DropDownList DropList;
LinkButton saveButton;
newRow = new HtmlTableRow();
newRow.ID = "TheRow";
cell = new HtmlTableCell();
cell.ID = "TheCell1";
DropList = new DropDownList();
DropList.ID = "StatusDD";
DropList.Items.Add(new ListItem("", "0"));
DropList.Items.Add(new ListItem("A", "1"));
DropList.Items.Add(new ListItem("B", "2"));
DropList.Items.Add(new ListItem("C", "3"));
cell.Controls.Add(DropList);
newRow.Cells.Add(cell);
cell = new HtmlTableCell();
cell.ID = "TheCell2";
cell.BgColor = "black";
saveButton = new LinkButton();
saveButton.ID = "saveButton";
saveButton.CommandName = "saveRecord";
saveButton.CommandArgument = "'1A',this.id,'StatusDD'";
saveButton.BackColor=Color.Green;
saveButton.ForeColor=Color.Cyan;
saveButton.BorderColor=Color.Maroon;
saveButton.Text = "Save";
saveButton.Visible = true;
cell.Controls.Add(saveButton);
newRow.Cells.Add(cell);
myTable.Rows.Add(newRow);
}
}
It loads the screen just fine with the simple dropdown and with the (unstylish) button (frankly the HtmlButton looks much nicer, but I'm aiming for functionality first).
When I select an item from the dropdown and then click save, the screen appears to refresh, keeping the value of the dropdown the same as that which was selected. However, when I check the database, the procedure hasn't fired. Additionally I cannot get this code segment Response.Write("<script>alert('Hello');</script>"); to execute when placed in the method/function saveRecord.
Furthermore, when I run the debugging mode and put break points in saveRecord, none of them are hit.
After inspecting element, this is what I get:
InspectElementResults
Any suggestions? What am I missing?
If I don't use LinkButton (or Button/HtmlButton with onServerClick) then I get errors saying the function isn't defined - which makes since as the function/method is define on the aspx.cs not the aspx within JS script tags.
I've got it figured out. At least, it is functional.
I was trying to set the function to pass the values I want in the format I wanted, but apparently the when you set up a LinkButton, it prefers the object and Event Args as parameters, and the object is the ListButton itself, so if that ListButton object holds the values you need in its attributes, then when the function is called you parse out the attributes you need. There's likely a better way than to assign the two values I need to CommandName and CommandArgument, but this works. (I had thought of using .Attributes.Add("ROW_ID","1a") and .Attributes.Add("DD_ID","StatusDD") ... but couldn't initially figure out how to retrieve those values from the sender object...to be investigated later, in the meantime, rolling forward with a functional solution.
...
protected void saveRecord(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
string ROW_ID = (string)lb.CommandName;
string DD_ID = (string)lb.CommandArgument;
Response.Write("<script>alert('Hello');</script>");
...
}
protected void Page_Load(object sender, EventArgs e)
{
...
saveButton.CommandName = "1a";
saveButton.CommandArgument = "StatusDD";
saveButton.Click += new EventHandler(saveRecord);
...
}
}

How to call javascript function in every row during itemdatabound

Hi I have a javascript and I need to running it every row during datagrid itemdabound. However I used the below code and it only show one time only. Would someone tell me how to solve the problem. Thanks in advance.
Code:
Private Sub dgrdConfirmed_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) _
Handles dgrdConfirmed.ItemDataBound
Select Case e.Item.ItemType
Case ListItemType.Item, ListItemType.AlternatingItem, ListItemType.EditItem
Dim dr As DataRow = CType(e.Item.DataItem, DataRowView).Row
If (Not Page.ClientScript.IsStartupScriptRegistered(Page.GetType(), "addWarning")) Then
Dim cs As ClientScriptManager = Page.ClientScript
cs.RegisterStartupScript(Page.GetType(), "addWarning",
"<script language='javascript' type='text/javascript'>addWarning
();</script>")
Else
Dim lt As New Literal
lt.Text = "<script type='text/javascript'>addWarning()</script>"
lt.Mode = LiteralMode.Transform
End If
End Select
End Sub
There is my javascript:
<script type="text/javascript" >
function addWarning(e) {
alert('addWarning');
}
</script>
I think its better to loop the gridview rows in jquery not calling javascript on databound, you can use this block of code, and do not forgot to make ClientIDMode of the gridview Static :
$("#GridViewID tr").each(function () {
var checkBox = $(this).find("input[type='checkbox']");
var textBox = $(this).find("input[type='text']");
if ($(checkBox).is(':checked')) {
if (textBox.val().length === 0) {
alert("Warning Length 0 !!");
}
else {
alert("Warning Length diffrent of 0 !!");
}
}
});

javascript not firing after setting onclientclick in gridview rowdatabound

I want to fire a javascript to confirm deleting the row.
This is the rowdatabound
Private Sub GridSlide_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridSlide.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
DirectCast(e.Row.FindControl("LinkDelete"), LinkButton).Attributes.Add("OnClientClick", "javascript:DeleteSlide('" & Convert.ToString(e.Row.RowIndex) & "')")
End If
End Sub
This is the javascript
function DeleteSlide(var_row) {
var blnResponse = null;
var strMessage = '';
try {
strMessage = 'Are you sure you want to delete this slide data?';
blnResponse = window.confirm(strMessage);
if (blnResponse) {
__doPostBack('DeleteSlide()', var_row );
}
}
catch (Err) {
alert('DeleteSlide - ' + Err.description);
}
}
but when I click the delete link button, the javascript won't fire.
What's the problem?
P.S. I tried using the CommandArgument and Container.DataItemIndex but that caused a whole lot more errors so I ended up using the rowdatabound.
Try this:
DirectCast(e.Row.FindControl("LinkDelete"), LinkButton).OnClientClick = "javascript:DeleteSlide('" & Convert.ToString(e.Row.RowIndex) & "')";

Passing Variable from JS to VB.net

I have a variable that gets a value in a js function. I need to get its value as a double into a vb.net variable.
I have tried putting the variable into a label then grabbing it from the label in vb.net as shown in the code below:
Js part.
document.getElementById("Label1").innerText = nwLat;
then in the vb part
Dim nwLat As Double
nwLat = Label1.Text
MsgBox(nwLat)
it does not work for me any ideas? the error that comes up is
Input string was not in a correct format.
Cheers!
Easiest way without any type of ajax would be to use a hidden field.
Markup:
<asp:HiddenField ID="nwLatHidden" runat="server" Value="" />
JS:
document.getElementById('nwLatHidden').value = '6.00'; // or of course the value from your function.
.NET during your postback routine:
Dim nwLat As Double
nwLat = nwLatHidden.Value
In JavaScript:
__doPostBack(
'edit',
JSON.stringify({ ID: id, Code: code, AcctNo: acctNo })
);
In VB.NET:
Protected Sub Page_Load(s As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
'...
Else
Dim eventTarget As String = Request.Form!__EVENTTARGET
Dim eventArgument As String = Request.Form!__EVENTARGUMENT
If Not eventArgument Is Nothing AndAlso Not eventTarget Is Nothing AndAlso eventTarget = "edit" Then
Dim jss As New JavaScriptSerializer()
Dim ac As AccountCode = jss.Deserialize(Of AccountCode)(eventArgument)
End If
End If
End Sub
You need to use the ClientID or the UniqueID:
document.getElementById("<%=Label1.UniqueID%>").innerText = "Hi";

Set selectedvalue for a dropdownlist using Javascript

I have a dropdownlist that is populated by a webservice using the ajax cascading dropdown. I have not been able to set the selected value using javascript. It appears that the values do not exist when the javascript runs. I placed the javascript at the bottom of the aspx page. Any ideas. Here is all of the code and the javascript I have tried.
<asp:DropDownList ID="ddlBusinessArea" runat="server"></asp:DropDownList>
<cc1:CascadingDropDown ID="CascadingDropDown1" runat="server" TargetControlID="ddlBusinessArea"
Category="BusinessArea" ServiceMethod="GetBusinessArea" ServicePath="DropDownFilter.asmx"
LoadingText="Please Wait.....">
</cc1:CascadingDropDown>
<WebMethod()> _
Public Function GetBusinessArea() As CascadingDropDownNameValue()
Dim values As New List(Of CascadingDropDownNameValue)()
Dim objData As clsDataAccess = New clsDataAccess()
Dim ds As DataSet = New DataSet
Dim SQL = "select Description from tblvalidation where MyType = 'Business Area' order by description"
ds = objData.SQLExecuteDataset(SQL)
For Each dr As DataRow In ds.Tables(0).Rows
values.Add(New CascadingDropDownNameValue(dr("Description"), dr("Description")))
Next
Return values.ToArray
End Function
<script type="text/javascript">
var e = document.getElementById("<%=ddlBusinessArea.ClientID%>");
e.options[e.selectedIndex].value = "12345"
document.getElementById("<%=ddlBusinessArea.ClientID%>").value = "12345"
document.getElementById("ctl00_ContentPlaceHolder2_ddlBusinessArea").value = "12345"
</script>
No, you cannot set the value from code-behind; you would have to use JavaScript to set the selected value if binding from a web service. The web service binds everything after the server-side process runs and can only be affected by javascript.
HTH.

Categories