So a question on a quiz in my programming class is this: "Create a value returning method called squareThis() independent of but called from the test app. This method cannot refer to any object within the application. Rather, pass the double value dblValue to the method and place the result into lblOutput once btnProblem4 is pressed. Have the method return dblValue squared."
I have established dblValue and called the method in a click event, specifically btn_4. I was not sure what he meant by calling it independently, and created another .cs within the program specifically for this problem. This is the code for the click event.
public void btnProblem4_Click(object sender, EventArgs e)
{
FinalCalc c = new FinalCalc();
lblOutput.Text = c.FinalPiece();
}
This is the separate class form I created in the program:
namespace MethodsQuiz
{
class FinalCalc
{
public string FinalPiece()
{
double Math4 = Math.Pow(1.5, 2);
string mathfinal = Math4.ToString();
return mathfinal;
}
}
}
The instructor marked this question with this comment: "#4 problem? Don't find the method."
This is my first post, so I apologize if this is in a terrible format. I am not asking you to solve this question for me; only to explain the question and the instructors comment, as well as what I have done wrong. Again, I am not seeking you to answer this question, just to provide assistance so that I can understand. Thank you.
Probably he meant having a self static method in the same class (in your control or Forms code behind class) and call that method in your button click event like
private static string FinalPiece(double dblVal)
{
double squared = dblVal * dblVal;
return mathfinal.ToString();
}
public void btnProblem4_Click(object sender, EventArgs e)
{
lblOutput.Text = FinalPiece(10);
}
Related
I have two stupid questions :
The first one :
I have already asked this and I'm truly sorry to ask it again (even more so because there are a lot of posts about it), but now I really don't understand why that happens even if I read every other post, here is my code :
public class PageTitre {
...
public void situation(string s) {
onglet.get_Range("C11").Value = "(" + s + ")";
}
}
public class PPE_Process {
public static PageTitre pageTitre;
public static void MainProcess() {
...
pageTitre = new PageTitre();
...
}
}
public partial class PPE_Ribbon {
private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
{
PPE_Process.pageTitre.situation(SituationEditBox.Text);
}
}
I have tried some other things, like putting situation as a variable of PageTitre and having a get and a set, and
private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
{
PPE_Process.pageTitre.set_situation(SituationEditBox.Text);
}
Or
private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
{
PPE_Process.pageTitre.situation = SituationEditBox.Text;
}
But nothing worked, with the same error: cannot explicitly call operator or accessor.
I guess there is a problem with the static? If that is the case, here is my second question:
Second one :
I read a lot of documentation about it but I really can't understand what is the use of "static"... Is it just so that we can't change the value outside of the class, or something like this? Then, would it really change something if I take off every static there is in my code?
Again, I am sorry that you have to answer this question again and again, but I understand a lot better if that is directly related to my code, and not someone answering someone else about some other random code, which has a different problem than mine. :/
Edit to add more information:
There shouldn't be any problem with .Value or .get_Range, as it works on other parts of the code, but
For .Value, here is the information given by Visual Studio:
void Range.set_Value([object RangeValueDataType = System.Type.Missing], [object value = System.Type.Missing])
For .get_Range: Excel.Range_Worksheet.get_Range(object Cell1, [object Cell2 = System.Type.Missing])
For static, I still don't really understand all these "instances" things, but I will try to look more, and add another question in this forum if I still don't understand after this.
To your first question: I don't see any problem with your call of the method situation, maybe the problem is the statement inside the method (get_Range("C11"))?
To your second question: When you make a variable/property/method static it means that it is independent from any instance (object) of the class. Otherwise you couldn't access the property PPE_Process.pageTitre without an instance of PPE_Process.
Alrighty, I changed nothing in my code but now it works with
private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
{
PPE_Process.pageTitre.situation = SituationEditBox.Text;
}
So... I don't know, it was maybe a problem with the build of my solution, but that's pretty fortunate :)
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.)
Ok so I'm attempting to create a simple game. In a nutshell it's a resource management game where the player will attempt to manage a thieves guild. In regards to running missions I've created a Thief class, a new instance of which is created when a new thief is recruited. I have coded within the thief class the ability to gain experience and level up.
Here's my specific problem:
I want the player to be able to select which thief/thieves to send on a mission. I have thought about it and figured that opening a new form and populating it with checkboxes is the easiest way to allow this. These checkboxes will be related to a List<thief> of thieves, the player then checks the thieves s/he wants to send and these are then stored in another List<thief> and passed on to the run mission function.
I've built a separate project with the intention of testing and playing around with this before putting it into the main program. The test project consists of two forms: The first (frmMain) with a textbox to hold the selected options and a button to open the second form (frmSelect). Currently I can open and populate the second form (frmSelect) but when I try to add the checked options to the textbox I simply...well can't.
So far I have tried directly accessing the textbox by typing frmMain.txtOptionsDisplay in the cs file of frmSelect but it causes the following error:
An object reference is required for the non-static field, method or
property
I tried to create a new form in frmSelect and make it equal to the active instance of frmMain with: Form frmTemp = frmMain.ActiveForm; and then alter the textbox using frmTemp as a go-between but that produced the error:
'System.Windows.Forms.Form' does not contain a definition for
'txtOptionsDisplay'.
Having searched both google and stackoverflow forums I've encountered answers that I either have never heard of (Threading) or answers that I kind've recognise but can't interpret the code pasted to make it relevant to my problem (delegates).
Any advice or pointers would be fantastic.
EDIT:
frmMain code:
public frmMain()
{
InitializeComponent();
selections.Add("Option 1");
selections.Add("Option 2");
}
private void btnClick_Click(object sender, EventArgs e)
{
frmSelectOptions.Show();
int length = selections.Count();
for (int i = 0; i < length; i++)
{
CheckBox box = new CheckBox();
box.Text = selections[i];
box.AutoSize = true;
box.Location = new Point(50, 50*(i+1));
frmSelectOptions.grpControls.Controls.Add(box);
}
}
public void updateText(string option)
{
txtOptionsDisplay.Text += option;
}
}
frmSelect code:
public List<CheckBox> selectedOptions = new List<CheckBox>();
Form frmTemp = frmMain.ActiveForm;
public frmSelect()
{
InitializeComponent();
}
private void btnSelect_Click(object sender, EventArgs e)
{
foreach (CheckBox box in grpControls.Controls)
{
if (box.Checked == true)
selectedOptions.Add(box);
}
this.Hide();
}
}
I hope this formats correctly... I'm kinda new and don't know how to indent. Oh look there's a preview...
Does this help?
Your problem is that controls defined within a form by default receive the private access identifier. Hence you could just add a property along the lines of
public ControlType ProxyProperty {
get {
return txtOptionsDisplay;
}
}
Besides from that you should think about wether what you're trying is actually a good solution. Manipulating forms from one to another will become a huge clusterfuck in terms of maintenance later on.
I'd suggest using the Singleton pattern for your frmMain. This will help safeguard you from accidentally launching another instance of frmMain and at the same time, will give you access to frmMain's objects. From there, you can either write accessors to Get your txtOptionsDisplay or you can make it public. Below is an example:
public class frmMain
{
private static frmMain Instance = null;
private static object LockObj = new object();
public static frmMain GetMain()
{
// Thread-safe singleton
lock(LockObj)
{
if(Instance == null)
Instance = new frmMain();
return Instance;
}
}
public string GetOptionsDisplayText()
{
return txtOptionsDisplay.Text;
}
}
public class frmSelect
{
private void frmSelect_Load(object sender, EventArgs e)
{
// Set whatever text you want to frmMain's txtOptionsDisplay text
txtDisplay.Text = frmMain.GetMain().GetOptionsDisplayText();
}
}
If you do go this route, don't forget to update Program.cs to use frmMain's singleton.
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Application.Run(new frmMain()); - Old method
Application.Run(frmMain.GetMain());
}
ladies and gentlemen, once again I unfortunately am going to bother you with newbie stuff. I have searched for this information for hours, so if there’s a thread with what I want on it, it’s buried deeper than I could find.
This was my first question here, and Mark Hall was kind enough to set me straight. Since then, I have created a new project and recreated my first three screens as user controls – a container/login, a choice screen, and a main screen (currently empty). If a user has more than one collection, the choice screen pops up and allows them to choose a collection.
I did run into a snag with parameters, but I’m solving that by overloading the form declaration (solution found here) – yes, I know it’s much better to send parameters through calls, but I’d hate to have to create a call for each parameter (do I?) and… OK, OK, I’m better at this than {get, set}. Man, I hate being a newbie.
Anyways, I’m having trouble with the choice form – I can’t seem to call it, close it, then go to the main form. I have no problem (if there’s only one collection) in going straight to the main form, it’s that darn choice form. Yes, I know I could include a choice datagridview, but a few of our end users aren’t the sharpest bulb in the tool shed, and need hand-holding. Anyways, here’s the code.
CONTAINER/LOGIN SCREEN
namespace DeleteThis
{
public partial class ContainerForm : Form
{
Main Main = new Main();
LoginCollectionChoice LoginChoice = new LoginCollectionChoice();
DataTable dtPermissions = new DataTable();
public ContainerForm()
{
InitializeComponent();
Main.ExitEvent += new Main.ExitEventHandler(Main_ExitEvent);
LoginChoice.ExitEvent += new
LoginCollectionChoice.ExitEventHandler(LoginChoice_ExitEvent);
}
void LoginChoice_ExitEvent(object sender, EventArgs e)
{
pnlcontainer.Controls.Remove(LoginChoice);
}
void Main_ExitEvent(object sender, EventArgs e)
{
pnlcontainer.Controls.Remove(Main);
}
private void btnLogin_Click(object sender, EventArgs e)
{
LoginProcedure();
}
private void LoginProcedure()
{
DataTable dtPermissions = AdminClass.GetCollectionsForUser(int.Parse(txtbxUserName.Text));
if (dtPermissions.Rows.Count == 1)
{
//Valid user, one collection. Head right in.
pnlcontainer.Controls.Add(Main);
Main.BringToFront();
}
else
{
//More than one collection found. Giving user choice
LoginCollectionChoice LoginChoice = new LoginCollectionChoice(dtPermissions);
pnlcontainer.Controls.Add(LoginChoice);
LoginChoice.BringToFront();
}
}
private void btnExitProgram_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I hope I didn't kill anything in the snipping. And now the choice screen…
public partial class LoginCollectionChoice : UserControl
{
public delegate void ExitEventHandler(object sender, EventArgs e);
public event ExitEventHandler ExitEvent;
private static DataTable dtPermit;
DataTable dtPermissions = new DataTable();
public LoginCollectionChoice()
{
}
public LoginCollectionChoice(DataTable dtPermissions)
{
InitializeComponent();
GrdCollection.DataSource = dtPermissions;
dtPermit = dtPermissions;
}
private void btnChoose_Click(object sender, EventArgs e)
{
//Code for the user to choose a collection
ExitEvent(this, new EventArgs());
}
}
I’ve snipped all non-relevent code, I hope you gentlemen and ladies can help this newbie get on the right path. Please, be gentle, you wouldn’t want to see me cry, would you? :) Oh! And if you know of any great tutorial sites, please email them to me. I'd prefer to spend a week on tutorials than a week on stumbling and asking here. Thank you all very much.
Are you calling logonForm.Show()?
It seems like you'd need to show it that way.
You use BringToFront(), but I think it needs to be shown first.
The first thing that jumps out to me is that you are calling
LoginCollectionChoice LoginChoice = new LoginCollectionChoice(dtPermissions);
which is creating a local variable called LoginChoice, which is not the same as your class variable even though they share the same name.
What you want to do is to not declare a local variable in that method. Change that line to
LoginChoice = new LoginCollectionChoice(dtPermissions);
Having said that, I believe tylerjgarland in that you need to call .Show() first. And the way you are closing the form is certainly odd. I would create a form, showDialog, get the result and then close the form that way.
I'll admit sometimes the deeper nuances of the keyword static escape me.
Here's what I'm seeing:
public partial class Default : CSSDEIStatusBase
{
private static Default _csWitWeb;
protected void Page_Load(object sender, EventArgs e)
{
//DoStuff
_csWitWeb = this;
//OtherStuff
}
public static void ForceLoadSyncOperation(int? index)
{
Default._csWitWeb.LoadSelectedSyncOperation(index);
}
}
The only references to ForceLoadSyncOperation are:
Default.ForceLoadSyncOperation(index);
or
Default.ForceLoadSyncOperation(null);
Both of these calls originate from:
public partial class DataOriginUserControl : System.Web.UI.UserControl
and are not located inside of static methods.
E.G:
protected void btnCancelSyncOperation_Click(object sender, EventArgs e)
{
this.lblErrorMessage.Text = string.Empty;
this.lblErrorMessage.Visible = false;
int index = _syncOperation.Sequence - 1;
Default.ForceLoadSyncOperation(index);
}
This all seems really quirky to me. Does this smell to anyone else? Not really sure how to untangle it, though, as I can't exactly create an instance of the Default page inside of a user control.
Thoughts? Thanks for reading.
protected void LoadSelectedSyncOperation(int? index)
{
SyncOperationConfiguration[] syncOperations = CSServiceClient.GetInterfaceConfiguration().SyncOperationConfigurations.ToArray();
PopulateSyncOperationsListView(syncOperations);
SyncOperationConfiguration syncOperation = null;
try
{
syncOperation = syncOperations[index.HasValue ? index.Value : 0];
}
catch
{
syncOperation = syncOperations[0];
}
ucDataOrigin.LoadSyncOperationData(syncOperation);
Session["ConfigMenuActiveIndex"] = 1;
menuConfiguration.Items[(int)Session["ConfigMenuActiveIndex"]].Selected = true;
mvwConfiguration.ActiveViewIndex = (int)Session["ConfigMenuActiveIndex"];
}
Presumably, the user control is contained within the Default page and the static member is being used as a shortcut to get the current instance of Default. I would've done it this way:
Default defaultPage = this.Page as Default;
if (defaultPage != null)
{
defaultPage.LoadSelectedSyncOperation(index);
}
Using a static member in this way is not safe. It opens up the door for race conditions. There is the potential risk that the user control is loaded in another page and calls LoadSelectedSyncOperation() on a separate request's instance of Default, thus wreaking all kinds of potential havoc.
I don't know what LoadSelectedSyncOperation does but this code looks weird. Whenever you click btnCancelSyncOperation you end up calling this method on some page, but you never know on which of them. It doesn't make much sense to me.
I would definitely say your concerns are valid. I can't think of any reason that this design would make sense, ever. This would throw a flag for me, too.
Based on your reply to my comment, if the Default.LoadSelectedSyncOperation is not dependent upon the Default page somehow, then I suggest it be refactored into a separate class (not an ASP.NET Page).
Whether it makes sense for the method or new class to be static or not is a separate concern and would be based on the logic contained within the method.