My program compiles and to me it makes sense.
I want to know how to get 'name' to list in my listbox.
I'm trying to use an array of classes so I can add salesmen. A new class will be created every time a person is to be added.
This way the name is a way of calling all the data in that class.
When I execute the program everything looks like its doing what it's suppose to do but it just lists 'form1' in the list box when i press the list names button
This is what i mean:
Where am I going wrong?
SalesmanClass
namespace WindowsFormsApplication1
{
class SalesmanClass
{
private string name;
public string cNum;
public string Email;
public string address;
public string gArea;
public int tSales;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
Form 1
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
Form2 w2;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (w2 == null)
{
w2 = new Form2();
w2.Show();
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Object names;
names = Name;
listBox1.Items.Add(Name);
}
}
}
Form 2
//form2
namespace WindowsFormsApplication1
public partial class Form2 : Form
{
SalesmanClass[] salesman = new SalesmanClass[] { };
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim().Length != 0)
{
for (int i = 0; i > salesman.Length; i++)
{
if (salesman[i] == null)
{
salesman[i].Name = textBox1.Text;
break;
}
}
this.Close();
}
else
{
MessageBox.Show("Please Input a Name");
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
In this method:
private void button2_Click(object sender, EventArgs e)
{
Object names;
names = Name; // <--- Using this.Name, i.e. Form.Name, NOT SalesmanClass.Name
listBox1.Items.Add(Name);
}
You have accidentally used the Name property of the Form itself (which naturally is "form1").
You need to have a SalesmanClass object at this point, and use the Name property of that instead.
You don't currently have a list of salesmen in your Form1, so you will need to add one and use that.
Also, if you have a list or array of SalesmanClass objects, you should create a List<string> from them and use that to initialise the listbox, something like:
SalesmanClass[] salesmen = new SalesmanClass[] {};
// ...
List<string> names = new List<string>();
foreach (var salesman in salesmen)
names.Add(salesman.Name);
listBox1.Items.AddRange(names);
You can do this using Linq too, but I don't want to confuse you by introducing that into the mix!
In your button2_Click, you have :
names = Name;
What does this Name belong to ? I suspect it belongs to Form1, that's why it's been displaying "form1". If that's the case, you just need to get your SalesmanClass object and get the Name from it.
Related
I've created a simple Pokemon WinForm application with just 2 forms. Form1 shows the Pokemon and its associated values.
Upon Clicking the Edit button, Form2 appears (EditCharacter) allowing the user to edit the attributes of the character.
To get the selected Pokemon to appear in Form2 (EditCharacter), I've passed in the currentCharacter from Form1.
Here is the code for Form1.
public partial class Form1 : Form
{
CardCollection cardCollection;
public Character currentCharacter;
public Form1()
{
InitializeComponent();
cardCollection = new CardCollection();
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (var keyValuePair in cardCollection.Cards)
{
cmbPokemon.Items.Add(keyValuePair.Key);
}
}
private void cmbPokemon_SelectedIndexChanged(object sender, EventArgs e)
{
currentCharacter = cardCollection.Cards[cmbPokemon.Text];
updateControls();
}
public void updateControls()
{
lblHP.Text = currentCharacter.HealthPoints.ToString();
lblStrength.Text = currentCharacter.Strength.ToString();
lblSpecialPower.Text = currentCharacter.SpecialPower;
pbPokemon.ImageLocation = #currentCharacter.FileName;
}
private void btnEdit_Click(object sender, EventArgs e)
{
EditCharacter EditChar = new EditCharacter(currentCharacter);
EditChar.ShowDialog();
}
}
And here is the code with Constructor for the EditCharacter form:
public partial class EditCharacter : Form
{
Character currentCharacter;
public EditCharacter( Character c)
{
InitializeComponent();
currentCharacter = new Character();
currentCharacter = c;
lblCharacter.Text = c.Name;
pbCharacter.ImageLocation = c.FileName;
txtPower.Text = c.SpecialPower;
tbHP.Value = c.HealthPoints;
tbStrength.Value = c.Strength;
lblHP.Text = c.HealthPoints.ToString();
lblStrength.Text = c.Strength.ToString();
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
lblHP.Text = tbHP.Value.ToString();
}
private void tbPower_Scroll(object sender, EventArgs e)
{
lblStrength.Text = tbStrength.Value.ToString();
}
private void btnSave_Click(object sender, EventArgs e)
{
currentCharacter.Name = lblCharacter.Text;
currentCharacter.FileName = pbCharacter.ImageLocation;
currentCharacter.SpecialPower = txtPower.Text;
currentCharacter.HealthPoints = tbHP.Value;
currentCharacter.Strength = tbStrength.Value;
currentCharacter.SpecialPower = txtPower.Text;
this.Close();
}
}
My question is (and I've tried), how to preserve the values set in the EditForm to appear in Form1? For example, I edit Rayquaza's HealthPoints to 0, but when I return to Form1, it hasn't changed.
You can use interface to pass the same object directly to EditCharacter from and get it back when it has been updated.
Create new interface , that contains two methods one for reading and the other for writing.
public interface ICharacterManager
{
Character ReadCharacterData();
void WriteCharacterData(Character character);
}
Update your Form1 code by applying ICharacterManager interface, like this :
public partial class Form1 : Form , ICharacterManager
{
CardCollection cardCollection;
public Character currentCharacter;
public Form1()
{
InitializeComponent();
cardCollection = new CardCollection();
}
// The currentCharacter object which will be passed to EditCharacter form.
public Character ReadCharacterData()
{
return currentCharacter;
}
// Get back Character object from EditCharacter form after updating data and pressing Save Button
public WirteCharacterData(Character character)
{
currentCharacter = character;
// Call you updateControls() Method here.
updateControls();
}
private void btnEdit_Click(object sender, EventArgs e)
{
// You can still use this code, because already the type of Form1 is IChatacterManager now.
EditCharacter EditChar = new EditCharacter(this);
EditChar.ShowDialog();
}
}
Update your EditCharacter code by adding ICharacterManager variable like this :
public partial class EditCharacter : Form
{
private ICharacterManager _characterManager;
Character currentCharacter;
public EditCharacter(ICharacterManager characterManager)
{
InitializeComponent();
_characterManager = characterManager;
// Character object which come form Form1.
currentCharacter = _characterManager.ReadCharacterData();
lblCharacter.Text = currentCharacter.Name;
pbCharacter.ImageLocation = currentCharacter.FileName;
txtPower.Text = currentCharacter.SpecialPower;
tbHP.Value = currentCharacter.HealthPoints;
tbStrength.Value = currentCharacter.Strength;
lblHP.Text = currentCharacter.HealthPoints.ToString();
lblStrength.Text = currentCharacter.Strength.ToString();
}
private void btnSave_Click(object sender, EventArgs e)
{
currentCharacter.HealthPoints = tbHP.Value;
currentCharacter.Strength = tbStrength.Value;
currentCharacter.SpecialPower = txtPower.Text;
// Check if _characterManager object is not equal to null.
if (_characterManager != null)
{
// Pass the updated object back to Form1
_characterManager.WriteCharacterData(currentCharacter);
}
this.Close();
}
Hope this was helpful.
Happy coding :) ...
So I'm making this small program for my assignment at university and I'm finding it hard to add to my list in my form. Here is my code:
public partial class WorkOutBeam : Form
{
Check checkLib;
public BindingList<ListBox> list;
public WorkOutBeam()
{
InitializeComponent();
}
public void StartForm(object sender, EventArgs e)
{
list = new BindingList<ListBox>();
listBox1.DataSource = list;
}
private void NewForce_Click(object sender, EventArgs e)
{
NewForceName forceItem = new NewForceName();
forceItem.Show();
}
public void AddToForceList(string name)
{
list.Items.Add(name);
}
}
NewForceName class below:
public partial class NewForceName : Form
{
public WorkOutBeam workOutBeam;
public NewForceName()
{
InitializeComponent();
}
private void OkButton_Click(object sender, EventArgs e)
{
if (NewForceNames.Text != "")
{
ReferToLibs();
workOutBeam.AddToForceList(NewForceNames.Text);
Close();
}
}
private void ReferToLibs()
{
workOutBeam = new WorkOutBeam();
}
private void NewForceName_Load(object sender, EventArgs e)
{
}
}
So I say to my program, "give me a new force." When it does, it initializes a new form of "NewForceName." I type into a text box and click 'Ok', this starts a public method shown below:
The list is a binding list which refers to the listBox as a data source. However the program tells me that the Items part is inaccessible due to its protection but I don't know how to add it as public. I tried looking in the properties of my listBox but to no avail.
Give this a shot:
public partial class WorkOutBeam : Form
{
Check checkLib;
// public BindingList<ListBox> list; // get rid of this for now
public WorkOutBeam()
{
InitializeComponent();
}
/*public void StartForm(object sender, EventArgs e)
{
list = new BindingList<ListBox>();
listBox1.DataSource = list;
}*/
private void NewForce_Click(object sender, EventArgs e)
{
NewForceName forceItem = new NewForceName(this); // pass a reference to this
// instance of WorkoutBeam
forceItem.Show();
}
public void AddToForceList(string name)
{
// we should do some more things here, but let's keep it simple for now
listBox1.Items.Add(name);
}
}
And
public partial class NewForceName : Form
{
public WorkOutBeam workOutBeam;
public NewForceName( WorkoutBeam beam ) // we take a WorkoutBeam instance as CTOR param!
{
InitializeComponent();
workoutBeam = beam;
}
private void OkButton_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(NewForceNames.Text))
{
workOutBeam.AddToForceList(NewForceNames.Text);
Close();
}
}
// DO NOT create new WorkoutBeams every time. Use the original.
/*private void ReferToLibs()
{
workOutBeam = new WorkOutBeam();
}*/
}
Disclaimer: I did not address each and every problem in this code. This is just enough so that it should "work" as intended.
I am trying to fill the class with data and use this data anywhere else on the program, where I will need it.
I created this class:
public class id
{
private string name; // field
public string Name // property
{
get { return name; } // get method
set { name = value; } // set method
}
}
And in form_name I tried to fill the class this way:
private void Button_Click(object sender, RoutedEventArgs e)
{
id IDOBJE = new id();
{
IDOBJE.Name = txtshenimi.Text;
}
this.Close();
}
But I don't get any results. Could someone help me to clarify this?
What I have tried:
And in another form I tried to retrieve data like this:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
id idobje = new id();
txtrez.Text = idobje.Name;
}
You can use some global area to store and access a common variable.
For example, create a class as a central repository.
public static class Globals {
public object myObj;
}
Then assign your created object to this one on first form.
private void Button_Click(object sender, RoutedEventArgs e)
{
id IDOBJE = new id();
{
IDOBJE.Name = txtshenimi.Text;
}
Globals.myObj = IDOBJE;
this.Close();
}
Access that on your second form this way.
private void Button_Click_1(object sender, RoutedEventArgs e)
{
id idobje = (id)Globals.myObj;
txtrez.Text = idobje.Name;
}
Can I create an object in windows form1.cs so that I then can use it and the contents of the object in multiple click events in the windows form1.cs file?
This is the code that demonstrates my intention:
namespace example
{
public partial class Form1 : Form
{
// here i want to call a class an make an objekt thats contains list of "books" from other
// classes
// (classname variable = new classname)
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// here I want to use the object made from the code above.
// variable.function()
}
private void tabPage1_Click(object sender, EventArgs e)
{
// here I want to use the object made from the code above.
// variable.function()
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
// is there anyway to do this or is it another place that makes the object reachable from the
// places I want to call it?
}
}
You should create a new file and create a new class in it. The thing you look for is a field. A field is a variable that belongs to the instance of the class.
Here is an example: (added some extra to your code)
namespace exemple // <--- I know this is spelled wrong, but I'm using the original code, I'm not a spelling checker ;-)
{
public partial class Form1 : Form
{
// the declaration of the field (you can instantiate it here as well)
private BookCase _bookCase;
public Form1()
{
InitializeComponent();
// create an instance of the bookcase and store in into a field.
_bookCase = new BookCase();
}
private void Form1_Load(object sender, EventArgs e)
{
// add some books.
_bookCase.Add(new Book { Title = "Something", Author = "John" };
_bookCase.Add(new Book { Title = "Anything", Author = "Doe" };
// variable.function()**
}
private void tabPage1_Click(object sender, EventArgs e)
{
// call a method of the bookcase
_bookCase.ShowBooks();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
/**/ is there anyway to do this or is it another place thats make the objekt reachable from the
// places i whant to call it?**
}
}
namespace exemple
{
// just a book class
public class Book
{
// with some properties
public string Title {get;set;}
public string Author {get;set;}
}
}
namespace exemple
{
// a bookcase which contains a list of books store in a field
public class BookCase
{
private List<Book> _books = new List<Book>();
public void Add(Book book)
{
// add a book
_books.Add(book);
}
public void ShowBooks()
{
// show all books
foreach(var book in _books)
{
MessageBox.Show($"Title: {book.Title}");
}
}
}
}
I think you want following :
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
textBox1.TextChanged += new EventHandler(textBox_TextChanged);
textBox2.TextChanged += new EventHandler(textBox_TextChanged);
textBox3.TextChanged += new EventHandler(textBox_TextChanged);
}
private void textBox_TextChanged(object sender, EventArgs e)
{
TextBox box = sender as TextBox;
}
}
}
There is another question that is very similar to mine however after reading it i still cannot get it to work.
I have two forms , MainForm and SecondForm and a few other classes, i need an instance of my AVLtree and be able to access it through my other forms.
This is what ive done so far
MainForm
public partial class MainForm : Form
{
AddArtist secondForm = new AddArtist();
public static AVLTree<Artist> treeAVL { get; set; }
public MainForm()
{
InitializeComponent();
}
private void butAdd_Click(object sender, EventArgs e)
{
secondForm.Show();
}
private void MainForm_Load(object sender, EventArgs e)
{
}
}
}
SecondForm
public partial class AddArtist : Form
{
String Name1 = "No Name";
int Members = 0;
public AVLTreetreeAVL = new AVLTree();
public AddArtist()
{
InitializeComponent();
treeAVL = MainForm.treeAVL;
}
private void MainForm_Load(object sender, EventArgs e)
{
}
private void butAdd_Click(object sender, EventArgs e)
{
Name1 = tBName.Text;
Members = (Convert.ToInt32(tBMem.Text));
Artist newArtist = new Artist(Name1,Members);
try
{
treeAVL.InsertItem(newArtist);
}
catch (Exception )
{
MessageBox.Show("No Data Entered", "Error",MessageBoxButtons.OK, MessageBoxIcon.Error);
}
tBName.Text = "";
tBMem.Text = " ";
}
}
}
Any help would be greatly appreciated pointing out where im going wrong or how to solve it.
It now compiles however it gives an error of Object reference not set to an instance of an object. i hope ive gone about coding this is the right way.
What is the access modifier of AVLTree class? Check if it is private or internal, since your code needs it to be public.
Set public on your parametrized type
public class Artist
{
..
}