How do I reference a class object in a different function? - c#

I am new to c#, I am creating a quiz program (I am at the very beginning) and I have generated a class with a question, 4 answers and a correct answer. I have created one question in Public form1, How do I make the correct answer show up in a messagebox when button1 is clicked?
namespace Prog02
{
public class Question
{
public string Que { get; }
public string Ans1 { get; }
public string Ans2 { get; }
public string Ans3 { get; }
public string Ans4 { get; }
public string CorrectAns { get; set; }
public Question(string que, String ans1, String ans2, String ans3, String ans4, String correctans)
{
Que = que;
Ans1 = ans1;
Ans2 = ans2;
Ans3 = ans3;
Ans4 = ans4;
CorrectAns = correctans;
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//define question1
Question Question1 = new Question("What number is lowest", "1", "2", "3", "4", "1");
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(Question1.CorrectAns);
}
}
}

You have created an instance of the Question class directly in the constructor of the form (within Form1, below the method call InitializeComponent). The specified variable Question1 is only valid in this local scope of this specific function. So if you want to access it from outside of this function, you have to make it available in the class. This can be achieved by declaring a field within the class like private Question question; directly before the constructor call and changing your assignment to question = new Question(...);
public partial class Form1 : Form
{
private Question question;
public Form1()
{
InitializeComponent();
this.question = new Question("What number is lowest", "1", "2", "3", "4", "1");
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(this.question.CorrectAns);
}
}

You should move out the question instance and make it a field.
Also there were some other wrong parts with the code.
Here is the full code with the fixes.
Added comments for describing the changes.
using System;
using System.Collections.Generic;
namespace Prog02
{
public class Question
{
// Added "private set" to the properties below
public string Que { get; private set;}
public string Ans1 { get; private set;}
public string Ans2 { get; private set;}
public string Ans3 { get; private set;}
public string Ans4 { get; private set;}
public string CorrectAns { get; private set; }
public Question(string que, String ans1, String ans2, String ans3, String ans4, String correctans)
{
Que = que;
Ans1 = ans1;
Ans2 = ans2;
Ans3 = ans3;
Ans4 = ans4;
CorrectAns = correctans;
}
}
public partial class Form1 : Form
{
// Created a private field for holding the question instance.
private Question question1;
public Form1()
{
InitializeComponent();
//define question1
question1 = new Question("What number is lowest", "1", "2", "3", "4", "1");
}
private void button1_Click(object sender, EventArgs e)
{
// Use the instance here ("question1" instead of "Question1")
MessageBox.Show(question1.CorrectAns);
}
}
}

Related

Filter List of Objects

I want to store Objects of the class Rezept in the list List RezepteListe. After that I want to filter that RezepteListe regarding their NameID. But obviously I dont get the Filter() Method run on my RezepteListe.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public List<Rezept> RezepteListe = new List<Rezept>();
private void button1_Click(object sender, EventArgs e)
{
Rezept Kartoffelsalat = new Rezept("Kartoffelsalat");
textBox1.Text = Kartoffelsalat.NameID;
RezepteListe.Add(Kartoffelsalat);
textBox1.Text = RezepteListe.Where(x => x.NameID == "Kartoffelsalat");
List<String> liste2 = new List<string>();
liste2.Add("Hallo");
textBox1.Text= liste2.Find(x => x == "Hallo");
}
}
public class Rezept
{
public List<string> Zutat { get; set; }
public string NameID { get; set; }
public Rezept(string NameID)
{
this.NameID = NameID;
}
}

Can't pass the value to the other form

the value of filteredSymptoms is rashes, cough, diarrhea and when passing these values of filteredSymptoms to another form, the value of filteredSymptoms is not being passed to the form2 (this is the second form). What part of my code is wrong or missing something?
Form1
FinalScreen showForm = new FinalScreen();
showForm.checkedSymptoms = filteredSymp;
Form2
public string checkedSymptoms { get; set; }
label1.Text = checkedSymptoms;
Create an overload constructor on FinalScreen
public FinalScreen()
{
InitializeComponent();
}
public FinalScreen(string checkedSymptoms)
:base()
{
InitializeComponent();
CheckedSymptoms = checkedSymptoms;
}
public string CheckedSymptoms { get; set; }
private void FinalScreen_Load(object sender, EventArgs e)
{
label1.Text = CheckedSymptoms;
}
Then
FinalScreen showForm = new FinalScreen(filteredSymp);

C# Cant bind List to DataGridView -

I must be going mad - I can't seem to do the simple task of making my list display in my DataGridView by using the dgv.datasource = list code. No errors appear but my list remains blank - can anyone help i'm sure its something obvious but I just can't spot it.
namespace WindowsFormsApp4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
List<DGVNames> NamesList = new List<DGVNames>();
NamesList.Add(new DGVNames("Adam", 18, "Wigan"));
NamesList.Add(new DGVNames("Bob", 21, "Bolton"));
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = NamesList;
}
}
}
and this is my class..
namespace WindowsFormsApp4
{
class DGVNames
{
public String strName;
public int intAge;
public String strTown;
public DGVNames(String _strName, int _intAge, String _strTown)
{
strName = _strName;
intAge = _intAge;
strTown = _strTown;
}
}
}
I think the issue is what New Contributor said - DataGridView requires properties to bind to, not just fields. You need Getters and Setters to get the binding to work.
Try this changing your class to this and it should work:
public String strName { get; set; }
public int intAge { get; set; }
public String strTown { get; set; }
public DGVNames(String _strName, int _intAge, String _strTown)
{
strName = _strName;
intAge = _intAge;
strTown = _strTown;
}

How do I get data from another file to my form1 shapelist?

I have a form1.cs that contains
List<Shape> shapeList = new List<Shape>();
listBoxDB listBoxHist = new listBoxDB();
public Form1()
{
listBoxHist.Show();
InitializeComponent();
this.DoubleBuffered = true;
}
I have another file called listBoxDB.cs that has a button that will take data from a listbox in listBox and store in it a string Lname that form1 uses. However I can't access my shapelist to add to the list correct due to protection level. How can I fix this?
private void button2_Click(object sender, EventArgs e) //load 1 line
{
//string s = Form1.datInfo;
Form1.Lname = listBox1.GetItemText(listBox1.SelectedItem);
//Console.WriteLine(text);
Shape Line = new Line();
Line.loadLine();
Form1.shapeList.Add(Line); <-- I get a protection error here.
Invalidate();
}
I am able to access Lname using this getter/setter
public static string Lname { get; set; }
How can I do the same to access my shapeList in form1 within another form?
Your problem seems to be the difference between static and instance variables.
If you make Lname static, like this public static string Lname { get; set; }, then you can access it via Form1.Lname, but it effectively becomes a globally defined variable. If you create two instances of Form1 they would both share the same Lname and that isn't usually what you should do.
Instead what you should do is declare it as public string Lname { get; set; } and then you could make a SetForm1 method on your listBoxDB form to pass the reference to the instance of Form1 in so that you can access Form1's public variables from listBoxDB.
Your code could then look something like this:
public class Form1 : Form
{
public string Lname { get; set; }
public List<Shape> shapeList = new List<Shape>();
private listBoxDB listBoxHist = new listBoxDB();
public Form1()
{
listBoxHist.SetForm1(this);
listBoxHist.Show();
InitializeComponent();
this.DoubleBuffered = true;
}
}
public class listBoxDB : Form
{
private Form1 _form1 = null;
public void SetForm1(Form1 form1)
{
_form1 = form1;
}
private void button2_Click(object sender, EventArgs e) //load 1 line
{
//string s = Form1.datInfo;
_form1.Lname = listBox1.GetItemText(listBox1.SelectedItem);
//Console.WriteLine(text);
Shape Line = new Line();
Line.loadLine();
_form1.shapeList.Add(Line);
Invalidate();
}
}

Inconsistent Accessibility C#

I'm working on a custom UI for Tracking stocks, although one UI I've made has caused an issue that I can't locate. I keep getting the error: "Inconsistent accessibility: parameter type 'SCM_Addin.Funds.TrackFund[]' is less accessible than method 'SCM_Addin.Forms.frm_FundTracker.frm_FundTracker(SM_Addin.Funds.TrackFund[])'
I've checked the protection in my classes, but I can't find any private variables that would hinder the accessibility in my code. Here is the code:
frm_FundTracker:
namespace SCM_Addin.Forms
{
public partial class frm_FundTracker : Form
{
public frm_FundTracker()
{
InitializeComponent();
}
public frm_FundTracker(String[] fundsToAdd, Double[] ePrices, Double[] cPrices)
{
InitializeComponent();
int index = 0;
foreach (String fund in fundsToAdd)
{
ListViewItem newFundItem = new ListViewItem(fund);
newFundItem.SubItems.Add(ePrices[index].ToString());
newFundItem.SubItems.Add(cPrices[index].ToString());
this.list_Tracker.Items.Add(newFundItem);
index++;
}//END LOADING COLUMNS
}//END FRM_FUNDTRACKER WITH ARRAYS
public frm_FundTracker(TrackFund[] funds)
{
InitializeComponent();
foreach (TrackFund fund in funds)
{
ListViewItem newFundItem = new ListViewItem(fund.symbol);
newFundItem.SubItems.Add(fund.entryPrice.ToString());
newFundItem.SubItems.Add(fund.currentPrice.ToString());
this.list_Tracker.Items.Add(newFundItem);
}
}//END FRM_FUNDTRACKER WITH FUNDS
private void btn_Done_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Close Form?", "Close Form?", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
{
this.Dispose();
}
}
}
}
Fund Class:
namespace SCM_Addin
{
class Fund
{
public String symbol { get; set; } //Symbol of the fund to be used
private int fundRow { get; set; } //Fund's spot in the Stats Sheet.
private String url1, url2, url3;
private HtmlAgilityPack.HtmlDocument doc;
private DataPuller puller;
private Dictionary<String, String> fundStats;
private SqlConnection conn;
public Fund(String sym)
{
this.symbol = sym;
this.doc = new HtmlAgilityPack.HtmlDocument();
this.puller = new DataPuller();
this.url1 = "http://finance.yahoo.com/q?s=" + this.symbol;
this.url2 = "http://finance.yahoo.com/q/ks?s=" + this.symbol;
this.url3 = "http://www.profitspi.com/stock-quote/" + this.symbol + ".aspx";
this.fundStats = new Dictionary<string, string>();
this.conn = null;
}
TrackFund class (Extends Fund)
namespace SCM_Addin.Funds
{
class TrackFund : Fund
{
public double entryPrice { get; set; }
public double currentPrice { get; set; }
public TrackFund(String sym, double entryP, double curP) : base(sym)
{
this.entryPrice = entryP;
this.currentPrice = curP;
}
}
}
This is my first time really extending a class in C#, so if I'm extending wrong, I guess that could be it.
Default accessibility for a class will be internal, so:
class Fund
//and
class TrackFund : Fund
...should be
public class Fund
//and
public class TrackFund : Fund
Make the TrackFund class public.
public class TrackFund : Fund
{
....
}

Categories