javascript not firing after setting onclientclick in gridview rowdatabound - javascript

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) & "')";

Related

How do I display an image saved within a file location in a new window by clicking a gridview link? A Terms Popup (modal) should display in between

Ok for a couple of weeks I have been stuck on a problem with one of my branches legacy applications.
I have a gridview and when I click on a link in the gridview I get a relevant image displayed within a new window. A new requirement has come in requesting that after clicking on the new window, the user should be displayed a "Terms of Use" pop up which they need to agree. After agreeing, the image should load in the new window as before.
I tried creating a popup with a modal.dialog using a bit of jquery and a div and I can get this to show. However any attempt I have made to open the image from this pop up has not worked. I think the index of the gridview gets lost when displaying the modal pop up.
The application is about 12 years old (waaaay before me). It was developed in c# and asp.net web forms.
I am new to stack. Apologies about formatting. The filestream code was in there for ages. Would there be a better way of doing this? Thank you for any help in advance.
So the user clicks on link within gridview -> A pop up displays the terms with an Agree button and ideally a cancel button too. User agrees and the popup displays image.
'''<%--button in gridview.--%>
<asp:LinkButton ID="btnOpenObject" runat="server" Text="View" OnClick="OpenObjectSelect_Click"
AlternateText="Opens Object in a new window" OnClientClick="aspnetForm.target= '_blank';" ToolTip="Opens in a new window"
CssClass="btnHyperLinkEnabled">
</asp:LinkButton>
'''<%--modal pop up.--%>
<div id="ModalMessage" title="testWindow" class="divAcceptWindow" style="display: none;">
<label style="font-weight: bold" class="boldCentral">Copying and Copyright Declaration</label>
<br />
This declaration has been issued under rule 5(3).
I declare that: blah blah…
<input type="button" id="okButton" value="I Agree" name="okButton" />
</div>
<script type="text/javascript">
//script to call popup
function showdialog() {
$("#ModalMessage").dialog({ modal: true });
$("#ModalMessage").dialog({ width: 500 });
$(".ui-dialog-titlebar").hide();
scrollTo(0, 0);
}
//script to show image from serverside
$('#okButton').click(function () {
$('#ModalMessage').dialog('close');
var dataToSend = { MethodName: 'IAgree' };
var options =
{
data: dataToSend,
dataType: 'JSON',
type: 'POST',
}
$.ajax(options);
});
</script>
'''//c# (code behind)
'''//Gridview link button click event
protected void OpenObjectSelect_Click(object sender, EventArgs e)
{
LinkButton b = (LinkButton)sender;
int miIndex = Convert.ToInt32(b.CommandArgument);
LocalSearch.DetailPosition = miIndex;
miArchiveItemId = LocalSearch.ArchiveItems[LocalSearch.DetailPosition].ArchiveItemId;
//call popup
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "showdialog()", true);
}
protected void Page_Load(object sender, System.EventArgs e)
{
//hook of jquery button click with method. This is hit after clicking I agree on pop up.
if (!Page.IsPostBack) {
if (Request.Form["MethodName"] == "IAgree") // same Method Name that we are specifying on client side
{
Agree();
return;
}
}
}
'''// Get information relating to image to pass to file stream
private void Agree()
{
ArchiveItem myArchiveItem = new ArchiveItem();
miArchiveItemId = Trunks;
if (miArchiveItemId > 0)
{
//Retrieve data from DB.
myArchiveItem = mysearchMediator.GetArchiveItemByID(miArchiveItemId);
}
DigitalObjectLink(myArchiveItem);
}
//Display the image using a file stream.
//Code works to display image without the file modal
public void DigitalObjectLink(ArchiveItem myArchiveItem)
{
LinkButton OpenObject = new LinkButton();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
OpenObject = (LinkButton)GridView1.Rows[0].FindControl("btnOpenObject");
OpenObject.OnClientClick = "aspnetForm.target ='_blank';";
}
try
{
string path = ConfigurationManager.AppSettings["ImageFilePath"] + '\\' + myArchiveItem.RelativeFolderPath +
'\\' + myArchiveItem.FileName;
//string path = "C:" + '\\' + "Temp" + '\\' + myArchiveItem.FileName;
FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] ar = new byte[(int)fs.Length];
Response.AddHeader("content-disposition", "attachment;filename=" + myArchiveItem.FileName);
Response.ContentType = "application/octectstream";
ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:showdialog('" + path + "'); ", true);
fs.Read(ar, 0, (int)fs.Length);
fs.Close();
Response.BinaryWrite(ar);
Response.Flush();
Response.End();
}
catch
{
/*
** Hide Navigation & GridView & Show File Not Found Panel
*/
OpenObject.OnClientClick = "aspnetForm.target ='_self';";
this.NavigationControl1.Visible = false;
this.NavigationControl2.Visible = false;
this.GridView1.Visible = false;
lblFileNotFound.CssClass = "SearchResultsCount";
btnContactUs.Text = "Please contact PRONI quoting reference: " + myArchiveItem.Reference;
}
}

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 !!");
}
}
});

e.Item.OwnerTableView.DataKeyValues(e.Item.ItemIndex)("IdVoiture") is returning 'nothing'

i have a rad grid which contains a view column allowing me to see details in a new window.
i am adding to that button in code behind a onclick attribute.
this is my code of the radgrid_itemCreated:
If TypeOf e.Item Is GridDataItem Then
Dim btn As Button
btn = e.Item.FindControl("btnView")
Dim s As String = e.Item.OwnerTableView.DataKeyValues(e.Item.ItemIndex)("IdVoiture")
btn.Attributes.Add("onclick", "OpenViewRepport('" + e.Item.OwnerTableView.DataKeyValues(e.Item.ItemIndex)("IdVoiture") + "','4'); return false;")
End If
my problem is that
e.Item.OwnerTableView.DataKeyValues(e.Item.ItemIndex)("IdVoiture") is returning nothing.
if u have a solution please help!!

Access OwnerTableView ParentItem

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>

Getting asp:TextBox text property in codebehind from a web user control after a javascript update

Here is the scenario.
I have a simple page containing an asp:PlaceHolder.
<%# Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="TrainingPlan.aspx.vb" Inherits="TrainingPlan" %>
<%# Reference Control="ctlTask.ascx" %>
<%# Reference Control="ctlTaskheader.ascx" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">
<div class="centered">
<h2><asp:Label ID="lblPlanTitle" runat="server" Text="Plan Title"></asp:Label></h2>
<hr />
<br />
<asp:ImageButton ID="imgbtnSave" runat="server" ImageUrl="~/Images/save.ico" />
<br />
<asp:PlaceHolder ID="PlanPlaceHolder" runat="server"></asp:PlaceHolder>
</div>
</asp:Content>
The placeholder on this page is populated with several rows of the same web user control. This web user control contains several textboxes. For each textbox in this web user control I have public properties to set and get the text value. In the page load event of the web user control I am adding onClick attributes to some of those textboxes like so.
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
txtTrainingStart.Attributes.Add("onClick", "txtTrainingStart_Click(" & txtTrainingStart.ClientID & ", " & txtTask.ClientID & ");")
txtTraineeBadgeNum.Attributes.Add("onClick", "txtTraineeBadgeNum_Click(" & txtTraineeBadgeNum.ClientID & ", " & txtTask.ClientID & ", " & txtTrainingStart.ClientID & ");")
txtTrainerBadgeNum.Attributes.Add("onClick", "txtTrainerBadgeNum_Click(" & txtTrainerBadgeNum.ClientID & ", " & txtTrainingComplete.ClientID & ", " & txtTask.ClientID & ", " & txtTraineeBadgeNum.ClientID & ", " & Session.Item("isTrainer").ToString.ToLower & ");")
txtDecertifyingOfficial.Attributes.Add("onClick", "txtDecertifyingOfficial_Click(" & txtDecertifyingOfficial.ClientID & ", " & txtTrainerBadgeNum.ClientID & ", " & txtTask.ClientID & ", " & Session.Item("isDecertifyingOfficial").ToString.ToLower & ");")
End Sub
For each of those onClick events I have corresponding javascript functions.
<script type="text/javascript">
function txtTrainingStart_Click(txtTrainingStart, txtTask) {
//processing and updates to textboxes here
}
</script>
Here is the problem.
On the main page containing the placeholder I have a save button. In the click event of the save button I am looping through each of the web user controls contained in the placeholder to process and save the data.
Protected Sub imgbtnSave_Click(sender As Object, e As ImageClickEventArgs) Handles imgbtnSave.Click
For Each item As Control In PlanPlaceHolder.Controls
Dim task As ctlTask = TryCast(item, ctlTask)
If Not IsNothing(task) Then
'need updated textbox values here.
'The following line gets the original textbox value, not the updated value that I need
Dim test As String = task.trainingStart
End If
Next
End Sub
Everything I have tried I can only get the original value that was in the textbox when the page loaded. I would think that this should be simple and I am just missing something basic. I've searched google high and low for the solution but I have yet to find one. This was the closest thing I found -> Set Text property of asp:label in Javascript PROPER way.
Although that post deals with a label rather than a textbox and isn't using a placeholder containing several web user controls. From what I understand I need to POST the updates back to the server from the client but I don't know how to do this. I've tried using the Request.Form property but I couldn't seem to make that work. What am I missing?
Thank you for any help,
Rylan
EDIT
Here is the code that populates the placeholder with the web user controls as requested
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim DBConn As MySqlConnection
Dim cmd As New MySqlCommand
DBConn = New MySqlConnection(Globals.mysqlConStr)
Try
lblPlanTitle.Text = Request.QueryString("plan_name") & " Training Plan"
If Session.Item("empID") = -1 Then
empID = clsUser.getID
Else
empID = Session.Item("empID")
End If
Dim strSQL As String = "SELECT * FROM task_revs tr WHERE tr.change != 'Deleted' and tr.id_plan = " & Request.QueryString("id_plan") & " ORDER BY task_num, rev_date desc"
Dim da As New MySqlDataAdapter(strSQL, DBConn)
Dim dtAllRevs As New DataTable
da.Fill(dtAllRevs)
Dim dtCurrentRev As New DataTable
Dim lastTaskNum As String = ""
dtCurrentRev = dtAllRevs.Clone
For Each row As DataRow In dtAllRevs.Rows
If lastTaskNum <> row("task_num") Then
dtCurrentRev.ImportRow(row)
lastTaskNum = row("task_num")
End If
Next
strSQL = "SELECT * FROM checkoffs WHERE emp_id = " & empID
da = New MySqlDataAdapter(strSQL, DBConn)
Dim dtCheckoffs As New DataTable
da.Fill(dtCheckoffs)
Dim addColor As Boolean = True
Dim tabWidth As Integer
Dim Header As ctlTaskHeader = LoadControl("ctlTaskHeader.ascx")
PlanPlaceHolder.Controls.Add(Header)
For Each row As DataRow In dtCurrentRev.Rows
Dim newRow As ctlTask = LoadControl("ctlTask.ascx")
tabWidth = 0
newRow.id_Task = row("id_Task")
newRow.taskNum = row("task_num")
newRow.task = row("task")
If row("is_header") = True Then
If row("task_num").ToString.EndsWith(".0") And row("task_num").ToString.Split(".").Count = 2 Then
newRow.taskBold = True
newRow.taskItalic = True
Else
newRow.taskForeColor = Drawing.Color.Blue
newRow.taskItalic = True
tabWidth += 10
End If
Else
tabWidth += 10
End If
For i As Integer = 0 To row("task_num").ToString.Split(".").Count - 3
tabWidth += 10
Next
newRow.TabSize = tabWidth
If Not IsDBNull(row("task_level")) Then
For i As Integer = 0 To row("task_level") - 1
newRow.taskLevel = newRow.taskLevel & "*"
Next
End If
If addColor = True Then
newRow.taskNumBackColor = Drawing.Color.LightGray
newRow.taskLevelBackColor = Drawing.Color.LightGray
newRow.taskBackColor = Drawing.Color.LightGray
newRow.trainingStartBackColor = Drawing.Color.LightGray
newRow.trainingCompleteBackColor = Drawing.Color.LightGray
newRow.traineeBadgeNumBackColor = Drawing.Color.LightGray
newRow.trainerBadgeNumBackColor = Drawing.Color.LightGray
newRow.decertifyingOfficialBackColor = Drawing.Color.LightGray
End If
addColor = Not addColor
For Each checkoff As DataRow In dtCheckoffs.Rows
If checkoff("id_task") = row("id_task") Then
If Not IsDBNull(checkoff("training_start")) Then
newRow.trainingStart = checkoff("training_start")
End If
If Not IsDBNull(checkoff("training_complete")) Then
newRow.trainingComplete = checkoff("training_complete")
End If
If Not IsDBNull(checkoff("trainee_badge")) Then
newRow.traineeBadgeNum = checkoff("trainee_badge")
End If
If Not IsDBNull(checkoff("trainer_badge")) Then
newRow.trainerBadgeNum = checkoff("trainer_badge")
End If
If Not IsDBNull(checkoff("decertifying_official")) Then
newRow.decertifyingOfficial = checkoff("decertifying_official")
newRow.taskNumBackColor = Drawing.Color.LightSalmon
newRow.taskLevelBackColor = Drawing.Color.LightSalmon
newRow.taskBackColor = Drawing.Color.LightSalmon
newRow.trainingStartBackColor = Drawing.Color.LightSalmon
newRow.trainingCompleteBackColor = Drawing.Color.LightSalmon
newRow.traineeBadgeNumBackColor = Drawing.Color.LightSalmon
newRow.trainerBadgeNumBackColor = Drawing.Color.LightSalmon
newRow.decertifyingOfficialBackColor = Drawing.Color.LightSalmon
End If
End If
Next
If row("is_header") = True And PlanPlaceHolder.Controls.Count > 1 Then
Dim newLine As LiteralControl = New LiteralControl("<br/>")
PlanPlaceHolder.Controls.Add(newLine)
End If
PlanPlaceHolder.Controls.Add(newRow)
Next
Catch ex As Exception
clsLog.logError(ex)
Finally
DBConn.Close()
End Try
EDIT 2
I thought it might also be important to show how I am making updates to the textboxes in my javascript functions
function txtTrainingStart_Click(txtTrainingStart, txtTask) {
var currentdate = new Date();
var datetime = (currentdate.getMonth() + 1) + "/" + currentdate.getDate() + "/" + currentdate.getFullYear() + " " + getTimeAMPM();
txtTrainingStart.value = datetime;
txtTrainingStart.style.backgroundColor = "yellow";
}
Edit 3:
The below code will work for static controls, but dynamically-created controls will not be preserved on postback. You will need to store the updated values so they can be retrieved on postback somehow (e.g. a Session variable or HiddenField). If possible, I would create the controls statically and populate them in page_load, hiding controls with no data - this would allow you to get the values on postback as below.
Hmm...I set up a super simplified version of your code and ran it pretty much as is (without the database function), and it seems to be working fine.
Here is the simplified version I used:
<asp:Content id="Content1" ContentPlaceHolderID="MainContent" runat="server">
<asp:ImageButton ID="imgbtnSave" runat="server"></asp:ImageButton>
<asp:PlaceHolder ID="PlanPlaceHolder" runat="server">
<asp:TextBox runat="server" ID="txtTrainingStart" value="before" ></asp:TextBox>
</asp:PlaceHolder>
</asp:Content>
Javascript:
function txtTrainingStart_Click(txtTrainingStart, txtTask) {
var currentdate = new Date();
var test = "after";
txtTrainingStart.value = test;
txtTrainingStart.style.backgroundColor = "yellow";
}
VB:
Protected Sub imgbtnSave_Click(ByVal sender As Object, ByVal e As ImageClickEventArgs Handles imgbtnSave.Click
For Each item As TextBox In PlanPlaceHolder.Controls
'need updated textbox values here.'
Debug.WriteLine(item.ID)
Debug.WriteLine(item.Text)
Next
End Sub
I'm getting the updated value of the textbox, so you should be able to pass that value to a function and do whatever operations you need.
Let me know if I'm missing something.
Edit 2: I just had a thought--can you check if page_load is being called after you click the save button? I wonder if it is overwriting your updated values with the original values again.
If it is, I would wrap the database functionality in page_load with a postback check:
If Not IsPostBack
' connect to database'
' populate placeholder'
End If
I have figured it out. I was on the right track using Request.Form I just didn't fully understand how to use it yet.
New code for my save button
Protected Sub imgbtnSave_Click(sender As Object, e As ImageClickEventArgs) Handles imgbtnSave.Click
Dim coll As NameValueCollection
coll = Request.Form
For x = 0 To coll.Count - 1
Response.Write("Key = " & coll.GetKey(x) & " Value = " & coll(x) & "<br />")
Next
End Sub
The loop outputs all the control keys and updated values from the postback like so.
Key = ctl00$MainContent$ctl01$txtTrainingStart Value = 8/1/13
Key = ctl00$MainContent$ctl01$txtTrainingComplete Value = 8/2/13
Key = ctl00$MainContent$ctl02$txtTrainingStart Value = 8/3/13
Key = ctl00$MainContent$ctl02$txtTrainingComplete Value = 8/4/13
I use a hidden field to store a database row id with each dynamically created web user control. From that point it's easy to insert the updated values into my database.

Categories