I have a method in VB.Net that calls button of form:
Private Sub BUTTON_CAL( _
ByVal frm As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
If e.KeyCode = Keys.A AndAlso e.Modifiers = Keys.Control Then
If frm.AddButton.Enabled = True Then Call frm.AddButton.PerformClick()
e.SuppressKeyPress = True
End if
End Sub
I have converted this code into c#
public static void BUTTON_CAL(object frm, System.Windows.Forms.KeyEventArgs e) {
if(e.KeyCode==Keys.A&&e.Modifiers==Keys.Control) {
if(frm.AddButton.Enabled==true) {
frm.AddButton.PerformClick();
}
e.SuppressKeyPress=true;
}
}
in C#.Net I am getting the error
'object' does not contain a definition for AddButton' and no extension method 'AddButton' accepting a first agument of type 'object' could be found(are you missing a using directive or an assembly reference?)
Cast 'frm' to the data type you expect it to be (runtime checking if valid is a good idea)
Form form = frm as Form;
if( null == form )
// error
form.AddButton(...);
public static void BUTTON_CAL(object sender, KeyEventArgs e) {
if(sender is Form) {
var frm=sender as Form;
if(e.KeyCode==Keys.A && e.Modifiers==Keys.Control) {
if(frm.AddButton.Enabled)
frm.AddButton.PerformClick();
e.SuppressKeyPress=true;
}
}
}
The signature of KeyEventHandler
is
public delegate void KeyEventHandler(object sender, KeyEventArgs e);
Rather if(SomeBool)
than if(SomeBool==true)
. Don't be unnecessarily complicated.
put someObject as SomeType
in a if(someObject is SomeType)
would be safe. It seems a little bit redundant, but more readable than compare to null.
Thank you all for giving time to solve the problem I have solved the problem by using below :
public static void BUTTON_CAL(object sender, System.Windows.Forms.KeyEventArgs e)
{
var frm = sender as Form;
if(e.KeyCode==Keys.A&&e.Modifiers==Keys.Control)
{
if(frm.Controls["AddButton"].Enabled==true)
{
((Button)frm.Controls["AddButton"]).PerformClick();
}
e.SuppressKeyPress=true;
}
}
cast frm to the class name of your form
if (((Form1)frm).AddButton.Enabled == true){
((Form1)frm).AddButton.PerformClick();
}
I assume Form1 is the name of your form, and it has a button with name AddButton and that button has the proper access modifier.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.