I'm trying to create a custom textbox with a userControl, my problem lies in the part of setting the default event of the userControl to handle the textChanged of the textbox. I currently have the userControl with only one textbox.
In c # I have this code that works perfectly (UserControl3.cs file):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace custom_controls
{
[DefaultEvent("_TextChanged")]
public partial class UserControl3 : UserControl
{
public UserControl3()
{
InitializeComponent();
}
public event EventHandler _TextChanged;
private void TextBox1_TextChanged(object sender, EventArgs e)
{
if (_TextChanged != null)
{
_TextChanged.Invoke(sender, e);
}
}
}
}
But I have not been able to translate it correctly to vb.net where I need the control. Any help or suggestion is greatly appreciated.
This is the code resulting from the conversion from C # to VB.net:
<DefaultEvent("_TextChanged")>
Public Class UserControl3
Public Event _TextChanged As EventHandler
Private Sub textBox1_TextChanged(sender As Object, e As EventArgs) Handles textBox1.TextChanged
If _TextChanged IsNot Nothing Then 'error here: _TextChanged
_TextChanged.Invoke(sender, e) 'error here: _TextChanged
End If
End Sub
End Class
Error image:
You can't raise events the same way in vb and c#. vb has a keyword RaiseEvent to do that
<DefaultEvent("_TextChanged")>
Public Class UserControl3
Public Event _TextChanged As EventHandler
Private Sub textBox1_TextChanged(sender As Object, e As EventArgs) Handles textBox1.TextChanged
RaiseEvent _TextChanged(sender, e)
End Sub
End Class
Related
I'm creating a game using the PictureBox control and adding a MouseDown event to handle reducing the "health" value of the PictureBox.
I would like to programmatically add a new control when the initial control loses all of it's health so that I can add variance to how the new PictureBox appears, but I do not know how to add an event handler to a programmatically created control.
Update: Thanks for the help!
This is how my finished code works, if you would like to do the same.
Public Class Form1
Private Sub NewBug()
Dim pbBug As New PictureBox With {
.Name = "pb",
.Width = 100,
.Height = 100,
.Top = 75,
.Left = 75,
.SizeMode = PictureBoxSizeMode.Zoom,
.Image = My.Resources.bug}
Me.Controls.Add(pbBug)
AddHandler pbBug.MouseDown, Sub(sender As Object, e As EventArgs)
MessageBox.Show("Hello", "It Worked")
End Sub
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
NewBug()
End Sub
Thanks,
sunnyCr
Something isnt adding up. It would appear as though Dim MyButton As New Button() should be declared at Class scope, you should not have to declare WithEvents on local variables. Furthermore the MyButton_Click sub wouldnt compile if MyButton was Local to load routine. If it is declared at Class Scope then instead of Dim MyButton As New Button You would WithEvents MyButton As New Button If you want to keep it local then you could do something like this instead
Dim MyButton As New Button With {
.Name = "MyButton",
.Top = 100,
.Left = 100,
.Image = My.Resources.SomeImage}
Controls.Add(MyButton)
AddHandler MyButton.Click, Sub(s As Object, ev As EventArgs)
'Do stuff
End Sub
which is generally how I do things as this, unless I intend to remove the handler, then I will create a Sub and use AddressOf such as how you are attempting to use it.
You must create a class for generate a picturebox by code importing windows.system.Forms; as example you can do this, changing label for picturebox:
This is the class:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
class Etiqueta
{
private Label etiquetaHija;
public Label EtiquetaHija { get => etiquetaHija; set => etiquetaHija = value; }
public Etiqueta(Point posicion, Size dimensiones, string texto)
{
etiquetaHija = new Label();
etiquetaHija.Size = dimensiones;
etiquetaHija.Location = posicion;
etiquetaHija.Text = texto;
etiquetaHija.Click += EtiquetaHija_Click;
}
private void EtiquetaHija_Click(object sender, EventArgs e)
{
MessageBox.Show("Etiqueta Hija");
}
}
This is the code behind of the form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Etiqueta etiqueta = new Etiqueta(new Point(20, 20), new Size(100, 100), "Ejemplo de creacion de un label por codigo con manejador de eventos");
this.Controls.Add(etiqueta.EtiquetaHija );
}
}
}
I'm making a Windows Forms application with VB.Net, Visual Studio 2015.
The Form has a WebBrowser control and other controls.
Whenever pressing the TAB key on keyboard, it always focuses on a html element loaded in the WebBrowser control first. Then pressing the TAB key again, the focus is switched between the HTML elements in the WebBrowser control.
Till ending up switching in all HTML elements, the focus doesn't switch to other controls in the Form.
Though I set .TabIndex = 1000 and .TabStop = false in the WebBrowser control, it always focuses on a html element loaded in the WebBrowser control first, always first.
So, I want to disable focusing on the WebBrowser control by pressing the TAB key or to disable the TAB key function in the Form entirely.
I have to get the answer done in VB.NET soon, but for now here's the C# version of it:
First, an extended web browser control, that you'll have to use on the form, with a custom event when the tab key is pressed.
Here we call the TabStop = false to ensure this key gets processed. Similar reasoning on WebBrowserShortcutsEnabled.
Then, we capture on the HTML Body, the key press event.
If the key code is a 9 (tab), we fire our event.
public class WebBrowserExtended : System.Windows.Forms.WebBrowser
{
protected virtual void OnTabKeyEvent(EventArgs e)
{
EventHandler handler = TabKeyEvent;
if (handler != null)
{
handler(this, e);
}
}
public event EventHandler TabKeyEvent;
public WebBrowserExtended() : base()
{
this.TabStop = false;
this.WebBrowserShortcutsEnabled = false;
}
protected override void OnDocumentCompleted(WebBrowserDocumentCompletedEventArgs e)
{
base.OnDocumentCompleted(e);
if (this.Document.Body != null)
this.Document.Body.KeyDown += new HtmlElementEventHandler(Body_KeyDown);
}
private void Body_KeyDown(Object sender, HtmlElementEventArgs e)
{
if (e.KeyPressedCode == 9 && !e.CtrlKeyPressed)
{
this.OnTabKeyEvent(e);
e.BubbleEvent = false;
}
}
}
And here's is your event handler:
private void webBrowser1_TabKeyEvent(object sender, EventArgs e)
{
var controls = new List<Control>(this.Controls.Cast<Control>());
var nextControl = controls.Where(c => c.TabIndex > webBrowser1.TabIndex).OrderBy(c => c.TabIndex).FirstOrDefault();
if (nextControl != null)
nextControl.Focus();
else
controls.OrderBy(c => c.TabIndex).FirstOrDefault().Focus();
}
And here's the VB version of the control:
Public Class WebBrowserExtended
Inherits System.Windows.Forms.WebBrowser
Protected Overridable Sub OnTabKeyEvent(ByVal e As EventArgs)
RaiseEvent TabKeyEvent(Me, e)
End Sub
Public Event TabKeyEvent As EventHandler
Public Sub New()
MyBase.New()
Me.TabStop = False
Me.WebBrowserShortcutsEnabled = False
End Sub
Protected Overrides Sub OnDocumentCompleted(ByVal e As WebBrowserDocumentCompletedEventArgs)
MyBase.OnDocumentCompleted(e)
If Me.Document.Body IsNot Nothing Then
AddHandler Me.Document.Body.KeyDown, AddressOf Body_KeyDown
End If
End Sub
Private Sub Body_KeyDown(ByVal sender As Object, ByVal e As HtmlElementEventArgs)
If e.KeyPressedCode = 9 AndAlso Not e.CtrlKeyPressed Then
Me.OnTabKeyEvent(e)
e.BubbleEvent = False
End If
End Sub
End Class
And the VB event handler:
Private Sub WebBrowser1_TabKeyEvent(sender As Object, e As EventArgs) Handles WebBrowser1.TabKeyEvent
Dim controls = New List(Of Control)(Me.Controls.Cast(Of Control))
Dim nextControl = controls.Where(Function(c)
Return c.TabIndex > WebBrowser1.TabIndex
End Function).OrderBy(Function(c)
Return c.TabIndex
End Function).FirstOrDefault()
If Not controls Is Nothing Then
nextControl.Focus()
Else
controls.OrderBy(Function(c)
Return c.TabIndex
End Function).FirstOrDefault().Focus()
End If
End Sub
Hi i converted the following c# code to vb.net.
public Dropdown(CheckedComboBox ccbParent)
{
this.ccbParent = ccbParent;
InitializeComponent();
this.ShowInTaskbar = false;
this.cclb.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.cclb_ItemCheck);
}
private void cclb_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (ccbParent.ItemCheck != null)
{
ccbParent.ItemCheck(sender, e);
}
}
Visual Basic
Private cclb As CustomCheckedListBox
Public Event ItemCheck As Windows.Forms.ItemCheckEventHandler
Public Sub New(ByVal ccbParent As PlexisCheckedComboBox)
MyBase.New()
Me.ccbParent = ccbParent
InitializeComponent()
Me.ShowInTaskbar = False
AddHandler cclb.ItemCheck, AddressOf cclb_ItemCheck
End Sub
Private Sub cclb_ItemCheck(ByVal sender As Object, ByVal e As
Windows.Forms.ItemCheckEventArgs)
If (Not (ccbParent.ItemCheck) Is Nothing) Then
ccbParent.ItemCheck(sender, e)
End If
End Sub
In the converted vb.net code im getting error in the following line as
""
If (Not (ccbParent.ItemCheck) Is Nothing) Then
ccbParent.ItemCheck(sender, e)
please help me how to resolve it .
Well, as the error message told you, you have to use the RaiseEvent keyword to raise events.
But even then it would not work, since you can't raise events outside of the class the event is declared in (in contrast to C#, where nested classes can raise events of the outer class).
So to solve this add a new method to the outer class called OnItemCheck which raises the ItemCheck event, and call that method in cclb_ItemCheck instead of trying to raise the event directly.
I am using vb.net as code behind. As soon as I added USING System; I started getting error.
Here is what I have, its literally nothing except the basic structure.
using system;
Public Class Appointment
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Public Function saveAppointment() As String
Return 0
End Function
End Class
In aspx I have this in header
I am unable to understand the problem. Any suggestions?
VB.net does not have the using xyzNamespace; syntax (that is C# syntax). Also, don't forget that VB.Net doesn't use semicolon ";" as a line terminator either.
You should do Imports System instead
I have a Form (ClientGUI) that has a RichTextBox. What I want to do is to append text to this RichTextBox from a Sub located in another class (MyQuickFixApp). I know that the Sub works, because the debugger go through, but it doesn't append the text to my RichTextBox.
How do I do that ?
Thanks for you help !
ClientGUI.vb :
Imports QuickFix
Imports QuickFix.Transport
Imports QuickFix.Fields
Public Class ClientGUI
Dim initiator As SocketInitiator
Public Sub ClientGUI_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim filename As String = "Resources/initiator.cfg"
Dim settings As New SessionSettings(filename)
Dim myApp As New MyQuickFixApp()
Dim storeFactory As New FileStoreFactory(settings)
Dim logFactory As New FileLogFactory(settings)
initiator = New SocketInitiator(myApp, storeFactory, settings, logFactory)
End Sub
Public Sub ConnectToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ConnectToolStripMenuItem.Click
ToolStripDropDownButton1.Text = "Establishing connection..."
ToolStripDropDownButton1.Image = My.Resources.Connecting
initiator.Start()
End Sub
Public Sub DisconnectToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DisconnectToolStripMenuItem.Click
ToolStripDropDownButton1.Text = "Disconnecting..."
ToolStripDropDownButton1.Image = My.Resources.Disconnecting
initiator.Stop()
End Sub
End Class
MyQuickFixApp.vb :
Imports QuickFix
Imports QuickFix.Transport
Imports QuickFix.Fields
Public Class MyQuickFixApp
Inherits MessageCracker : Implements IApplication
Dim _session As Session = Nothing
Public Sub FromAdmin(message As Message, sessionID As SessionID) Implements IApplication.FromAdmin
ClientGUI.RichTextBox1.AppendText("")
ClientGUI.RichTextBox1.AppendText("IN (ADMIN): " + message.ToString())
Try
Crack(message, sessionID)
Catch ex As Exception
ClientGUI.RichTextBox1.AppendText("")
ClientGUI.RichTextBox1.AppendText("==Cracker exception==")
ClientGUI.RichTextBox1.AppendText(ex.ToString())
ClientGUI.RichTextBox1.AppendText(ex.StackTrace)
End Try
End Sub
Public Sub FromApp(message As Message, sessionID As SessionID) Implements IApplication.FromApp
ClientGUI.RichTextBox1.AppendText("")
ClientGUI.RichTextBox1.AppendText("IN (APP): " + message.ToString())
Try
Crack(message, sessionID)
Catch ex As Exception
ClientGUI.RichTextBox1.AppendText("")
ClientGUI.RichTextBox1.AppendText("==Cracker exception==")
ClientGUI.RichTextBox1.AppendText(ex.ToString())
ClientGUI.RichTextBox1.AppendText(ex.StackTrace)
End Try
End Sub
Public Sub ToApp(message As Message, sessionId As SessionID) Implements IApplication.ToApp
Try
Dim possDupFlag As Boolean = False
If (message.Header.IsSetField(Tags.PossDupFlag)) Then
possDupFlag = Converters.BoolConverter.Convert(message.Header.GetField(Tags.PossDupFlag))
End If
If (possDupFlag) Then
Throw New DoNotSend()
End If
Catch ex As FieldNotFoundException
ClientGUI.RichTextBox1.AppendText("OUT (APP): " + message.ToString())
End Try
End Sub
Public Sub OnCreate(sessionID As SessionID) Implements IApplication.OnCreate
'_session = Session.LookupSession(sessionID)
ClientGUI.RichTextBox1.AppendText("Session created - " + sessionID.ToString())
End Sub
Public Sub OnLogon(sessionID As SessionID) Implements IApplication.OnLogon
ClientGUI.RichTextBox1.AppendText("Logon - " + sessionID.ToString())
ClientGUI.ToolStripDropDownButton1.Text = "Connected"
ClientGUI.ToolStripDropDownButton1.Image = My.Resources.Connected
'MsgBox("onlogon")
End Sub
Public Sub OnLogout(sessionID As SessionID) Implements IApplication.OnLogout
ClientGUI.RichTextBox1.AppendText("Logout - " + sessionID.ToString())
ClientGUI.ToolStripDropDownButton1.Text = "Disconnected"
ClientGUI.ToolStripDropDownButton1.Image = My.Resources.Disconnected
End Sub
Public Sub ToAdmin(message As Message, sessionID As SessionID) Implements IApplication.ToAdmin
ClientGUI.RichTextBox1.AppendText("OUT (ADMIN): " + message.ToString())
End Sub
Public Sub OnMessage(message As FIX42.Heartbeat, sessionID As SessionID)
ClientGUI.RichTextBox1.AppendText("HEARTBEAT")
End Sub
End Class
I guess that the code in MyQuickFixApp class access to the default instance of your ClientGUI, not the instance which is actually running, each time you write ClientGUI.(...).
See this thread Why is there a default instance of every form in VB.Net but not in C#? for more information about default instance, which is something you should avoid to use.
So you could add a parameter in the MyQuickFixApp class constructor :
Public Class MyQuickFixApp
Inherits MessageCracker : Implements IApplication
Dim _clientGUI As ClientGUI = Nothing
Public Sub New(cltGui As ClientGUI)
_clientGUI = cltGui
End sub
(...)
End class
Then, replace in the MyQuickFixApp class all the ClientGUI.(...), with _clientGUI.(...) to be sure to access to the correct instance.
And finally, initialize your MyQuickFixApp class in ClientGUI like this:
Dim myApp As New MyQuickFixApp(me)
Note that this code, you can only access to the method of the class in the Form_Load event. This variable should be declared in the class and initialized in the form_load if you want to access it later from the ClientGUI form.
Public Class ClientGUI
Dim initiator As SocketInitiator
Dim myApp As MyQuickFixApp()
Public Sub ClientGUI_Load(sender As Object, e As EventArgs) Handles MyBase.Load
(...)
myApp =New MyQuickFixApp(Me)
(...)
End Sub
(...)
End Class
In Form
private void button3_Click(object sender, EventArgs e)
{
TestClass tc = new TestClass();
tc.addComment(richTextBox1);
}
In Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
public class TestClass
{
public void addComment(RichTextBox rt)
{
rt.Text = rt.Text + Environment.NewLine + "My Dynamic Text";
}
}
you can do it same in VB.net also