I've just recently started with C# and I know this has been kind of asked here before but all with complex examples which i could not really grasp yet. So here is my simple example.
I'm trying to add a string to a ListBox from an added class.
It compiles fine but the "TEST" doesn't get added to the ListBox
Form1.cs
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ListBoxAdder myAdder = new ListBoxAdder();
myAdder.Testing();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
ListBoxAdder.cs
namespace WindowsFormsApplication1
{
class ListBoxAdder : Form1
{
public void Testing()
{
listBox1.Items.Add("TEST");
}
}
}
I assume nothing is happening because of creating another instance of "ListBoxAdder"? But I couldn't make it static because I wouldn't make Testing() static or I would have no access to listBox1.
namespace WindowsFormsApplication1
{
class ListBoxAdder
{
ListBox listBox;
public ListBoxAdder (ListBox listBox)
{
this.listBox = listBox;
}
public void Testing()
{
listBox.Items.Add("TEST");
}
}
}
And:
private void button1_Click(object sender, EventArgs e)
{
ListBoxAdder myAdder = new ListBoxAdder(listBox1); // pass ListBox instance here
myAdder.Testing();
}
Related
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.
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;
}
}
}
I've created a new form, in which I have a toolbox. When I press a button in that form, it should relay that information that has been entered by the user(toolboxbox value) to the main form, in which it should say that piece of information in a label.
Since the method to create that username from the toolbox is private, I cannot access it from any other way. Making it public does not seem to make a difference, neither does get,set (from the way I've been trying to atleast).
Picture that may help explaining it:
Code (in which to create user):
namespace WindowsFormsApplication3
{
public partial class Newuserform : Form
{
public Newuserform()
{
InitializeComponent();
}
private void buttonCreateUser_Click(object sender, EventArgs e)
{
string uname = textboxUsername.ToString();
}
public void Unamecreate()
{
}
}
}
Form1 Code (To receive created user):
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void aboutToolStripMenuItem1_Click(object sender, EventArgs e)
{
Aboutform form2 = new Aboutform();
form2.Show();
}
private void newLocalUserToolStripMenuItem_Click(object sender, EventArgs e)
{
Newuserform formnewuser = new Newuserform();
formnewuser.Show();
}
}
}
you have a lot of options.
One way is to create an event and handle it in the main form.
public partial class Newuserform : Form
{
//the public property
public event EventHandler<string> UnameChanged;
public Newuserform()
{
InitializeComponent();
}
private void buttonCreateUser_Click(object sender, EventArgs e)
{
if (UnameChanged != null)
UnameChanged(textboxUsername.ToString()); //fire the event
}
}
Now, to "handle" the event, do the following in your main form:
private void newLocalUserToolStripMenuItem_Click(object sender, EventArgs e)
{
Newuserform formnewuser = new Newuserform();
formnewuser.UnameChanged += Handler;
formnewuser.Show();
}
private void Handler (object sender, string Uname)
{
// do something wit the new Uname.
}
note: recreating the Newuserform will require to cleanup previous attached resources.
I want to Use an instance of a class made in Form 1 in Form 2 (i changed it to a list for simplicity of example code:
Not only that, I want Form 2 to be able to modify it (Clear it at some point).
The advice I got was this, although I was not told how due to "no spoonfeeding allowed"
namespace automationControls.FileTime
{
public class Form_Main : Form
{
public List<string> folderList; //<---- i want to access this.....
private void button_showForm2_Click(object sender, EventArgs e)
{
Form_Log ConfirmBoxForm = new Form_Log(this);
ConfirmBoxForm.Show();
}
}
//form_Main opens form_Log
namespace automationControls.FileTime
{
public partial class Form_Log : Form
{
public Form_Log(Form_Main _f1)
{
InitializeComponent();
}
private void Form1_FormClosing(Object sender, FormClosingEventArgs e)
{
How.Do.I.AccessForm_Main.folderList.Clear();//<---- ............. in this function
}
}
}
Answered:In the constructor of Form_Log, store the reference to _f1 somewhere you can access it from elsewhere in Form_Log
Why don't you use the constructor that you have already added your form?
private Form_Main _mainForm;
public Form_Log(Form_Main _f1)
{
InitializeComponent();
_mainForm = _f1;
}
private void Form1_FormClosing(Object sender, FormClosingEventArgs e)
{
var myList = _mainForm.folderList;
}
Try This,
public class Form_Main : Form
{
public List<string> folderList; //<---- i want to access this.....
private void button_showForm2_Click(object sender, EventArgs e)
{
Form_Log ConfirmBoxForm = new Form_Log(this);
ConfirmBoxForm.Show();
}
}
Form log :
public partial class Form_Log : Form
{
private Form_Main _mainForm;
public Form_Log(Form_Main _f1)
{
InitializeComponent();
_mainForm = _f1;
}
private void Form1_FormClosing(Object sender, FormClosingEventArgs e)
{
_mainForm.folderList.Clear();
}
}
I don't know how advanced is your project but in this situation i would use delegates. Here is how i would do it:
public delegate void ModifyCollectionHandler(string parameter);
public delegate void ClearCollectionHandler();
public partial class Form1 : Form
{
public List<string> folderList;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form = new Form2()
form.ClearItem+=form_ClearItem;
form.AddItem+=form_AddItem;
form.DeleteItem+=form_DeleteItem;
}
void form_DeleteItem(string parameter)
{
if (folderList == null)
return;
folderList.Remove(parameter);
}
void form_AddItem(string parameter)
{
if (folderList == null)
folderList = new List<string>();
folderList.Add(parameter);
}
void form_ClearItem()
{
if (folderList != null)
folderList.Clear();
}
}
public partial class Form2 : Form
{
public event ModifyCollectionHandler AddItem;
public event ModifyCollectionHandler DeleteItem;
public event ClearCollectionHandler ClearItem;
public Form2()
{
InitializeComponent();
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
if (ClearItem != null)
ClearItem();
}
}
I hope I helped you :)
Best regards
in the Form1 put this :
public static List<string> folderList;
you can simply call it from any form ex:Form2 like this :
From1.folderList.Clear();
I am trying to do a simple test with Isolated Storage so I can use it for a Windows Phone 7 application I am making.
The test I am creating sets a creates a key and value with one button, and with the other button sets that value equal to a TextBlock's text.
namespace IsoStore
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
public class AppSettings
{
IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;
private void button1_Click(object sender, RoutedEventArgs e)
{
appSettings.Add("email", "someone#somewhere.com");
}
private void button2_Click(object sender, RoutedEventArgs e)
{
textBlock1.Text = (string)appSettings["email"];
}
}
}
}
This way gives me this error:
Cannot access a non-static member of outer type 'IsoStore.MainPage' via nested type 'IsoStore.MainPage.AppSettings'
So I tried this:
namespace IsoStore
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
public class AppSettings
{
IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;
private void button1_Click(object sender, RoutedEventArgs e)
{
appSettings.Add("email", "someone#somewhere.com");
}
}
private void button2_Click(object sender, RoutedEventArgs e)
{
textBlock1.Text = (string)appSettings["email"];
}
}
}
And instead I get this error:
The name 'appSettings' does not exist in the current context
So what obvious problem am I overlooking here?
Thanks so much for your time.
appSettings is out of scope for button2_Click
Update Since IsolatedStorageSettings.ApplicationSettings is Static anyway there's no need for the reference at all. Just directly access it.
namespace IsoStore
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
IsolatedStorageSettings.ApplicationSettings.Add("email", "someone#somewhere.com");
}
private void button2_Click(object sender, RoutedEventArgs e)
{
textBlock1.Text = (string)IsolatedStorageSettings.ApplicationSettings["email"];
}
}
}
Try this code, as there isn't any need to define AppSettings class.
namespace IsoStore
{
public partial class MainPage : PhoneApplicationPage
{
IsolatedStorageSettings appSettings;
// Constructor
public MainPage()
{
InitializeComponent();
appSettings = IsolatedStorageSettings.ApplicationSettings;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
appSettings.Add("email", "someone#somewhere.com");
}
private void button2_Click(object sender, RoutedEventArgs e)
{
textBlock1.Text = (string)appSettings["email"];
}
}
}