I want to make a function for Windows Forms like:
private void do(textBox_name, string text)
{
textBox_name.Text=text.toString();
}
The function should take name of textBox as an argument, then write text to right textBox.
But I don't know how can I send properly which textBox should be used.
At this moment I have done it in "if statement", but adding new elements is scripting it again and again because I have to write
textBox1.Text=text.toString(); then textBox2.Text=text.toString();
for every textBox that takes a lot of time. Also, I know I can do it with switches, like this:
switch(ID)
case 1:
textBox1.Text=text.toString();
break;
case 2:
textBox2.Text=text.toString();
But I guess there is a way to do one function for every textBox.
I have one question - why are you invoking ToString() method on a string? It is completely unnecessary.
Your function should look like:
private void do(TextBox tb, string text)
{
tb.Text = text;
}
If you work with doubles, then it will differ slightly:
private void do(TextBox tb, double number) //use meaningful names, "text" for double is poor choice
{
tb.Text = number.ToString();
}
Welcome again. Problem has been solved, it was easy so i'm really embarassed how long i was looking for solving problem. I didn't knew that i can send to function parameter of TextBox.
Now it looks like
private void write(TextBox tbox, string text)
{
tbox.Text=text;
}
Related
I am trying to call a function based on information from a combobox. The user will change the combobox and in doing so we call a function according to the data in the combobox text joined with a fixed text. I am trying to do this so every time we get a new version I just add a folder and do not have to go into the code to add new function names like in a case statement.
The combobox would have text as
v6.1
v6.4
v7.2
v8.6
and so on
The function I want to call is named Getinfo_ with the addition of the text from the combobox with the . replaced with _ e.g. I would choose v6.1 from combobox and in doing so I would call function called Getinfo_v6_1
After a lot of thinking searching and trying I have got close but not close enough yet. I think I need to use Reflection (maybe not) and
private void cmbobx_version_SelectedIndexChanged(object sender, EventArgs e)
{
Type t = this.GetType(); //need to get the type
MethodInfo method = t.GetMethod("Getinfo" + cmbobx_version.Text.Replace('.', '_')); //put together function name
method.Invoke(this, new object[] {Fridge, "Order" }); //call function with parameters
}
Unfortunately this stops at invoke saying the method is NULL, I do not understand why this is so apart from maybe I totally misunderstand what I am doing.
The function I want to call would look a bit like the following
public void Getinfo_v6_1(ComboBox inFocusComboBox, string action)
{
switch (inFocusComboBox.Text)
{
case "Red": Price = 11254; break;
case "Blue": Price = 11278; break;
case "Green": Price = 11354; break;
}
}
public void Getinfo_v6_4(ComboBox inFocusComboBox, string action)
{
switch (inFocusComboBox.Text)
{
case "Red": Price = 254; break;
case "Blue": Price = 278; break;
case "Green": Price = 354; break;
}
}
All help greatly appreciated even if you have a better way of doing what I need to do.
You should read about design patterns for example you could create polymorphic items that implement your function using for example the template design pattern. Try to avoid reflection as it is ‘slow’ and not type safe.
Thanks to Ĵošħ Williard I had indeed missed out the underscore and when working with it I had not noticed as I also do a text replace from . to _ and thought it was all correct. Even when debugging I did not see it, often we cannot see the obvious which is why a second opinion of those wiser than me is always good.
The working code is now as follows.
private void cmbobx_version_SelectedIndexChanged(object sender, EventArgs e)
{
Type t = this.GetType(); //need to get the type
MethodInfo method = t.GetMethod("Getinfo_" + cmbobx_version.Text.Replace('.', '_')); //put together function name
method.Invoke(this, new object[] {Fridge, "Order" }); //call function with parameters
}
Please do be careful as the functions will have no references but it will compile and will work. It all works at run-time when you call the correct function.
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";
I have a method called BuyShares() that is supposed to take a value in a textbox and add another user input value to it. I would like to use a messagebox that sets off the method by the user clicking okay. The only problem is that I can't seem to call upon the method.
This is the method.
public void BuyShares(int anAmount)
{
int newShares;
newShares = GetInvestmentShare() - anAmount;
SetInvestmentShare(newShares);
}
And this is the messagebox I have set up
private void button1_Click(object sender, EventArgs e)
{
DialogResult result;
result = MessageBox.Show("Your transaction is complete", "Success", MessageBoxButtons.OK);
if(result==DialogResult.OK)
{
txtStockSharesTab3.Text=??????
}
This is a windows form application and the program has several different classes
Without giving away the answer because you probably want to learn something from this...
I'm guessing you want to get the amount of shares to buy from one textbox, then call BuyShares and finally update txtStockSharesTab3 to this value.
Your BuyShares method returns void meaning it won't return a value. Somewhere in that method is where you're going to update your txtStockSharesTab3 textbox. Is that exact method signature for BuyShares required?
I'm trying to write the status of the program to the user. But my method to do so doesn't work. statusBox is a textbox windows form.
public static void writetoStatus(string text)
{
TextBox statusBox = new TextBox();
statusBox.Text = text;
}
Help please!
You can't access instance variables with a static method. I can't think of a way that statusBox would not be an instance member. Try making your method non-static and it should be fine.
As mentioned in a previous answer, your method needs to be static in order to access the TextBox on your form.
Also pressing, however is the fact that you're putting the status in a new TextBox instead of the one on your form.
If you created a form and put a TextBox on it, then the TextBox already has a name, and you can access it from the code-behind file. By default, I think it would be Textbox1 or some other number. You can, of course, change this name in the designer file or in the form editor GUI in Visual Studio.
So, lets say you change the name of the existing TextBox to statusBox. Now your method need only be this:
void WriteToStatus(string status)
{
statusBox.Text = status;
}
Ok, i see that you are creating a new instance of text box inside static method. That instance of textbox ends up nowhere and it's destroyed once you your static method is executed.
You can either have:
public static void writetoStatus(TextBox tb, string text)
{
tb.Text = text;
}
// and then later use it like:
writetoStatus(statusBox, text);
Or:
public static void writetoStatus(Form frm, string text)
{
TextBox tb = new TextBox();
tb.Text = text;
frm.Controls.Add(tb);
}
// and then later use it like:
writetoStatus(myForm, text);
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]);
}