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);
Related
I've been trying to do this multiple times in my recent project, since I'm currently experimenting on how can I keep my main function in the main class as clean and tidy as possible, while making use of all my functions and values in different classes
Couldn't find solution to my current issue anywhere, so I wrote a simple example of what I mean by that, here I'm trying to make a simple method for generating a random name of a character and then access its name value from a main method
As you can see, if I'm creating an instance of a class in the main method, I can do it very easily, but when I try to use a method from another class, I get an error
So, my question is: could there be any way I could access the values of an instance of a class if it was created by using a method?
Any help or solutions would be much appreciated
class Program
{
public static Random rand = new Random();
public class Character
{
public static string[] nameList = new string[]
{
"John",
"Jack",
"Josh",
};
public string name = nameList[rand.Next(0,3)];
}
public class Functions
{
public void GetCharName()
{
var Char1 = new Character();
Console.WriteLine(Char1.name);
}
}
static void Main(string[] args)
{
//I want this to work, but it doesn't (The name 'Char1' does not exist in the current context)
var TestFunction = new Functions();
TestFunction.GetCharName();
Char1.name = "Arthur";
//This works, but I want to be able to get the name, using function from another class
var Char2 = new Character();
Char2.name = "Andrew";
Console.WriteLine(Char2.name);
}
}
You should create a class. Something like this:
public class Character
{
private readonly string[] nameList = new string[]
{
"John",
"Jack",
"Josh",
};
public string Name { get; private set; }
public Character()
{
Random randomGenerator = new Random();
Name = nameList[randomGenerator.Next(0, nameList.Length - 1)];
}
}
In Main class instantiate a Character type and you can reach the object name with getter.
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 5 years ago.
Improve this question
There is a simple code:
class Test
{
public int number;
public void method()
{
Console.WriteLine("Something");
}
}
class Program
{
public static void Main(string[] args)
{
while(true)
{
Test obj=new Test();
obj.number=3;
}
}
}
This program sets the "number" of obj to 3 in every moment. But I would like to create a totally another, unique object with copy of content of the original object in every loop, automatically. If I make an object with same name, it will be overwritten.
Naturally I don't want to use it in an endless loop, it would be meaningless, but it was the easiest way to explain my problem.
You are creating new objects each iteration, but you only keep reference to the last created object.
public static void Main(string[] args)
{
var myOjects = new List<Test>();
int startIndex = 1;
while(true)
{
Test obj=new Test();
obj.number=startIndex;
myObjects.Add(obj);
startIndex = startIndex + 1;
if (startIndex > 5) break;
}
}
Now you can go through all objects in your list:
foreach (var obj in myObjects) obj.method();
There are a couple of ways that you can do this.
My first thought would be to use a factory method (it just returns an instance of a class). It would look something like this.
public Test TestFactory()
{
return new Test() { number = 3 };
}
Or add a constructor to the Test class that takes an instance of Test:
// inside Test class
public Test(Test that)
{
number = that.number;
}
I made a text file which contain a city name and Many interesting places name of that city. I want that when a city name appear on first combobox the 2nd combobox will show all the places name automatically.
to do that, at the the first step I filled the 1st combobox with city name which I get from a large .xls file. then I made the text file with city and place name of that city. it looks like this-
Flensburg;Nordertor;Naval Academy Mürwik;Flensburg Firth
Kiel;Laboe Naval Memorial;Zoological Museum of Kiel University
Lübeck;Holstentor;St. Mary's Church, Lübeck;Passat (ship)
I create dictionary in a separate method and now I want to to call this method in the main form. Well I am trying it in this way. But it is not actually working.
For data input I wrote the code as follows-
public class POI
{
Dictionary<string, List<string>> poi = new Dictionary<string, List<string>>();
public void poiPlace()
{
foreach (string line in File.ReadLines("POIList.txt"))
{
string[] parts = line.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
poi.Add(parts[0], new List<string>());
poi[parts[0]] = new List<string>(parts.Skip(1));
}
}
Now I want to call this in the main form
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
POI poi1 =new POI();
poi1.List();
}
public void Combo_list_SelectedIndexChanged(object sender, EventArgs e)
{
if (Combo_list1.SelectedItem != null)
{
string txt = Combo_list1.SelectedItem.ToString();
if (poi.ContainsKey(txt))
{
List<string> points = poi[txt];
Combo_list2.Items.Clear();
Combo_list2.Items.AddRange(points.ToArray());
}
}
}
It does not work at all.
You do not call poiPlace anywhere which will set the poi-dictionary appropriately. I guess you have to write something similar like
POI poi1 = new POI();
poi1.poiList()
Instead of
POI poi1 =new POI();
poi1.List();
EDIT: You also have to provide a mechanism to get the data from your dictionary to your form, either by making the dictionary itself public (which is highly not recommended) or by using the following:
Within your POI-class add these two methods:
public bool ContainsKey(string key) { return this.poi.ContainsKey(key) ; }
public List<string> GetValue(string key) { return this.poi[key]; }
Those two methods can now be used within your form:
if (poi1.ContainsKey(txt))
{
List<string> points = poi1.GetValue(txt);
Combo_list2.Items.Clear();
Combo_list2.Items.AddRange(points.ToArray());
}
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.
This question already has answers here:
Why can't I declare C# methods virtual and static?
(16 answers)
Closed 9 years ago.
i have a class with a static field and a static function, e.g. like this
public class A {
protected static string[] _eventField = new[] { "SomeValue" };
public static TOut DoSomethingThatDependsOnEventField(TIn input){
//output depends on input and the static _eventField
}
public class Nested1: A {
protected new static string[] _eventField = new[] { "SomethingDifferent" };
}
public class Nested2 : A {
protected new static string[] _eventField = new[] { "SomethingElse" };
}
}
The output and input types of that static method are of no importance here, the only relevant thing is that the output - despite relying on the input, of course - depends on the content of the static field. The implementation of the method doesn't change at all in the derived classes, and all I want is to change that very static field. But whenever I do a call like
var res1 = A.Nested1.DoSomethingThatDependsOnEventField(...);
or
var res2 = A.Nested2.DoSomethingThatDependsOnEventField(...);
the incorrect static field from the base class A is referenced from within the method.
That is, the intended "hiding" / "redefining" of the static field via protected new static string[] _eventField = ... doesn't work - Why is that so?
You cant have an object associated with Static field/member/function , so static field/member/function cannot come into picture in Inheritance also.