C# Call function in a class from another class - c#

I'll start of by saying I'm not a developer. Yes this is a c# nightmare. But this is a one time tool and thats it. Quick and Dirty it just needs to work and thats it.
I have the following code:
public string[] get_status(string local_fname)
{
var dts_doc = new HtmlAgilityPack.HtmlDocument();
dts_doc.Load(local_fname);
//Pull the values
var ViewState = dts_doc.DocumentNode.SelectSingleNode("/html[1]/body[1]/div[1]/input[4]/#value[1]");
var EventValidation = dts_doc.DocumentNode.SelectSingleNode("/html[1]/body[1]/div[2]/input[1]/#value[1]");
string ViewState2 = ViewState.Attributes[3].Value;
string EventValidation2 = EventValidation.Attributes[3].Value;
//Display the values
//System.Console.WriteLine(ViewState.Attributes[3].Value);
//System.Console.WriteLine(EventValidation.Attributes[3].Value);
//System.Console.ReadKey();
return new string[] { ViewState2, EventValidation2 };
}
I want to call get_status from a button on my Main.cs which will show 2 Message Boxes with ViewState2 and EventValidation2.
Again, I'm not a developer, this is probably the wrong way of doing things. But I just need a quick and dirty solution to get this job done once.

Make the function static by adding the static keyword to the function definition:
static public string[] get_status(string local_fname)
Use the class name to reference the function from your Main class.

try this:
foreach(string s in get_status(localFname))
{
MessageBox.Show(s);
}
As you said, it is quick and dirty and I stayed faithful to that paradigm.
And yes, if you need to acces another class, make the method static or just simply create an instance and call the method on it. I hope I have understood the problem correctly.

if you are using visual studio, go to the Button you want to click, double-click the button. This will create an eventhandler. In the eventhandler you should call the above method.
protected void Button1_Click(object sender, eventArgs e)
{
string local_fname = someValue;
string results[] = get_status(local_fname);
MessageBox.Show(results[0]);
MessageBox.Show(results[1]);
}

Related

C# Get Value of a text box in a Static Void

I am trying to get the value of a text box called txtNum on the form FrmPhone as well as write to the text box txtLog however there seems to be no interacation between the Static Void and the Text Boxes on FrmPhone.
Below is the code for the CreateCall Static Void.
private void btnCall_Click(object sender, EventArgs e)
{
CreateCall();
}
static void CreateCall()
{
FrmPhone FrmPhone = new FrmPhone();
var numberToDial = FrmPhone.txtNum.Text;
FrmPhone.txtLog.Text += "\r\nCall " + numberToDial;
FrmPhone.txtLog.ScrollToCaret();
SetupDevices();
call = softphone.CreateCallObject(phoneLine, numberToDial);
call.CallStateChanged += call_CallStateChanged;
call.Start();
}
What am I missing to allow me to interact with the text boxes on the form while executing code in the static void?
Also worth noting is that If replace
var numberToDial = FrmPhone.txtNum.Text;
with
var numberToDial = "2788";
The call is made but the txtLog text does not change.
There are two options.
You make the method non-static. This is the easiest solution and the one that makes most sense. You are after all using instance variables.
void CreateCall()
{
var numberToDial = this.txtNum.Text;
}
Pass in the form to the method, as said, it doesn't make sense, but it does the job. txtNum needs to be internal or public, or CreateCall must reside in the same class:
static void CreateCall(FrmPhone frmPhone)
{
var numberToDial = frmPhone.txtNum.Text;
}
In calling the code you pass in this:
CreateCall(this);

Call an Activity method from Fragment

I'm using ToDoActiviy.cs for user login, this class got this method:
[Java.Interop.Export()]
public async void LoginUser(View view)
{
if(await authenticate())..
This method is called from .axml file from Button widget android:onClick="LoginUser" I changed this for android:onClick="LoginUserClick" This last method create a dialog fragment for show different logins accounts.
Now from the Dialog Fragment(Is situated on another class) I want to hand the event for the button click on the dialog fragment and call this method from ToDoActivity.cs.
On dialog fragment class I hand the click event like this:
private void ButtonSignInFacebook_Click(object sender, EventArgs args){
//Here code for call to LoginUser method from 'ToDoActivity.cs'
ToDoActiviy.cs act = new ToDoActivity();
act.LoginUser();
}
I need to pass a View but I tried a lot of things and any works..
Someone can help me?
Thanks in advance ;)
I would like to make a slight modification to #guido-gabriel 's answer.
In C# syntax, it will be
((ToDoActivity)Activity).yourPublicMethod();
Getter/Setter Methods in Java are mapped to Getter Setter properties in Xamarin.Android
Finally I fix it ! I had to change the parameters of the method and create it without parameters.. and now Is working. Both solutions are good:
((ToDoActivity)Activity).LoginUserFacebook();
//ToDoActivity act = new ToDoActivity();
//act.LoginUserFacebook();
Adapt and use the snipped below in your fragment
var casted = Activity as MyActivityName;
if (casted != null) {
casted.IWantToCallThisMethodFromMyFragment();
}
You have to call the method from the activity. Have you tried?
((YourActivityClassName)getActivity()).yourPublicMethod();
I.E.
((ToDoActivity)getActivity()).yourPublicMethod();
This is not really a good practice to do. Why?
Doing this couples the Fragment tightly to this particular Activity type, meaning it will not be possible to reuse the Fragment elsewhere in the code.
Instead I suggest you rely on the Activity subscribing to an event or implementing some kind of callback method in order to do the desired action after login.
It could also seem like your Activity might be containing a lot of logic that could be split out into a shared library of some kind. Making it possible to reuse that code on another platform, for instance iOS in the future.
So since your are in charge of newing up the Fragment, I would do something like this instead:
public class LoginFragment : Fragment
{
Action _onLoggedIn;
public static void NewInstance(Action onLoggedIn)
{
var fragment = new LoginFragment();
fragment._onLoggedIn = onLoggedIn;
return fragment;
}
private void Login()
{
// login user
// after loggedin
_onLoggedIn?.Invoke();
}
}
Then in your Activity:
private void LoginUser()
{
// whatever
}
var loginFragment = LoginFragment.NewInstance(LoginUser);
// fragment transaction here...

Change Textbox object to Static

I have little experience in C#, mostly playing with it as a hobby, and I was wondering what I needed to do to change a textbox from non-static to static.
In Visual Studio 2012, I'm trying to add a line of text using the method textbox1.AppendText("Text");, and it won't work because the textbox isn't static, while the method trying to write the code is static. I can't find the line of code where the textbox is initialized in my code, nor have I found an option in the properties that allows me to change that.
Is there a work-around, or do I need to make it static? And if I need to make it static, how would I do that? I'm at a loss.
Thank you for your help!
EDIT: adding code sample. The method below is called from a second form, same from which the value of x is determined.
public static void getMethod(int x)
{
if (x > 4)
{
textbox1.AppendText("Text");
}
else
{
textbox1.AppendText("Other text");
otherVariable = x;
}
}
It's not clear from your post which GUI framework you're using. Both Winforms and WPF have a TextBox class.
But, to the point of your question: you could in the object where the TextBox is declared and created, also have a static field to which you assign that reference. But that would be a poor design choice, IMHO.
It's not clear what your static code is doing, where it's declared, or who called it (another failing of your question is that you did not provide any code, never mind a concise, complete code example), but assuming the static method is not in the UI object that owns the TextBox instance itself (if it is, then you just need to make the method non-static), the the correct way to address this would be for the UI object that does know about the TextBox instance to have some public method or property used to set the text, and then for the code that invokes your static method to pass the reference of that UI object to the static method, so that it can use the member you added.
For example:
class Form1 : Form
{
public string FieldText
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
}
and elsewhere:
static void SomeMethod(Form1 form)
{
// ...do some stuff...
form.FieldText = "some text";
// ...do some other stuff...
}
In your specific scenario, you seem to have two forms: one containing the textbox1 member, and another that passes an int value to a method, where you want to be able to add some text to the TextBox1 based on the value.
In that case, it would look more like this:
class Form1 : Form
{
public void AppendFieldText(string text)
{
textbox1.AppendText(text);
}
}
and in the static method:
public static void getMethod(int x, Form1 form)
{
if (x > 4)
{
form.AppendFieldText("Text");
}
else
{
form.AppendFieldText("Other text");
otherVariable = x;
}
}
Naturally, the caller of the getMethod() method will need the reference for the form parameter; you will have to pass that somehow to that second form which is calling this method, so that it can pass it to the method.
Note that in both of my examples, I have not exposed the TextBox object itself. You should follow this example, exposing only the minimum amount of functionality needed in order to get the job done. This helps ensure that the TextBox object doesn't wind up getting used in appropriately by some other code, and especially helps ensure that your classes remain reasonably decoupled.
On that latter point, I will mention that your code example is still pretty bare. There are other techniques which can solve this problem with even less coupling between the types. But again, lacking a good code example, it's not possible to know for sure what would work, never mind what would be best.
The above example is appropriate, given the information you've shared.
If you would like to edit your question to provide better, more specific detail, a better, more specific answer could be provided.
you can do something like below
private void button3_Click(object sender, EventArgs e)
{
getMethod(textBox1,5);
}
public static void getMethod(TextBox textbox1,int x)
{
if (x > 4)
{
textbox1.AppendText("Text");
}
else
{
textbox1.AppendText("Other text");
otherVariable = x;
}
}
Textboxes aren't static. And you can't make them static, they are all instanciated. The name of your textbox is the instance name.
So just use the text property on the instance of the text box.
textbox1.Text = "Text";
If you want to Append one just do:
textbox1.Text = String.Concat(Textbox1.Text, "more text");
same thing about could also be seen as:
textbox1.Text = textbox1.Text + "more text";

Adding buttons by a function

I want to add a button, using a function that takes all the arguments in one line, to keep it clean. But if I try to add the button via This.Controls.Add, I get an error because the function is static. What should I write instead of This (something like Form1.Controls.Add) so I can do everything in one function?
You could take the form as an argument to the static function:
public static void CreateButton(Form targetForm, param1, param2, ...) {
Button b = new Button();
...
targetForm.Controls.Add(b);
}
...but unless this method is going to be used to add buttons to a variety of forms, I don't see the advantage of making it static like this. It seems like a sort of OO anti-pattern. I would probably make it non-static and use this.
I would just have your function return the button:
//Usage
this.Controls.Add(CreateButton(...));
//Function def
public static Button CreateButton(...)
{
Button createdButton = new Button();
...
return createdButton;
}
Assignment returns the result of the assignment (so you can chain them). So to inline the assignment:
//With a variable (I did *not* say it was good practice to do this)
this.Controls.Add(myVar = CreateButton(...));

Displaying<List> reports in a message box

Within my WinForm i have a method that checks the validation of various user controls and adds them to an errorList. When the user clicks the save button I want it to check the validation method and show the errors if any in a message box. The Validate method is in another form and class so i think that might be my problem.
private void Save_Click(object sender, EventArgs e)
{
var errorList = string.Join(Environment.NewLine, Validate.ToArray());
MessageBox.Show(errorSet);
}
Thank you for any help.
The error 'Form1.Validate(System.Collections.Generic.List<string>)' is a 'method', which is not valid in the given context means that you're using the method wrong.
var errorList = string.Join(Environment.NewLine, Validate.ToArray());
makes no sense. You're missing the parentheses:
var errorList = string.Join(Environment.NewLine, Validate().ToArray());
That's only one problem. The method has a parameter of type List<string>, but you don't pass an argument to the function.
Also, you said in a comment that the return value is of type bool, but it seems you expect it to return a collection of strings.
You have this issue because you are calling the validate method that is on another form without mentioning the instance of that form.
Lets say you have another class Class1.
//create instance of your class/form that has this method
OperationControl oc = new OperationControl ();
private void Save_Click(object sender, EventArgs e)
{
//call the method with form instance created above
var errorList = string.Join(Environment.NewLine, oc.Validate().ToArray());
MessageBox.Show(errorSet);
}
some time this error means you may have the same method with the same name in your program scope. Check if no other function named MessageBox exist in your program

Categories

Resources