Sever side created button doesn't fire click event - html

Following the example answer found at ASP.NET/HTML: HTML button's onClick property inside ASP.NET (.cs)
The button "Click Me!" works if I add the button html normally on the page. If I add it to the page using ASP.NET VB.NET InnerHTML, the click doesn't fire. Does anyone know why?
Below is after the HTML is rendered.
Below is the ASP.NET VB.NET code:
strTbl1 = "<table style='text-align:Left;'><tr class='spaceUnder'>"
strTbl1 = strTbl1 + "<td style=''><button id='Button1' OnServerClick='Button1_OnClick' runat='server'>Click me!</button></td></tr>"
strTbl1 = strTbl1 + "</table>"
Task1Assignees.InnerHtml = strTbl1
I have attempted <input type=button..., asp:Button .. and etc but all don't register click event. If I attempt an asp type then I get a JavaScript error as well.
UPDATE:
Server Side function
Protected Sub Button1_OnClick(ByVal sender As Object, ByVal e As EventArgs)
MsgBox("hi")
End Sub
FINAL FIX
So using example from Dynamic created Buttons VB.Net with Loop and from the accepted answer below, I was able to fix my code like so
Page_Load (outside the IsPostBack check)
Task1Assignees.Controls.Clear()
For j As Integer = 0 To System.Web.HttpContext.Current.Session("intAssignees") Step 1
Dim btn As New Button
btn.Text = "Mark Completed"
btn.CssClass = "btn btn-success"
btn.ID = "btnAssignee" & j
AddHandler btn.Click, AddressOf Send
Task1Assignees.Controls.Add(btn)
Next
Button Creation
System.Web.HttpContext.Current.Session("intAssignees") = ds1.Tables(0).Rows.Count
Task1Assignees.Controls.Clear()
For j As Integer = 0 To System.Web.HttpContext.Current.Session("intAssignees") Step 1
Dim btn As New Button
btn.Text = "Mark Completed"
btn.Cssclass = "btn btn-success"
btn.ID = "btnAssignee" & j
AddHandler btn.Click, AddressOf Send
Task1Assignees.Controls.Add(btn)
Next
Function for button
Sub Send()
Response.Redirect("~\Home.aspx")
End Sub

That won't work, but you can create server-side HTML controls instead.
var table = new HtmlTable();
var row = new HtmlTableRow();
var cell = new HtmlTableCell();
var btn = new LinkButton();
btn.Text = "Click Me!";
btn.Click += Button1_OnClick;
cell.Controls.Add(btn);
row.Cells.Add(cell);
table.Rows.Add(row);
Task1Assignees.Controls.Add(table);

1) Try change that button to an ASP:Button object and not an HTML button.
2) If that doesn't work, change view from code to design view, then double click the button and Visual Studio should automatically create the method (or in your case, direct you to the method where you'll execute code for the button click.)
3) If that doesn't work, drag and drop a button from toolbar and double click and repeat step 2. <-This should definitely work

Related

Click html button and enable button in Visual Basic

I'm new with Visual Basic and I have a simple app in visual basic using the WebBrowser component, the web page that is loaded has a button (html) and I would like to enable a button of visual basic when press that html button, I have no idea how to achieve this, I read that I can do this but not how, I searched here in SO and youtube but I didn't found what I'm looking for, can you help me to achieve this please?, thanks.
<button type="button" id="login">Login</button>
I can simplify that for you :), and its very easy.
What I am using is the following:
1- HTML page "Index.html" with one simple javascript function called "CheckStat" to change your buttons value.
2- Form with 1 Button, 1 WebBrowser and 1 Timer.
"Index.html"
<!DOCTYPE html>
<html>
<head>
<title>HTML - VB.NET</title>
<script>
function CheckStat(){
document.getElementById("login").innerHTML = "clicked";
}
</script>
</head>
<body>
<button type="button" id="login" onclick="CheckStat();">Login</button>
</body>
</html>
This is what I did from Visual Studio, first this is my code:
"Form1.vb"
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'I am using localhost, it's not required you can simply put your HTML file on your Desktop or you can get it from any website.
WebBrowser1.Url = New Uri("http://localhost/stackoverflow.com/AN03/index.html")
'Enalbe Timer
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Try
'Get that our HTML button, as you see i am using GetElementById("HTML BUTTON ID HERE")....
Dim loginbtn = WebBrowser1.Document.GetElementById("login")
If loginbtn.InnerHtml = "clicked" Then
'Disable what button you want to disable...
Button1.Enabled = False
'Change HTML text to something else because every 100 interval it checks again and again...
loginbtn.InnerHtml = "click me"
'This message box just shows you were clicked or not. you can simply remove it
MessageBox.Show("Clicked me is enabled")
End If
Catch ex As Exception
'for any problem, it shows this message box to the user and tells him/her what was wrong....
MessageBox.Show(ex.Message)
End Try
End Sub
End Class
Because you said i am new for VB.net, let me tell you what is going on. when you click on Button1 the WebBrowser will load that file for you, and also enables Timer1.
now browser loaded the page and timer1 run that code every 100 intervals 1 Sec = 1000 interval, first it searches for all Element from HTML page which its ID equals to "login" and it returns to the variable called "loginbtn".
then it checks for its value (The text or caption that appears on HTML button) if it's equal to "clicked" then it means user click the HTML button.
Then it disables Button (VB's Button), changes HTML'S Button value to "click me again" and shows message box...
For any problem, it shows this message box to the user and tells him/her what was wrong....
Yes you can do it, but i used timer because it check it every i.e 1 min or 1 hour or any time you set...I updated for you and i created this function please let me know if you don't understand it or anything else....
you can disable or remove your timer, add one button and add this simple code to it which i put it in Button2...
one more thing, if you see i create my function as a Private, so you can't called from any other form, or class, etc.
you can change it to Public so you can use it anywhere in your app.
How do i call it then? .
like this : Form1.CheckStatByid("login"). updated code is :
Dim _Stat As Boolean = False
Private Function CheckStatByid(ByVal htmlid)
' Check sended paramiter
' IF it has no value then we need to end our function,
' Else we can check its value...
If htmlid <> Nothing Then
Try
'Get that our HTML button, as you see i am using GetElementById("HTML BUTTON ID HERE")....
Dim loginbtn = WebBrowser1.Document.GetElementById(htmlid)
'Check loginbtn if it has a value or NOT
If loginbtn <> Nothing Then
If loginbtn.InnerHtml = "clicked" Then
'Change HTML text to 'click me again', but you can change it to anything else...
loginbtn.InnerHtml = "click me again"
_Stat = True
Else
'If we have some value (ID) returns from our HTML, but it doesn't match our ID which is "login"
MessageBox.Show("loginbtn variable has deffrent id OR button is not clicked yet. and we end the try...catch")
Exit Try
End If
Else
'We don't find any elements from our HTML page...
MessageBox.Show("loginbtn variable has no value. and we end the try...catch")
Exit Try
End If
Catch ex As Exception
'for any proble it shows this message box to user and tell him/her what was wrong....
MessageBox.Show(ex.Message)
End Try
Else
' We don't have any ID to check...
MessageBox.Show("Please recall the function with an ID...")
End If
' Retuen _Stat : if the IF statment was true then it returns TRUE, else it returns FASLE
Return _Stat
End Function
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
' How to use our function? its easy
' check it with some value.
If CheckStatByid("login") = True Then
' User Clicked the HTML button, we can now disable our button or do any thing else...
Button1.Enabled = False
Else
' User doesn't clicked the button or any other stat has been returned from our function.
' Message box will show for any stat...
' if you like, you can simply remove those message box from function and put them here...
MessageBox.Show("HTML page is not loaded or user doesn't clicked...")
End If
End Sub
Hope you understand it. and I am sorry for any grammar or spelling error.
...

error 2110 setfocus on bound combobox

I use the following code on the click event of a button on my form:
...
'Make the appropriate location appear in the combobox
For i = 0 To cboLocations.ListCount - 1
If Me.cboLocations.Column(0, i) = locindex Then
Me.cboLocations.SetFocus
Me.cboLocations.Value = Me.cboLocations.Column(1, i)
Me.cboLocations.Selected(i) = True
Exit For
End If
Next i
...
This works as expected when using the button, but when I attempt to execute the very same code in some other subroutine, the SetFocus line triggers the error 2110: Access can't move the focus to the control cboLocations. That doesn't make sense to me. Why does it work in one place and not in another?

How to get elements added in html editor

I have an html editor (ckeditor) in my vb.net application. after the user adds controls(buttons, input, text...) in the editor, he clicks on a button. after clicking that button i want to take all the elements added from that html editor... is there any way i can do it? I can get the text as string, but is there a way i can "transform" that string into html and get all the tags/controls added? ]
I'm new at this so please, excuse my errors. Thank you!
this is the function fired after button click
'ckeditor ID = "TBHTMLText"
Protected Sub btnGetElements_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGetElements.Click
dim textAddedByUser as string
textAddedByUser = TBHTMLText.Text
End Sub
this textAddedByUser is everything the user adds in the editor so I was thinking if i develop an algorithm that can help me take every single tag and get the ID of each control added... but I think there is an easier way to do it. If so help me please.
I don't know anything about vb.net but with JavaScript you might have a listener for CKEditor's "change" event. Or, if you wanted to get the content from an editor instance upon the triggering of some arbitrary event, you could use CKEditor's getData() method. This would give you the raw HTML.
Examples:
When an arbitrary event is fired:
var editor = $(e.currentTarget).ckeditorGet();
var data = editor.getData();
var el = editor.element.$;
Setting up a "change" listener for CKEditor instances:
$.each(CKEDITOR.instances, function(i, editor) {
editor.on("change", function(e) {
var data = e.sender.getData();
var el = editor.element.$;
...
});
});

Colorbox and Dynamic Inline HTML

I've got a form in .NET.
when the user presses submit, a sub is launched to check all checkboxes, radiobuttons, etc...
and when there's an issue, i'm adding the specific issue to a stringbuilder
as per below
Dim errors As New StringBuilder
If APACradio.Checked = False And EMEAradio.Checked = False And LATAMCANADAradio.Checked = False Then
errors.AppendLine(" You must select a Region")
End If
If CountryDDL.SelectedValue = "Select" Then
errors.AppendLine(" You must select a Country")
End If
If EmploymentDDL.SelectedValue = "Select" Then
errors.AppendLine(" You must select a Employment Type")
End If
etc....
At the end of the check, i would like a Colorbox to appear, listing the lines of the stringbuilder, one by one.
I've worked with colorbox's inline HRef's before and i love that but this is a bit different as i can not preload my document with the code here.
Colorbox page itself shows samples on how to load a HTML page (sample 5) but my HTML i want to show would be rather in memory than on a disk somewhere
Why not use ColorBox's html property? Example:
$.colorbox({html:function(){
var html = '';
// do your formatting
return html;
}});

LinkButton not accessing EventArg

I am using c#.net.
I am trying to create a LinkButton within the code-behind, when I debug my code I recieve no errors, however its not accessing the EventArg attached to the button, it does however refresh the page. What am I doing wrong?
Button Code
LinkButton myLinkButton = new LinkButton();
myLinkButton.ID = appointment.appID.ToString();
myLinkButton.CommandArgument = appointment.appID.ToString();
myLinkButton.Command += new CommandEventHandler(ViewClick);
myLinkButton.CommandName = appointment.appID.ToString();
myLinkButton.Text = appointment.contactName
Used to style button
string divLook = "height:" + divHeight + "em";
Button is then added to a panel
Panel p = new Panel();
p.Style.Add("linkStyle", divLook);
p.CssClass = "standardLink";
p.Controls.Add(myLinkButton);
dataCell.Controls.Add(p);
protected void ViewClick(object sender, CommandEventArgs e)
{
var appointmentId = Convert.ToInt32(e.CommandArgument);
Debug.Write("Are you even getting in here");
}
Thanks in advance for any help.
Clare
Everything looks legit. I would recommend viewing the source of the generated page and looking at the ID that the link button is getting. It may be duped on the page.