So I am trying to do this for a hw and in my class I have this double method for converting from cm to inch:
public decimal Conversion(decimal Input)
{
return Input * (decimal)0.393701;
}
The problem is when I try to call it in a form, and I need to send arguments to it.
public partial class frmCmVoInch : Form
{
public frmCmVoInch()
{
InitializeComponent();
}
public frmCmVoInch(mainForm parent)
{
InitializeComponent();
MdiParent = parent;
}
private void btnKonverzija_Click(object sender, EventArgs e)
{
decimal parsed;
decimal.TryParse(txtVlez.Text, out parsed);
CmVoInch cmVoInch = new CmVoInch(decimal.Parse(txtVlez.Text));
rtbIzlez = txtVlez.Text + " cm = " + cmVoInch.Konverzija(parsed);
}
}
This is basically a typo:
rtbOutp = txtInp.Text + " cm = " + CmVoInch.Conversion(decimal.Parse(txtInp.Text));
Should be:
rtbOutp = txtInp.Text + " cm = " + cmVoInch.Conversion(decimal.Parse(txtInp.Text));
Note the change in case of CmVoInch. The first is the type name, so attempts to call an instance method without an instance, hence the error an object reference is required for the nonstatic field method or property. The second correctly refers to the instance of that class you created on the previous line.
You also need to change to set the text property of the RichTextBox, as you can't assign a string to it:
rtbOutp.Text = txtInp.Text + " cm = " + cmVoInch.Conversion(decimal.Parse(txtInp.Text));
but it is String, and it wont accept it even if I convert it to
decimal. Any way I can fix this?
the issue is not with the Conversion method.
the issue is the btnKonverzija_Click method returns void and you're trying to return a string value. you cannot do that.
private void btnKonverzija_Click(object sender, EventArgs e)
{
CmVoInch cmVoInch = new CmVoInch(decimal.Parse(txtInp.Text));
return txtInp.Text + " cm = " + CmVoInch.Conversion(decimal.Parse(txtInp.Text));
}
note - C# is a case-sensitive language, currently, you're calling the Converion method as if it belongs to a class rather you should use cmVoInch.Conversion not CmVoInch.Conversion.
full solution:
private void btnKonverzija_Click(object sender, EventArgs e)
{
CmVoInch cmVoInch = new CmVoInch(decimal.Parse(txtInp.Text));
rtbIzlez.Text = txtInp.Text + " cm = " + cmVoInch.Conversion(decimal.Parse(txtInp.Text));
}
Related
I have a class with the following code:
public delegate void EventHandler(HMIEventArgs e);
public event EventHandler OnEvent;
private void ReadReg(RegisterMap register)
{
if (!_hmiConnected) return;
var eventArgs = new HMIEventArgs();
var handler = OnEvent;
try
{
byte slaveId = 1;
ushort startAddress = register.Register;
eventArgs.Event = Events.GotData;
eventArgs.IPAddress = _hostname;
eventArgs.Name = register.FriendlyName;
ushort[] val = _master.ReadHoldingRegisters(slaveId, startAddress, 1);
eventArgs.Data = val[0];
handler?.Invoke(eventArgs);
// -------- THIS GETS PRINTED ------------
Debug.WriteLine("Got data from " + _hostname + ":" + register.Register + "(" + register.FriendlyName + ") : " + val[0]);
}
catch (Exception err)
{
Debug.WriteLine(err.ToString());
}
}
Several instances of this class are created in another class :
new Thread(() =>
{
tasks.Add(Task.Factory.StartNew(() =>
{
_masters.Add(new HMIMaster().Connect(ipAddress, port).SetRegisters(registers));
_masters.Last().OnEvent += HMIEvent;
Debug.WriteLine(_masters.Count + " masters");
}));
}).Start();
private static void HMIEvent(HMIEventArgs e)
{
// HOWEVER THIS SOMETIMES DOESN'T SHOW FOR
// ALL INSTANCES OF THE PREVIOUS CLASS
Debug.WriteLine(">> in logger (" + e.IPAddress + " " + e.Event + ") >> " + e.Name + " :: " + e.Data);
var handler = OnEvent;
handler?.Invoke(e);
}
Am I doing something wrong here?
I would use a static event to avoid registering every time on new instance and un-register on dispose (to void memory leaks). No locking is required in your case so I would simplify it like that:
(First class)
public static event EventHandler<HMIEventArgs> HMIEvent;
private void OnHMIEvent(HMIEventArgs e)
{
HMIEvent?.Invoke(this, e);
}
private void ReadReg(RegisterMap register)
{
...
OnHMIEvent(new HMIEventArgs()
{
Name = register.FriendlyName,
Event = Events.GotData,
IPAddress = _hostname,
eventArgs.Data = val[0]
});
...
}
(Second Class)
...
FirstClass.HMIEvent += FirstClass_HMIEvent; // Probably in your static constructor, register only once (unregister if required on disposal)
...
private void FirstClass_HMIEvent(object sender, HMIEventArgs e)
{
// (FirstClass)sender can be used here if required
}
By the way those two lines at your sample code should not be there (on your static HMIEvent method, you didn't provide us what is the OnEvent on your second class and you dont need to pass it on the handler var every time):
var handler = OnEvent;
handler?.Invoke(e);
[UPDATE: Added Form1() constructor]
I am trying to match some data from certain clases into combo box values in windows form application.
What I've done until now looks like this:
(This class has some region[] values that I want to store in a combobox, depending on enum Project)
public Form1()
{
formatWorker.DoWork += worker_DoWork;
formatWorker.RunWorkerCompleted += worker_RunWorkerCompleted;
extractWorker.DoWork += extractWorker_DoWork;
extractWorker.ProgressChanged += extractWorker_ProgressChanged;
extractWorker.RunWorkerCompleted += extractWorker_RunWorkerCompleted;
InitializeComponent();
projectBox.DataSource = Constant.projects.ToString();
projectBox.SelectedIndex = (int)Regions.Project.NBTevo;
PopulateUsbDevices();
}
class Regions
{
public enum Project
{
NBT = 0,
NBTevo = 1,
MGU = 2
}
string[] regions = { "ARG", "AUSNZ", "ECE", "IND", "ISR", "LA", "ME", "NA", "NAF", "NANT", "PAL", "SEA", "TC", "ZA" };
public string[] GetRegionsForProject(Project proj)
{
//all directories from /Databases/proj[i]
string[] allDirectories = Constant.ExtractFileNames(Directory.GetDirectories(Constant.path + "//" + Constant.projects[(int)proj]));
string[] availableSubDirectories = Enumerable.Intersect(allDirectories, regions).ToArray();
return availableSubDirectories;
}
}
The next class stores a certain pattern files
class DBVersion
{
public string[] GetVersion(string proj, string region)
{
string pattern = "^" + proj + "_" + region + "_" + #"(\d+\.\d+\.\d+_[a-zA-Z0-9_]+)\.iso$";
string[] files = Directory.GetFiles(Constant.path + "\\" + proj + "\\" + region + "\\images\\", "*.iso", SearchOption.AllDirectories);
return files;
}
}
I am trying to build a dependency, for example, depending on the selected values in projectBox and regionBox some versions will appear in versionBox
private void projectBox_SelectedIndexChanged(object sender, EventArgs e)
{
isoPaths.Clear();
populateRegions((Regions.Project)Enum.Parse(typeof(Regions.Project), projectBox.SelectedValue.ToString()));
regionBox.SelectedIndex = 0;
regionBox_SelectedIndexChanged(null, null);
}
private void regionBox_SelectedIndexChanged(object sender, EventArgs e)
{
string[] versionPaths = version.GetVersion(projectBox.SelectedValue.ToString(), regionBox.SelectedItem.ToString());
isoPaths.Clear();
isoPaths.AddRange(versionPaths);
populateVersions(Constant.ExtractFileNames(versionPaths));
//versionBox.SelectedIndex = 0;
//versionBox_SelectedIndexChanged(null, null);
}
private void versionBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void populateRegions(Regions.Project proj)
{
this.regionBox.DataSource = region.GetRegionsForProject(proj);
}
private void populateVersions(string[] versions)
{
this.versionBox.DataSource = version.GetVersion(
projectBox.SelectedItem.ToString(),
regionBox.SelectedItem.ToString());
}
After running, I don't have nothing stored in ComboBox
If you want to bind a DataSource to a ComboBox you should use :
An object that implements the IList interface or an Array
according to the ComboBox.DataSource Property documentation
So this line in the constructor of Form1:
projectBox.DataSource = Constant.projects.ToString();
has to be changed into this:
projectBox.DataSource = Constant.projects;
The rest of the comboboxes is empty because the problem cascades from one to the next. If one is empty then the rest cannot be filled appropriately
i have passes some values though a constructor from one from to another. the values are successfully transferred in another form through constructor but when i display them in a textbox the values become null and the textbox remains empty. i am showing the code of the constructor for both forms.
starting form which opens another form
private void lbl_imgpass_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string img = img_name.Text;
Setimgpass st = new Setimgpass(img);
st.Show();
}
form1(from where the values are transferred to another form)
else
{
first = textBox2.Text;
second = textBox3.Text;
third = textBox4.Text;
Adduser add = new Adduser(x1low, x1up, x2low, x2up, x3low, x3up, y1low, y1up, y2low, y2up, y3low, y3up, first, second, third);
this.Hide();
}
second form(where the values are received)
public Adduser(string x1low, string x1up, string x2low, string x2up, string x3low, string x3up, string y1low, string y1up, string y2low, string y2up, string y3low, string y3up,string first, string second, string third)
{
InitializeComponent();
frst = first;
secnd = second;
thrd = third;
lowx1 = x1low;
upx1 = x1up;
lowx2 = x2low;
upx2 = x2up;
lowx3 = x3low;
upx3 = x3up;
lowy1 = y1low;
upy1 = y1up;
lowy2 = y2low;
upy2 = y2up;
lowy3 = y3low;
upy3 = y3up;
txt_imgpass.Text = frst + " " + secnd + " " + thrd;
}
txt_imgpass is the textbox in which i want values.
In the first form the values are passed to the object "add" that you created .
You can simply use static variables to pass data from one form to another .
EDIT
You might as well want to try something like this instead of static variables
Form 1 :
assuming this is the button you click on to show the second form
private void button1_Click(object sender, EventArgs e)
{
Form2 form = new Form2(textBox1.Text);
form.Show();
}
in Form 2 you can do something like this
public Form2(string text)
{
InitializeComponent();
label1.Text = text;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I keep getting the error
" XXXX does not exist in this current context".
I know there are plenty of similar questions, but they don't help me as I'm not very good at C# & asp.net.
I've been struggling with this piece of code. Basically I need to have a calculate cost (Which is mean tot be done in the Beverage class, and it outputted on the About page.
My code is very messy as I honestly have next to no idea what I'm doing.
Beverage class:
public class Beverage
{
string fruit;
int kg;
int cost;
int cal;
public string getOutputString()
{
return " Your selected Beverage is made of " + kg + " of " + fruit + ". " +
"The cost is £ " + cost + " and has " + cal + ".";
}
public static int CalculatePrice()
{
int cost = (TextBox1.text + TextBox2.text);
int cal = TextBox1.Text + TextBox3.Text;
}
}
About code behind:
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e)
{
MyFruit = Session["Fruitname"] as List<string>; //Create new, if null
if (MyFruit == null)
MyFruit = new List<string>();
DropDownList1.DataSource = MyFruit;
DropDownList1.DataBind();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
{
decimal total = calculatePrice(DropDownList1.SelectedItem.Text,
TextBox1.Text.Trim());
lbl1.Text = "You would like " + TextBox1.Text.Trim() +
DropDownList1.SelectedItem.Text + "(s) for a total of $" +
total.ToString();
}
}
public List<string> MyFruit { get; set; }
}
The errors are always for TextBox1, TextBox2, TextBox3 & calculatePrice.
You are getting the error because you are trying to access TextBox1.Text outside About class. Only this class will have access to this properties, as it inherits System.Web.UI.Page. TextBox1.Text doesn't have its scope in Beverage class. If you want to use these values in that class, pass them as input parameters to the method.
Working on a project for school that has 2 forms. I want to add items to the listbox in the Display form when I click the show data button. It's showing the form but the form is blank. I think this is because the form object is being created 2x once when I click the add button and another when I click the show data button. How can I create a new object of the display form that can be used in any method in my main form?
Sorry there is a few things in here that I am still working on that were just ideas. I am a beginner so please keep the help in simple terms if at all possible. Thanks :)
private void addEmployee(Employee newEmployee)
{
//Get data from textboxes and use set methods in employee class
newEmployee.Name = EmployeeNameTextBox.Text;
newEmployee.BirthDate = EmployeeBirthDateTextBox.Text;
newEmployee.Dept = EmployeeDeptTextBox.Text;
newEmployee.HireDate = EmployeeHireDateTextBox.Text;
newEmployee.Salary = EmployeeSalaryTextBox.Text;
}
private void AddButton_Click(object sender, EventArgs e)
{
//New list for employee class objects - employeelist
List<Employee> employeeList = new List<Employee>();
//Create new instance of Employee class - newEmployee
Employee newEmployee = new Employee();
bool errorCheck = false;
CheckForms(ref errorCheck);
if (!errorCheck)
{
//Gather input from text boxes and pass newEmployee object
addEmployee(newEmployee);
//Add object to employeeList
employeeList.Add(newEmployee);
Display myDisplay = new Display();
myDisplay.OutputListBox.Items.Add(" Bob");
//" " + newEmployee.BirthDate + " " +
//newEmployee.Dept + " " + newEmployee.HireDate + " " + newEmployee.Salary);
You are creating two separate instances of mydisplay.Create a single instance when the Form Loads and refer to that when you call ShowDataButton_Click
namespace WK4
{
public partial class MainForm : Form
{
Display myDisplay;
public MainForm()
{
InitializeComponent();
}
//Method to clear form input boxes
private void ClearForm()
{
EmployeeNameTextBox.Text = "";
EmployeeBirthDateTextBox.Text = "";
EmployeeDeptTextBox.Text = "";
EmployeeHireDateTextBox.Text = "";
EmployeeSalaryTextBox.Text = "";
FooterLabel.Text = "";
}
//Method to check for blank input on textboxes
private void CheckForms(ref bool error)
{
if (EmployeeNameTextBox.Text == "" || EmployeeBirthDateTextBox.Text == "")
{
MessageBox.Show("Please do not leave any fields blank");
error = true;
}
else if (EmployeeDeptTextBox.Text == "" || EmployeeHireDateTextBox.Text == "")
{
MessageBox.Show("Please do not leave any fields blank");
error = true;
}
else if (EmployeeSalaryTextBox.Text == "")
{
MessageBox.Show("Please do not leave any fields blank");
error = true;
}
else
error = false;
}
private void addEmployee(Employee newEmployee)
{
//Get data from textboxes and use set methods in employee class
newEmployee.Name = EmployeeNameTextBox.Text;
newEmployee.BirthDate = EmployeeBirthDateTextBox.Text;
newEmployee.Dept = EmployeeDeptTextBox.Text;
newEmployee.HireDate = EmployeeHireDateTextBox.Text;
newEmployee.Salary = EmployeeSalaryTextBox.Text;
}
private void AddButton_Click(object sender, EventArgs e)
{
//New list for employee class objects - employeelist
List<Employee> employeeList = new List<Employee>();
//Create new instance of Employee class - newEmployee
Employee newEmployee = new Employee();
bool errorCheck = false;
CheckForms(ref errorCheck);
if (!errorCheck)
{
//Gather input from text boxes and pass newEmployee object
addEmployee(newEmployee);
//Add object to employeeList
employeeList.Add(newEmployee);
Display myDisplay = new Display();
myDisplay.OutputListBox.Items.Add(" Bob");
//" " + newEmployee.BirthDate + " " +
//newEmployee.Dept + " " + newEmployee.HireDate + " " + newEmployee.Salary);
//Clear Form after adding data
ClearForm();
//Print footer employee saved info
FooterLabel.Text = ("Employee " + newEmployee.Name + " saved.");
}
}
//Exit the form/program
private void ExitButton_Click(object sender, EventArgs e)
{
this.Close();
}
//Method to clear the form and reset focus
private void ClearButton_Click(object sender, EventArgs e)
{
ClearForm();
EmployeeNameTextBox.Focus();
}
private void ShowDataButton_Click(object sender, EventArgs e)
{
myDisplay.ShowDialog();
}
private void MainForm_Load(object sender, EventArgs e)
{
myDisplay = new Display();
}
}
}
You are making 2 different instances of display class, in first instance you are adding data and you are displaying it using the second instance thats why you are getting a blank form
create a display class object on your MainForm_Load
private void MainForm_Load(object sender, EventArgs e)
{
Display myDisplay = new Display();
}
and the use this object (myDisplay) to add and display data in your AddButton_Click and ShowDataButton_Click methods respectively.