The name does not exist in current context - How to access it? - c#

In my code i have defined string repeatnumber and assigned it into for loop. However, i need it to be accesible when im creating a button click event. Not sure how to do it.
Can anyone give me some tips?
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
string[] assignments = new string[] { "A", "b", "c", "d", "e", "f" };
Random rnd = new Random();
string[] randomingArray = assignments.OrderBy(x => rnd.Next()).ToArray();
string repeatNumber = "";
List<ImageSource> animals = new List<ImageSource>();
for (int i = 1; i < 100; i++)
{
if (i == 9)
{
repeatNumber = randomingArray[i % randomingArray.Length];
animals.Add(new ImageSource() { Source = repeatNumber, Number = i });
}
else if ((i % 9) == 0)
{
animals.Add(new ImageSource() { Source = repeatNumber, Number = i });
}
else
{
animals.Add(new ImageSource() { Source = randomingArray[i % rnd.Next(1,5)], Number = i });
}
ItemsControl1.ItemsSource = animals;
}
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("test");
}
private void btn2_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show((new ImageSource() { Source = repeatNumber })); <-- the name repeatNumber does not exist in current context
}
}
class ImageSource
{
public int Number { get; set; }
public string Source { get; set; }
}

You need to define repeatnumber as a class property
public partial class MainWindow : Window
{
private string repeatNumber;
public MainWindow()
{
...
Otherwise it is limited to the scope (<= you want to look that up) of the MainWindow constructor.

Related

How to link functions in form?

I try to do that the func Form1_Load will display the city list.
I dont know how can i link the 3 functions of the cities (JerusalemData(), LondonData(), OttawaData()) to the function FillCitiesData();
The problem is that it doesnt show the list but only the streets without choosing a city. Another problem - in HouseNum_ValueChanged it doesnt show numbers and you can also type letters and not just numbers.
This is my code - I'll be happy if anyone can help me find the problem.
namespace PlanYourParty
{
public partial class Form1 : Form
{
List <City> cities;
List <string> streets;
public Form1()
{
InitializeComponent();
FillCitiesData();
}
public void FillCitiesData()
{
cities = new List<City>();
cities.Add(new City() { Code = "123", Name = "Jerusalem" });
cities.Add(new City() { Code = "456", Name = "London" });
cities.Add(new City() { Code = "789", Name = "Ottawa" });
JerusalemData();
LondonData();
OttawaData();
}
private void Form1_Load(object sender, EventArgs e)
{
FillCitiesData();
cmbCity.DataSource = cities;
cmbCity.DisplayMember = "Name";
cmbCity.ValueMember = "Code";
cmbCity.SelectedIndexChanged += cmbCity_SelectedIndexChanged;
}
public void JerusalemData()
{
streets = new List<string>();
cmbStreet.Items.Clear();
cmbStreet.Items.Add("Admond Peleg");
cmbStreet.Items.Add("Pardes");
cmbStreet.Items.Add("Nayman");
}
public void LondonData()
{
streets = new List<string>();
cmbStreet.Items.Clear();
cmbStreet.Items.Add("Oxford Street");
cmbStreet.Items.Add("Piccadilly");
cmbStreet.Items.Add("Highfield Ave");
}
public void OttawaData()
{
streets = new List<string>();
cmbStreet.Items.Clear();
cmbStreet.Items.Add("Riverside Drive");
cmbStreet.Items.Add("Ontario Highway");
cmbStreet.Items.Add("Moodie Drive");
}
private void cmbCity_SelectedIndexChanged(object sender, EventArgs e)
{
if (sender != null && sender as City != null)
{
string code;
code = (sender as City).Code;
if (code == "123")
{
JerusalemData();
}
else if (code == "456")
{
LondonData();
}
else OttawaData();
}
}
private void cmbStreet_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void domainUpDownHouseNumber_SelectedItemChanged(object sender, EventArgs e)
{
}
private void Form1_Load_1(object sender, EventArgs e)
{
}
}
First I suggest you separate your data model from the UI. Pull everything you need to define cities and streets in the City class. I have included two methods that return the cities in the example, and the streets for each city.
No need for separate methods that do the same thing, but with different data.
City.cs
public class City
{
public string Code { get; set; }
public string Name { get; set; }
public IList<string> Streets { get => GetStreets(this); }
public static List<City> GetCities()
{
var cities = new List<City>();
cities.Add(new City() { Code = "123", Name = "Jerusalem" });
cities.Add(new City() { Code = "456", Name = "London" });
cities.Add(new City() { Code = "789", Name = "Ottawa" });
return cities;
}
public static List<string> GetStreets(City city)
{
var streets = new List<string>();
if (city == null) return streets;
switch (city.Code)
{
case "123":
streets.Add("Admond Peleg");
streets.Add("Pardes");
streets.Add("Nayman");
break;
case "456":
streets.Add("Oxford Street");
streets.Add("Piccadilly");
streets.Add("Highfield Ave");
break;
case "789":
streets.Add("Riverside Drive");
streets.Add("Ontario Highway");
streets.Add("Moodie Drive");
break;
default:
throw new ArgumentException("Unknown city code.");
}
return streets;
}
}
Then write the UI such that the controls contain the lists of items as specified by the City.GetCities() and City.GetSreets() methods.
The currently selected city and street are returned by CurrentCity and CurrentStreet as well as their corresponding index in the combobox in CurrentCityIndex and CurrentStreetIndex.
Form1.cs
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
cityComboBox.DataSource = City.GetCities();
cityComboBox.DisplayMember = nameof(CurrentCity.Name);
cityComboBox.ValueMember = nameof(CurrentCity.Code);
cityComboBox.SelectedIndexChanged += CityComboBox_SelectedIndexChanged;
cityComboBox.SelectedIndex = -1; // remove default selection of 1st item.
streetComboBox.DataSource = Array.Empty<string>();
streetComboBox.SelectedIndexChanged += StreetComboBox_SelectedIndexChanged;
}
private void CityComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
// TODO: Things when a city is selected.
streetComboBox.DataSource = CurrentCity?.Streets;
streetComboBox.SelectedIndex = -1; // remove default selection of 1st item.
UpdateLabels();
}
private void StreetComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
// TODO: Things when a street is selected.
UpdateLabels();
}
public void UpdateLabels()
{
cityInfo.Text = CurrentCityIndex >= 0 ? $"#{CurrentCity.Code} {CurrentCity.Name}" : "Please select a city.";
streetInfo.Text = CurrentStreetIndex >= 0 ? CurrentStreet : "Please select a street.";
}
public List<City> AllCities { get => cityComboBox.DataSource as List<City>; }
public List<string> AllStreets { get => streetComboBox.DataSource as List<string>; }
public int CurrentCityIndex { get => cityComboBox.SelectedIndex; }
public int CurrentStreetIndex { get => streetComboBox.SelectedIndex; }
public City CurrentCity { get => cityComboBox.SelectedItem as City; }
public string CurrentStreet { get => streetComboBox.SelectedItem as string; }
}
Screen Shots

List is not set value to the control from presenter

I'm trying to make a list of numericUpDown.value and, when I press the button, it sets a random value from the presenter; but, when I press the button nothing happen, I see the value change but I think it just replace the numeric control with a value instead of set value.
The view :
public partial class Form1 : Form, IForm1
{
public List<decimal> _valueList { get; set; }
public Form1()
{
InitializeComponent();
this._valueList = new List<decimal> { numericUpDown1.Value, numericUpDown2.Value, numericUpDown3.Value, numericUpDown4.Value, numericUpDown5.Value, numericUpDown6.Value };
}
public List<decimal> ValueList
{
get => _valueList; set => _valueList = value;
}
public event EventHandler ButtonClick;
private void button1_Click(object sender, EventArgs e)
{
ButtonClick?.Invoke(sender, e);
}
}
Interface:
public interface IForm1
{
List<decimal> ValueList { get; set; }
event EventHandler ButtonClick;
}
Presenter:
public class PresenterForm1
{
private IForm1 _form1;
public PresenterForm1(IForm1 form1)
{
_form1 = form1;
form1.ButtonClick += ButtonClick;
}
private void ButtonClick(object sender, EventArgs e)
{
var random = new Random();
for(int i = 0; i < 6; i++)
{
_form1.ValueList[i] = random.Next(0, 10);
}
}
If I change the type to List<NumericUpDown> it works, but I think this is the wrong way:
foreach (var item in _form1.ValueList)
{
item.Value = random.Next(0, 99);
}

How do I get a list that stores different styles I.E Button , Drag&Drop etc

public partial class QuestionDragAndDropList : Form
{
private List<ListQuestions> Questions = new List<ListQuestions>();
private int i = 0;
public QuestionDragAndDropList()
{
InitializeComponent();
NextQuestion();
}
private void QuestionList()
{
Questions.Add(new ListQuestions("Question 1", new[] {//Answers}, 0));
Questions.Add(new ListQuestions("Question 2", new[] {//^}, 0));
Questions.Add(new ListQuestions("Question 3", new[] {//^}, 0));
Questions.Add(new ListQuestions("Question 4", new[] {//^}, 0));
}
private void NextQuestion()
{
if (i != 2)
{
lblQuestion.Text = Questions[i].GetQuestion();
string[] Ans = Questions[i].GetAns();
BtnA1.Text = Ans[0];
BtnA2.Text = Ans[1];
BtnA3.Text = Ans[2];
BtnA4.Text = Ans[3];
}
else
{
Questions[i].GetQuestion();
BitMap[] Ans = Questions[i].GetAnswers();
}
}
private void AnsCheck(int Answer)
{
if (Answer < Questions.Count)
{
WelcomeYear11.Userfiling.IncreaseS();
}
i++;
if (i != Questions.Count)
{
NextQuestion();
}
else
{
do something.
}
}
private void GrabLabel(object sender, MouseEventArgs e)
{
Label selectedLbl = (Label)sender;
selectedLbl.DoDragDrop(selectedLbl.Text, DragDropEffects.Copy);
}
private void AllowDragDrop(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
private void PBox1DragDrop(object sender, DragEventArgs e)
{
string result = e.Data.GetData(DataFormats.Text).ToString();
if (result == "9")
{
lblA1.Visible = false;
PboxA1.Visible = false;
}
}
private void PBox2DragDrop(object sender, DragEventArgs e)
{
string result = e.Data.GetData(DataFormats.Text).ToString();
if (result == "30")
{
LblA2.Visible = false;
PBoxA2.Visible = false;
}
}
private void PBox3DragDrop(object sender, DragEventArgs e)
{
string result = e.Data.GetData(DataFormats.Text).ToString();
if (result == "5")
{
LblA3.Visible = false;
PBoxA3.Visible = false;
}
}
private void PBox4DragDrop(object sender, DragEventArgs e)
{
string result = e.Data.GetData(DataFormats.Text).ToString();
if (result == "18")
{
LblA3.Visible = false;
PBoxA3.Visible = false;
}
}
}
So using this code, how am I able to not only have it set to generate forms with button questions but also with drag/drop, checkboxes, etc...
The ListClass used in the sample is:
class ListQuestions
{
private string Questions;
private Bitmap[] Answers; private string[] Ans; //First is for Picbox questions. Second is for button questions.
private int PosOfAns;
public ListQuestions(string questions, Bitmap[] answers, int posOfAns)
{
Questions = questions;
Answers = answers;
PosOfAns = posOfAns;
}
public ListQuestions(string questions, string[] ans, int posOfAns)
{
Questions = questions;
Ans = ans;
PosOfAns = posOfAns;
}
public string GetQuestion()
{
return Questions;
}
public string[] GetAns()
{
return Ans;
}
public Bitmap[] GetAnswers()
{
return Answers;
}
public int GetPosOfAns()
{
return PosOfAns;
}
}
Any help is much appreciated :).
I think you're after this
using System.Collections.Generic;
Bitmap[] bm = { new Bitmap(1, 1) };//just had to make one to use in the ListQuestions method overload
List<ListQuestions> thelist = new List<ListQuestions>();
thelist.Add(new ListQuestions("", bm, 1));
Basically, you create your class, then you make a list of your class
List<ListQuestions> thelist = new List<ListQuestions>();
Then you can manipulate your list
thelist.Add(new ListQuestions("", bm, 1));
But since your class properties are all private, none of them are accessible outside of your class. So after you have added items to your List<>, you can't really access any of them. For example, this won't work until your properties are public.
string question = thelist[0].Questions;
Here's a working sample
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
List<myclass> mylist = new List<myclass>();
mylist = Fillmylist(mylist);
this.Controls.Add(mylist[0].chckbx_Recurse);
this.Controls.Add(mylist[0].txtbx_pwd);
this.Controls.Add(mylist[0].txtbx_usrname);
}
private List<myclass> Fillmylist(List<myclass> incominglist)
{
TextBox tb = new TextBox();
tb.Name = "txtbx_usr";
tb.SetBounds(20, 20, 50, 10);
TextBox tbp = new TextBox();
tbp.Name = "txtbx_pwd";
tbp.SetBounds(20,50, 50, 10);
CheckBox cb = new CheckBox();
cb.Name = "chkbx_recurse";
cb.SetBounds(20, 80, 20, 20);
incominglist.Add(new myclass { txtbx_usrname = tb, txtbx_pwd = tbp, chckbx_Recurse = cb });
return incominglist;
}
}
class myclass
{
public TextBox txtbx_usrname { get; set; }
public TextBox txtbx_pwd { get; set; }
public CheckBox chckbx_Recurse { get; set; }
}
}

object of the Order class is not being instantiated

Still learning c# and messing with GUI's, I ran into this problem and I have looked at the code over and over again and do not understand why my Order class will not be instantiated. Evrything looks good to me. Is there a basic concept I am missing here?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
newOrder = new Order ();
for (int i = 0; i < newOrder.menuEntree.Length; i++)
{
this.listBox.Items.Add(newOrder.menuEntree[i]);
}
}
private void listBox_SelectedIndexChanged(object sender, EventArgs e)
{
newOrder.Entree = this.listBox.Text;
}
public class Order
{
public string[] pastryEntree = new string[] { "Baklava", "Croissant", "Blueberry Muffin" };
public decimal[] pastryPrice = new decimal[] { 3.00m, 2.50m, 1.75m };
private string entree;
private decimal entreePrice;
public Order()
{
entree = "";
entreePrice = 0;
}
public string Entree
{
get
{
return entree;
}
set
{
entree = value;
SetEntreePrice();
}
}
public decimal EntreePrice
{
get
{
return entreePrice;
}
}
public void SetEntreePrice()
{
for (int i = 0; i < pastryPrice.Length; i++)
{
if (pastryEntree[i] == entree)
{
entreePrice = pastryPrice[i];
}
}
}
}
}
}
You have not defined newOrder as a member of your Form1 class, and so the variable is undeclared when you try to instantiate it.
public partial class Form1 : Form
{
Order newOrder;
....
}
You might want to replace this:
private void Form1_Load(object sender, EventArgs e)
{
newOrder = new Order ();
for (int i = 0; i < newOrder.menuEntree.Length; i++)
{
this.listBox.Items.Add(newOrder.menuEntree[i]);
}
}
with
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < newOrder.menuEntree.Length; i++)
{
Order newOrder = new Order ();
this.listBox.Items.Add(newOrder.menuEntree[i]);
}
}
It is likely that you want to declare order within the for-loop. Otherwise all the orders would be the same instance.

ObservableCollection binary serialization and transfer over the network

There is a small problem ka. there is a class
public class PLayer
{
public String Name{get;set;}
public TimeSpan Tax { get; set; }
}
The main form
public partial class MainWindow : Window
{
public ObservableCollection<PLayer> PlayersInGame { get; set; }
public ObservableCollection<PLayer> PlayersInGame2 { get; set; }
public ObservableCollection<PLayer> PlayersOnBench { get; set; }
public MainWindow()
{
PlayersInGame = new ObservableCollection<PLayer>();
PlayersInGame2 = new ObservableCollection<PLayer>();
PlayersOnBench = new ObservableCollection<PLayer>();
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 10; i++)
{
String vName = "Игрок" + i.ToString();
PlayersInGame.Add(new PLayer { Name = vName, Tax = new TimeSpan(0) });
}
for (int i = 10; i < 20; i++)
{
String vName = "Игрок" + i.ToString();
PlayersInGame2.Add(new PLayer { Name = vName, Tax = new TimeSpan(0) });
}
Game.Items.Refresh();
}
private void Button2_Click(object sender, RoutedEventArgs e)
{
if (Game.SelectedIndex > -1)
{
var temp = PlayersInGame[Game.SelectedIndex];
//PlayersInGame.RemoveAt(Game.SelectedIndex);
temp.Tax = new TimeSpan(0, 0, 5);
PlayersOnBench.Add(temp);
Game.Items.Refresh();
Bench.Items.Refresh();
}
if (Game2.SelectedIndex > -1)
{
var temp = PlayersInGame2[Game2.SelectedIndex];
//PlayersInGame2.RemoveAt(Game2.SelectedIndex);
temp.Tax = new TimeSpan(0, 0, 5);
PlayersOnBench.Add(temp);
Game2.Items.Refresh();
Bench.Items.Refresh();
}
}
private void timer_Tick(object sender, EventArgs e)
{
foreach (var x in PlayersOnBench)
{
x.Tax -= new TimeSpan(0, 0, 1);
}
List<int> Temp = new List<int>();
for (var i = 0; i < PlayersOnBench.Count; i++)
{
if (PlayersOnBench[i].Tax == TimeSpan.Zero)
{
Temp.Add(i);
}
}
for (int i = Temp.Count - 1; i >= 0; i--)
{
var s = PlayersOnBench[i];
PlayersOnBench.RemoveAt(Temp[i]);
//PlayersInGame.Add(s);
//Game.Items.Refresh();
}
Bench.Items.Refresh();
}
}
On the main form when you click on the button "Button2_Click" line is added to the ListView "Bench" with the addition of a timer. in the treatment of "timer_Tick" The timer is counting all the lines added to the "Bench". Contact ossushestvlyaetsya a Binding. My question is knowing binary serialization, how to transfer the contents of ListView "Bench" to the server to display in a ListView or ListBox. The binary serialization of the project has been in use for sending text fields.
Your question is kind of unclear on what you trying to achieve. In general, if you using binary serialization, it will convert your objects into byte array, you need to de-serialize inorder to get your object back. Below is a sample
BinaryFormatter m_formatter;
Byte[] m_stateData;
List<T> cloned_objList;
public binaryserializer(List<T> PlayersOnBench)
{
if ((!Object.ReferenceEquals(listToClone, null)) && (typeof(T).IsSerializable))
{
m_formatter = new BinaryFormatter();
using (MemoryStream stream = new MemoryStream())
{
try
{
m_formatter.Serialize(stream, PlayersOnBench);
}
catch { }
stream.Seek(0, SeekOrigin.Begin);
m_stateData = stream.ToArray();
}
}
}
public List<T> BenchStates
{
get
{
using (MemoryStream stream = new MemoryStream(m_stateData))
{
try
{
cloned_objList = (List<T>)m_formatter.Deserialize(stream);
}
catch (Exception) { }
}
return cloned_objList;
}
}

Categories

Resources