So far if a user inputs something, I store in a label property. I know this can't be right. How can I update a variable based on user input for use across whichever event needs to use it?
This is one of many things I've tried. I can't even figure out the right search terms to google the solution for what I need to do.
namespace Words
{
public partial class formWords : Form
{
int x = 5;
int y = 50;
int buttonWidth = 120;
int buttonHeight = 40;
string fileList = "";
string word = "";
string wordFolderPath = #"C:\words\";// this is the variable I want to change with the dialog box below.
private void selectWordFolderToolStripMenuItem_Click(object sender, EventArgs e)
{
FolderBrowserDialog folder = new FolderBrowserDialog();
if (folder.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string folderPath = folder.SelectedPath;
formWords.wordFolderPath = folderPath;
}
}
wordFolderPath is a variable public to your class (but private outside of it). This means that anything inside your class can freely read/write the value.
As for your syntax, you can just use the variable name or use this.:
private void DoAThing()
{
wordFolderPath = "asdf";
this.wordFolderPath = "qwerty"; //these are the same
}
You can't use the current class's name when accessing an internal variable. formWords is a type, not an instance.
The only advantage of using this is because it is legal to have a variable of the same name defined within your method. Using this keyword makes sure you are talking about the class's member.
Just changing formWords.wordFolderPath = folderPath;
to wordFolderPath = folderPath;
or this.wordFolderPath = folderPath;
should fix your problem
Also, there should have been a compiler error in the error list saying "An object reference is required for the non-static field, method, or property..."
If you don't have your error list visible you should definitely turn it on.
Related
I'm trying to create a Calculator with a Class. However using references from the internet particularly from this website (https://www.sourcecodester.com/tutorials/c/7548/simple-calculator-using-class-c.html)
It did not mention to declare "Information" or whatsoever.
When I typed in the code, the error list return with Information does not exist in current context.
Is there a way to modify the code below? Thank you so much.
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
}
private void Form4_Load(object sender, EventArgs e)
{
}
public void RadioButton_Click(object sender, System.EventArgs e)
{
//call a constructor method and return to cal as an instance of a class
calculate cal = new calculate();
//declaring the string variable represent as a textbox
string txtnum1 = TextBox1.Text;
string txtnum2 = TextBox2.Text;
//declaring the double variable
double dbl_val1 = default(double);
double dbl_val2 = default(double);
if (**Information**.IsNumeric(txtnum1) && **Information**.IsNumeric(txtnum2)) //check if the textbox has a numeric value
{
//convert the string to double
dbl_val1 = double.Parse(txtnum1);
dbl_val2 = double.Parse(txtnum2);
//get the value of the converted variable
//to pass it into the variable in the class
cal.num1 = dbl_val1;
cal.num2 = dbl_val2;
//the condition is, if the radiobutton is clicked,
//the operation of MDAS executes.
if (Radio_Multiplication.Checked)
{
//result:
cal.multiply(); //call a subname in a class for multiplying
}
else if (Radio_Addition.Checked)
{
//result:
cal.add(); //call a subname in a class for adding
}
else if (Radio_Subtraction.Checked)
{
//result:
cal.subtract(); //call a subname in a class for subtracting
}
}
else
{
//the result is:
//if the textbox is empty or has a string value
TextBox3.Text = "Enter a number";
return;
}
//put the result of the MDAS to a textbox.
TextBox3.Text = cal.total.ToString();
}
}
I had a quick look at the link and they don't appear to have declared Information anywhere nor have they indicated that they've overridden anything so...I don't know.
That line, however, is just validating that the information entered into the two text boxes are actually numbers and not anything else that can't be calculated.
There are lots of methods you could use to check those numbers. Options would include, but are not limited to:
if(Int32.TryParse(txtNum1, out int temp1) && Int32.TryParse(txtNum2, out int temp2))
{
do stuff;
}
or
if(txtNum1.All(char.IsDigit) && txtNum2.All(char.IsDigit))
{
do stuff;
}
There are other options, but those two might be worth looking into.
Downloading the sample project, I had a look at what Information refers to. Turns out, it's a class from the Microsoft.VisualBasic namespace, presumably for exposing certain aspects of the VB core library to all .NET languages. You can use it in your program by adding a reference to Microsoft.VisualBasic to your project and adding:
using Microsoft.VisualBasic;
to the top of your code file.
(Personally, I can't imagine that this approach is terribly efficient. It's supposed to take an object and determine if it can be evaluated as a number, and I have no idea what approaches it uses to make that deduction based on any random object. You would probably be better off using one of the alternatives that Benny O'Neill suggests.)
So I've been trying to figure out how to get my code to work all night. I've been reading up on all kinds of stuff and trying to identify what I'm doing wrong, but everything I try I end up at the same issue. I'm trying to change a variable in my class by referencing it in a method so it will change in the class and not just locally. But I don't know what to put as a parameter for the ref Storyboard SB. Can someone tell me what should be done, I've tried setting it to null, even through a variable and it doesn't work. Also 'StoryBoard' is the class that I'm writing the code in.
public class StoryBoard
{
public string[] TextBoxes = new string[10];
public int Counter = 0;
private void RtClickButton_Click(object sender, EventArgs e)
{
RtClickButton_ClickImpl(sender, e, "what would I put here?");
}
private void RtClickButton_ClickImpl(object sender, EventArgs e, ref StoryBoard SB)
{
string TBT = TxtBox.Text;
switch(Counter)
{
case 0:
TextBoxes[Counter] = TBT;
break;
}
SB.Counter++; // Adds 1 to the counter.
LtClickButton.Enabled = true;
TxtBox.Clear(); // Clears the text box.
}
}
Try simply
Counter++;
or if in doubt you can use the this keyword to refer to instance members of this class, e.g
this.Counter++; // Adds 1 to the counter.
To expand upon this, all variables from the current object will always be accessible in a normal method (i.e. not static) unless a variable of the same name exists in the same scope, where the scope can be the method or a single block between curly braces.
If you use the this keyword it will always reference the variable that belongs to the object/class and not an inline variable that is defined in a different scope.
But I don't know what to put as a parameter for the ref Storyboard SB.
Keep a private member variable for SB:
private StoryBoard _SB = null; //A member variable to hold the StoryBoard object
public class Form1WhatEver
{
public Form1WhatEver()
{
//Instantiate a reference to the StoryBoard and hold it in the private member variable
_SB = new StoryBoard();
}
public string[] TextBoxes = new string[10];
public int Counter = 0;
private void RtClickButton_Click(object sender, EventArgs e)
{
RtClickButton_ClickImpl(sender, e, ref _SB); //Pass the instance of StoryBoard byRef.
//Check that our _SB Counter variable was incremented (+1)
System.Diagnostics.Debug.WriteLine(_SB.Counter.ToString());
}
private void RtClickButton_ClickImpl(object sender, EventArgs e, ref StoryBoard SB)
{
string TBT = TxtBox.Text;
switch(Counter)
{
case 0:
TextBoxes[Counter] = TBT;
break;
}
SB.Counter++; // Adds 1 to the counter.
LtClickButton.Enabled = true;
TxtBox.Clear(); // Clears the text box.
}
I am creating a program to access a database.
The code that is causing me trouble is meant to open a new form when a button is pressed. It then gets data based on the selected values in a listbox on the main form and is needed to send that data to the second form to be placed in textboxes and labels.
The problem I have, is that in order for the code to execute without throwing the Error
"An object reference is required for the non-static field, method or property..."
I must make the method in the secondary form static; however this prevents me from accessing the controls on the secondary form.
Main Form Code Snippet:
private void MemView_Click(object sender, EventArgs e)
{
string selected = lstMember.SelectedItems[0].Text;
//MessageBox.Show(selected);
string[] data = P.selectMem(selected);
MessageBox.Show(data[0]);
MemForm mem = new MemForm(); //How to open a designed form
mem.Show(); //Displays the addmem form
MemForm.getData(data);
}
Secondary Form Code Snippet:
public void getData(string[] Data)
{
int index = 0;
bool loop = false;
string text;
while (loop == true)
{
if (index < 10)
{ text = "tb0" + index.ToString(); }
else
{ text = "tb" + index.ToString(); }
index = index + 1;
}
}
My secondary code snippet is meant to use the loop to fill all the data into the textboxes without me having to manually write out each tb00.Text = data[] etc.
I am unable to access the FindControls() method in C# most likely due to the need for a static method.
The P class used in the Main Form performs the SQL code and is working fully.
I've tried to give enough information for an answer, however if more is needed just ask in a comment I will try and provide more. :)
If getData() is a non-static method in MemForm, you need an instance of MemForm to use it. You have one: MemForm mem = new MemForm(); Use the mem object which is an instance of MemForm.
mem.getData(data);
I'm making a program that estimates energy usage. I have a list of appliances and have created a class for them:
List<Appliances> appliancesList = new List<Appliances>
{
new Appliances("Toaster",6000, durationInput),
new Appliances("Washing Machine",7000,durationInput),
};
class Appliances
{
public String name;
public int energy_rating;
public int duration;
public Appliances(String nameInput, int energy_ratingInput, int durationInput)
{
name = nameInput;
energy_rating = energy_ratingInput;
duration = durationInput;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
durationInput = int.Parse(textBox1.Text);
}
As you can see in the class, I have tried to create a variable that allows the user to enter the duration and then assign that value to the appropriate appliance in the list. I get a red line under 'durationInput' in the list section and the error says 'The name durationInput does not exist in the current context'
Any ideas?
You should be referencing duration. Durationinput is your parameter. The only thing you should be doing with durationinput is setting the variable duration equal to durationinput. Everything else should be referencing duration.
change
durationInput = int.Parse(textBox1.Text);
to
this.duration = int.Parse(textBox1.Text);
Your constructor accepts 3 parameters.
public Appliances(String nameInput, int energy_ratingInput, int durationInput)
In your list statement, you only pass two variables.
new Appliances("Washing Machine",durationInput)
You need to either pass three variables
new Appliances("Washing Machine",0,durationInput)
or overload your constructor.
I have something to do under a button click (add values to listbox) only if a particular string changes from its previous value. How do I manage this? Below is a sample of my code:
private void button6_Click(object sender, EventArgs e)
{
string x = //some varying value I get from other parts of my program
listBox1.Items.Clear();
listBox1.Items.Add(x + /*other things*/);
}
I can at times have same value for string x from previous value when clicking button6. In such cases I don't want listBox1 to add the item (string x). How to add to listbox only when value of string changes? There's no way to predetermine string x. It gets value when program is running.
Note: adding values to listBox1 every single time and later deleting the duplicates wont work in my program.
Have you considered keeping a copy of the old string value around in a private field, and simply comparing the new value to the old value to see if they match?
For example:
// holds a copy of the previous value for comparison purposes
private string oldString = string.Empty;
private void button6_Click(object sender, EventArgs e)
{
// Get the new string value
string newString = //some varying value I get from other parts of my program
// Compare the old string to the new one
if (oldString != newString)
{
// The string values are different, so update the ListBox
listBox1.Items.Clear();
listBox1.Items.Add(x + /*other things*/);
}
// Save the new value back into the temporary variable
oldString = newString;
}
Edit: As the other answers suggest, there are certainly other, more complicated solutions, like encapsulating all access to the string value in a property, or wrapping the string in a custom class. Some of these alternatives have the potential to be "cleaner", more object-oriented approaches. But they're all more complicated than simply saving the previous value in a field. It's up to you to decide whether your specific use case merits the complicated solution, or a simpler one. Think about long-term maintainability, not what's easier for you to implement right now.
string last = string.Empty;
private void button6_Click(object sender, EventArgs e)
{
string x = //some varying value I get from other parts of my program
if(x!=last)
{
listBox1.Items.Clear();
listBox1.Items.Add(x + /*other things*/);
last = x;
}
}
If this string is super important and gets passed around alot, maybe you should wrap it in a class. The class can hold the string value as a property, but also keep track of when it has changed.
public class StringValue
{
private bool _changed;
public string StrValue{get; set{ _changed = true;}
public bool Changed{get;set;}
}
this is rudimentery of course
I'm not sure I understand completely, but it sounds like you should be using a property to set String x;
string _x = string.Empty;
public string X
{
set
{
if(value != this._x)
{
DoFancyListBoxWork();
this._x = value;
}
}
get
{
return this._x;
}
}
If this is web application, store your last value into session variable. If this is windows application, store it at a class level variable or in singleton class and use this last value for comparison with new value.
On the page load add the current value to viewstate and at the button click check the current value is equal to the value in the view state. If both are equal we can say that the value is not changed.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["CurrentValue"] = Your Value;
}
}
protected void btnSubmit_click(object sender, EventArgs e)
{
if (NewValue== ViewState["CurrentValue"].ToString())
{
lblmsg.Text = "value is not changed..";
return;
}
else
lblmsg.Text = "value is changed..";
}
You can check the detailed article in this link.
Check Control Value is changed or not
First, I'd like to ask you to check most of the other answers. They are more complete, in that they treat more global issues of tracking the changes of a variable.
Now, I'm assuming, from reading the snippet of code you provided, that you need to track if a string was changed by the user. So, in other words, you probably have a TextBox or other kind of control through which the user can change that value. This is where you should focus your attention: just consume the TextChanged event.
If, however, I'm mistaken and your string comes from any other kind of external source, either use the wrapper class suggested by #Ryan Bennett or, if you are using .Net 4, use a dynamic container, which raises a PropertyChanged event whenever any property is changed.