Been working on a simple c# windows app program. I have been able to pass a few variables from one form to the next and use them using form2 y = new form2(passingVariable); y.ShowDialog(); and then on the next form public form2(string myVariable). However this method only allows me to use the variable within those curly braces. Currently I am trying to pass it to the next form in line. However it won't let me use the variable when I try to pass it into the next form using the code line I provided above. It gives me the error The name 'userName' does not exist in the current context I have a lot of source code and didn't know what exactly was needed for me to share so here is the link to my webng.com account with a very simple web page set up with my source code if anyone needs to review it.
Try creating another variable on that current form to store that Username and then assign the username passed into that variable. Your constructor will be like this then:
private string username;
public talkingWithProgram(string userName, string pcName)
{
InitializeComponent();
this.Text = pcName;
programQuestion.Text = "Whatcha wanna talk about \n" + userName + "?";
this.userName = userName;
}
sportsCategories y = new sportsCategories(userName);
Creating a new sportsCategories class now passes userName from this context, which has the value from the previous form. Currently it looks like you're referring to the userName in the constructor which is in the method context and out of scope outside.
I would avoid setting specific variables in the constructor of a windows form. In general, it is more customary to use getters and setters, or a function designated specifically for this purpose.
For example: If you can have the code form2 y = new form2(passingVariable); instead you can have the code
form2 y = new form2();
form2.SetMyVar(passingVariable);
OR, if you are using getters and setters:
form2 y = new form2();
form2.SetMyVar = passingVariable
That way, whenever you need to set or update the variable you can do it as long as you have a reference to the form. Also, in said SetMyVar() function (if you choose that method), be sure to set a class variable. In your code, class variables go outside your functions, so that they are visible to all functions of that instance of the class.
initialize a variable in a class xyz
assign the values to them in constructor like
String a1,b1=String.empty
Class xyz
{
xyz(string a,string b)
{ //constructor
a1=a;
b1=b;
//Now use them in whole class
}
}
or if you want to use them in whole application then initialize them globally in Program.cs
then you can set and get values like
Program.a1="abc" //assigning value
Related
I am having multiple forms with Buy button provided. The forms i am having are LawnA.cs and Lawnb.cs, i want to use single Buy.cs form for both of these forms. I mean I want to know what form called the Buy.cs.
In Form LawnA.cs
buy.lotAtobuy = this;
buy.ShowDialog();
In Form LawnB.cs
buy.lotBtobuy = this;
buy.ShowDialog();
In Form Buy.cs
public LawnA lotAtobuy;
public LawnB lotBtobuy;
((LawnA)lotAtobuy).textBox1.Text;
((LawnB)lotBtobuy).textBox1.Text;
In class Buy.cs, I want to execute:
((LawnA)lotAtobuy).textBox1.Text;
if LawnA.cs called Buy.cs while if LawnB.cs called Buy.cs I want to execute this code:
((LawnB)lotBtobuy).textBox1.Text;
You need to to define separate object for each class instead for that define the variable as object, and check the type of object before assigning the text. Which means the declaration of that variable in Buy.cs will be:
public object lotToBuyInstance;
So that you can get the type of object and compare before use, that would be like thi:
if (lotToBuyInstance.GetType() == typeof(LawnA))
{
((LawnA)lotAtobuy).textBox1.Text;
}
else if (lotToBuyInstance.GetType() == typeof(LawnB))
{
((LawnB)lotAtobuy).textBox1.Text;
}
// and so on
Consider that you wanted to create another class(let it be some LawnC) then you need not to create an object of that type and make changes as per that, Just add another condition in your if else if ladder to make them work
Try this in the constructor for the receiving form:
using System.Diagnostics;
public FormThatWasCalled
{
string caller = new StackTrace().GetFrame(1).GetMethod().DeclaringType.Name;
InitializeComponent();
}
So i am trying to store my main form and open a new one however i get this error, here is the code:
I have this at form level
public static frmAddBook frmkeepBooks = null;
public frmMain()
{
InitializeComponent();
frmkeepBooks = this;
}
The error underlines "this" saying it "Cannot inplicitly convert type Books.frmMain to Books.frmAddBook"
Change the first line into:
public static frmMain frmkeepBooks = null;
The types should be equal (or in herited) and probably it is not.
Are you trying to just show the new form on top of the old as a dialog keeping the old form up? I don't quite understand why you are trying to set your instance of frmMain to equal a null instance of frmAddBook.
if you are trying to open new form as a dialog you would do something like this:
public static frmAddBook frmkeepBooks;
public frmMain()
{
InitializeComponent();
frmKeepBooks = new frmAddBook();
/* if you want to display the 2nd form ontop of the first disallowing
user interaction on the first until the 2nd form closes */
frmKeepBooks.ShowDialog();
// If you want to allow interaction on either form
frmKeepBooks.Show();
/* maybe you don't want to display the first form
anymore after the 2nd form is displayed */
this.Visible = false;
}
I think this question needs some clarification on what you are trying to do exactly.
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'm working on a term paper that performs operations with complex numbers. Application looks like this:
If you click on "Calculate", will calculate the operands and the result is displayed in a new dialog box. So I have two dialogs - a main window (up on pic) to display the read result (down on pic). Unfortunately I was not able to save result in the main dialog box, which is then written to a text file. There is important piece of code:
Thank you for ideas.
In your MainForm class declare a property as
public class MainForm:Form
{
public string CalculationResult { get; set; }
...
...
//Your code here
...
...
}
then on method of calculate change it to
if(resultBool!=null)
{
CalculationResult = resultBool.ToString());
formResult dlg=new formResult(CalculationResult);
dlg.Owner=this
dlg.StartPosition=FormStartPosition.CenterParent;
dlg.ShowDialog();
}
else
{
...
...
//your code
...
...
}
and change the following line
sw.WriteLine("Result: ");
to
sw.WriteLine("Result: " + CalculationResult);
in saveData method which is in MainForm class. Hope this will work for you. Happy coding
You have to use a reference on the target form to write on it.
You have to assure that you use the correct targetForm reference. You could either create a new targetForm or use an existing one. You could for example use the "parent" form of your dialog box and set the text of the main form textbox, from a dialog box event (using this as MSDN reference):
Dim targetForm As Form = Me.parentForm
targetForm.targetTextBox.Text = "text"
Hope I helped!
In formResult create a variable which keep a reference of Main form
private MyMainForm _mainForm;
Then create one more constructor which take reference of your Main form as parameter:
public formResult(MyMainForm mainform)
{
this.InitializeComponent();
this._mainForm = mainform;
//Now you have access to public property ResultOut
this.textBoxResult.Text = this._mainForm.ResultOut;
}
After this you can use all public properties and method of your main form in second form(formResult)
I am trying to have a click event on a new form that gets the text property of controls in form1.
I have made a public method that returns the values that I need but the returned values are always null. I have looked everywhere for this.
Form1:
public List<string> returner()
{
List<string> thevalues = new List<string>();
thevalues.Add(textbox1.Text);
thevalues.Add(textbox2.Text);
return thevalues;
}
Form2:
Form1 x = new Form1();
List<string> values = x.returner();
label1.Text = values[0];
label2.Text = values[1];
My issue is that there are no values returned because Im declaring a new instance of Form1 rather than using the one that has values in it (I guess).
Yes, that would explain what's going wrong. Basically you need to tell Form2 about the relevant instance of Form1. Exactly how you do that will depend on what constructs everything. For example, you might have:
Form1 form1 = new Form1();
Form2 form2 = new Form2();
form2.Form1 = form1;
Or you could pass the reference in the constructor to Form2.
If those are really the names of your forms, by the way, I'd strongly advise you to rename them to something more meaningful - something which indicates the purpose of the form. Likewise returner not only violates .NET naming conventions, it also doesn't explain what it's doing.
you've messed up with your codes.. if you want to get a value of text just use this. string textValue = form1.textbox1.Text
or.. since you didnt post the full code here.. try this rather than creating the object form1.returner();