Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Getting errors when I am trying to save my inputs from textboxes to a list.
I am using visual studio and a windows form application.
What I want to do is to save the inputs from the textboxes to a list and then display the list in other forms.
I have created one class with this code:
public class myClass
{
public List<customer> customerIdInfo= new List<customer>();
public class customer
{
string Id { get; set; }
int phoneNumber { get; set; }
string message { get; set; }
}
}
Then I have this in my form with the textboxes:
private void nextForm_Click(object sender, EventArgs e)
{
Form2 Form1= new Form2();
Form1.Show();
class myClass= new myClass();
customerIdInfo.Add(new customer{
Id = txtCustomerId.Text;
phoneNumber = txtPhonenumber.Text;
message = txtMessage.Text;
});
All the code in the form with the textboxes gets error messages anyone knowws how I can solve this problem?
There were quite some errors in your original code. I have fixed them and commented on them, but Stack Overflow requires a certain level of understanding. Try to pick up a good C# book or read MSDN, so you can learn what the expected syntax is and how you can interpret compiler errors. This isn't exactly the last time you'll get them.
class myClass= new myClass();
You can only use class to declare a class. Here you declare a variable, which is done by naming its type or var:
myClass myClass = new myClass();
// Or
var myClass = new myClass();
Then in your object initializer:
new customer
{
Id = txtCustomerId.Text;
phoneNumber = txtPhonenumber.Text;
message = txtMessage.Text;
}
You use semicolons (;) where commas should be used (,):
new customer
{
Id = txtCustomerId.Text,
phoneNumber = txtPhonenumber.Text,
message = txtMessage.Text,
}
And you try to assign a string to an int:
phoneNumber = txtPhonenumber.Text
Which you can't do, it needs to be parsed:
phoneNumber = int.Parse(txtPhonenumber.Text)
You will also need to add error checking, because users can type in things that can't be parsed to an integer.
Then you try to access a variable named customerIdInfo in order to Add() a new customer, but that variable doesn't exist:
customerIdInfo.Add(...);
You want the field of the myClass instance:
myClass.customerIdInfo.Add(...);
And consider making it a property and naming things properly.
class is a reserved word in C# used for defining a class, it can't be used to declare a variable. So the line class myClass = new myClass() won't compile, you want
myClass obj = new myClass();
Or if you are using C# 3.0 or later you can use the var keyword i.e.
var obj = new myClass();
With C# you shouldn't use Pascal casing for variables i.e. Form1, use camel casing
Form2 form = new Form2();
Also, customer is a nested class (not sure if that's deliberate) so unless your new customer code is arguably breaking the design here. Sounds like what you really want is something like
myClass obj = new myClass();
obj.AddNew("CustomerId", 01234567, "Some message");
FYI - telephone number as int is not a great idea, means you can't store values like +44 01234 56789 or (0)141 232-4334 etc.
Related
This question already has answers here:
Comparing Object properties using reflection
(5 answers)
Closed 3 years ago.
I would like to know if there is a way to create a custom class out of an existing class in this manner:
original class:
public class Person
{
string name;
}
later in code:
var diffPerson = CreateDiffClass<Person>();
diffPerson.name.Value = "name";
diffPerson.name.Changed = false;
this diffPerson is not of Person type, instead it is custom created one, that for every variable in Person have one in itself so that the new variable is a tuple where T is the type of the variable.
I want it to create a system for comparing 2 instances of the same class. one old instance and one new and save the new value and if it changed
I don't really know how to describe it except showing in this example so I hope it is understandable..
I want this to be generic and work on any given class
Thanks
You can declare a generic class like this
public class CustomValue<T>
{
public T Value { get; set; }
public bool Changed { get; set; }
}
and then use it like this
public class Person
{
public CustomValue<string> Name;
}
later in code
var diffPerson = new Person();
diffPerson.Name = new CustomValue<string>();
diffPerson.Name.Value = "name";
diffPerson.Name.Changed = false;
Sending multiple parameters to a method?
So, i am pretty new to C# and Visual Studio and i am "learning by doing" and asking questions. I am writing a small Windows Form application.
I am trying to send another form values.
I have a list of objects from this class:
class Cars
{
public string Name { get; private set; }
public string Color { get; private set; }
public Cars(string name, string color)
{
this.Name = name;
this.Color = color;
}
}
So in my Form1 i have access to these objects by using:
List<Cars> cars = new List<Cars>();
This list of Cars is loaded in other methods.
So now, i am trying to send another form (Edit form) a car.
I would like to do this:
var form2 = new frmEdit(cars[0]);
But then compiler complains about that i need to set my class to public...bad OOP. So then i could do it like this:
var form2 = new frmEdit(cars[0].Name,cars[0].Color);
Fine! But if this was another language like Javascript or PHP i would have sent an object. So i have read about "Anonymus Types" in C# so i thought that could be a good solution.
But the receiveing form doesn´t know about that...so it will complain if i use it like this:
car.Name;
So what should i do here? I am trying to use at least "some" good OOP so i think it is a bad solution making the Cars class public. The Edit form does not need to know about the Cars class.
Thank you for any advice!
[EDIT]
Edit form constructor:
public frmEdit(string name, string color)
{
textName.Text = name;
textColor.Text = color;
}
Change your frmEdit to:
private Cars myCar; // add this var.
public frmEdit(Cars car)
{
this.myCar = car; // now you have your car stored if you need
textName.Text = car.Name;
textColor.Text = car.Color;
}
And Then:
var form2 = new frmEdit(cars[0]);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
How to change the array to enter the desired format in TextBox'e?
Here is the code:
private static readonly string[] Extensions = new string[] { textbox1.text };
In the fields of { } must be changed to textbox!
In the text box I want so I can introduce such formats using a comma! txt,png,ico,dll
Or better using List?
List<string> mylist = new List<string>() { "*.txt" };
Wish I could enter my desired formats is not in the code {"*.txt"}! And TextBox'e .
P.S:
private static string[] Extensions = new string[] { "*.txt" };
//public static string[] Extensions;
public static void extractExtensions(string s)
{
Extensions = s.Split(',');
}
And how do I assign values to string [] { "of the textbox"};
It is not easy to understand what you are really having problems with, but try this:
textbox1.Text = String.Join(",", Extensions);
the reverse would be from textbox --> array:
string [] singleExtensions = textbox1.Text.Split(',');
this would give you all the elements which were separated by a , and dump them into the array.
Or if you prefer Lists:
List<string> singleExtensions = textbox1.Text.Split(',').ToList();
EDIT:
Ok since you don't want to post more code, I make a wild guess:
I imagine you have a Windows Forms application and a TextBox in a Form1.
You also should have an instance of the class that you want to use in there.
Let's assume the class is called MyClass and it has an array for the extensions, and a method extractExtensions to extract the extensions:
public class MyClass
{
string [] singleExtensions;
public void extractExtensions(string s)
{
singleExtensions = s.Split(',');
}
}
public partial class Form1 : Form
{
// instance of class:
MyClass _myClass = new MyClass();
}
at a certain point in your Form you want to call the method of your class and pass the content of the textbox like this:
_myClass.extractExtensions(textbox1.Text);
and voilà.
EDIT 2:
Say for example you want to extract the extensions with a button click, then you call this method inside the btn1_Click event:
public partial class Form1 : Form
{
// instance of class:
MyClass _myClass = new MyClass();
private void btn1_Click(object sender, EventArgs e)
{
_myClass.extractExtensions(textbox1.Text);
}
}
if you made this method static like in your post you would call it like this:
MyClass.extractExtensions(textbox1.Text);
Assuming you have a list of desired extensions
var extensions = new List<string> { ".txt", ".png", ".dll" };
you can join the items to compose a string and show it in a text box
txtExtensions.Text = string.Join(",", extensions);
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 8 years ago.
Improve this question
I've got a bit of a problem trying to add an object to a list. I am working in c#.
Object with List of Objects:
public class Person
{
public string Title { get; set; }
public List<Names> FullNames { get; set; }
}
Names Object
public class Names
{
string First { get; set; }
string Middle { get; set; }
string Last { get; set; }
public Names(string First, string Middle, string Last)
{
this.First = First;
this.Middle = Middle;
this.Last = Last;
}
}
The Problem Area:
In the MainWindow, I create an Observable Collection of type Person. How do you correctly implement adding the FullNames list? I haven't been able to make it work at all.
public partial class MainWindow : Window
{
public ObservableCollection<Person> people { get; set; }
public MainWindow()
{
InitializeComponent();
people.Add(new Person() { Title = "President", FullNames = new Names(First = "George", Middle = "K", Last = "Will")}); //problem area
}
}
Alright, a few things.
You've got a NullReferenceException waiting to happen. people is initialized as null, and you're adding directly to it without giving it an instance.
You have a collection containing Person objects, and you're adding a TodoItem to it. One of those is wrong.
Your real question, you need to use the List initializer on the FullNames property, because it looks like you're trying to set a List<T> = T, which doesn't make any sense.
You are calling a constructor of Names with =, which is bad syntax. You want to leave out the parameter names. As #RohitVats points out, you could also use : to specify, but here you really don't want to. A constructor is really just a method call, so the same syntax rules applies to them as any other function (for the most part).
To address these concerns, your code would look something like this:
public MainWindow()
{
InitializeComponent();
people = new ObservableCollection<Person>();
people.Add(new Person()
{
Title = "President",
FullNames = new List<Names>()
{
new Names("George", "K", "Will")
}
});
}
For the sake of making sure you understand what's going on here, this would be the same as writing:
public MainWindow()
{
InitializeComponent();
people = new ObservableCollection<Person>();
Person toAdd = new Person();
toAdd.Title = "President";
toAdd.FullNames = new List<Names>();
toAdd.FullNames.Add(new Names("George", "K", "Will"));
people.Add(toAdd);
}
This one isn't a bug, but you should really consider adjusting your Names type name to be something singular, even just FullName, because it's hard to read as it stands. I get where you're coming from, since there are in fact multiple names (first, middle, and last), but it's still confusing.
Initialize people list first.
You can only add Person object in your collection.
Names should be initialized to list.
Constructor call with arguments is not correct.
Instead of First = "George", it should be First : "George" or simply omit the arguments name altogether if passing in same order as in definition.
This should work:
people.Add(new Person() { Title = "President",
FullNames = new List<Names>()
{ new Names("George", "K", "Will") } });
I learned about following syntax today
protected String TaskTitle { get; set; }
If I am correct this essentially translates to something like:
String _taskTitle;
protected String TaskTitle {
get { return _taskTitlel }
set { _taskTitle = value; }
}
My question is how can we use it now with objects to set and get certain values? Lets assume object is named MyTest(String title) how would I set TaskTitle equal to a passed in argument title? and afterwards instead of having methods like .getTitle(..) .setTitle(..) how would I take advantage of this {get; set;} syntax?
I understand that this might be getting long, but I believe this "sub question" belongs here, can I use this for arrays? Lets assume I have other object named MyTestTwo(String title, String description, int number); That inherits from first one, and I'd like to have an array MyTestTwo[] { get; set; } as part of MyTest() object, how could I populate it?
I know this might be a lot to ask, but I want to understand this {get; set;} syntax as I am new to it and new to c# in general, so far documentation is a bit confusing to me.
You should mark your property public to 'see' it in classes that do not derive your current class.
You can set it like this then:
yourInstance.TaskTitle = "test 123";
As an answer on your second question:
You can populate the array like you normally would when using variables:
yourInstance.ArrayProperty = new string[1];
yourInstance.ArrayProperty[0] = "test 123";
You can use the { get; set; } syntax like this to modify properties on existing objects:
myTest.TaskTitle = "A brand new title";
And like this to read data from existing objects
string currentTitle = mytest.TaskTitle;
Additionally you can use the following shorthand syntax to initialize a new object:
MyTest myTest = new MyTest{ TaskTitle = "a new task"};
There's some other shorthand syntax you can use for initializing ICollection data structures, which is explained quite well here: http://msdn.microsoft.com/en-us/library/bb384062.aspx
in C# you use the properties by either getting the value via a string a = class.TaskTitle; or setting via class.TaskTitle = "foo";
As far as array objects, try this:
Foo foo = new Foo();
foo.bar = new Bar[5];
foo.bar[0] = new Bar();
foo.bar[1] = new Bar();
...
After which you can access the properties of the Bar via the same syntax as any other object:
foo.bar.SomeMethod();
Or, sans nested classes:
Foo[] foo = new Foo[2];
foo[0] = new Foo();
foo[1] = new Foo();
i am assuming this is your constructor
MyTest(String title)
{
TaskTitle=title;
}
Modifier returntype PropertyName
{
get;
set;
}
get and set are methods ....in c# we use them becouse they are compact and simple.
or you can use methods get and set by creating in your class separately...like
public returntype get()
{
return yourPrivateMember;//
}
public returntype set(type value)
{
yourPrivateMember=value;//in certain cases you dont want the user the mess your private variable and you can control how the user interacts with your private variables
}