Why we can add String to combobox c#? [closed] - c#

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 7 years ago.
Improve this question
combobox.Items.Add(object item), so why we can use combobox.Items.Add("Some text"), although "Some text" is string, not object?

A string is a reference type, so it is an object. What combobox does is then call the .ToString() method of the object it receives to transform it in a string (to show it). The ToString() of a string simply returns the string.
Why is the Add() done in that way?
Let's look at an example using WinForms:
// A simple Person class, Name + Surname
public class Person
{
public string Name { get; set; }
public string Surname { get; set; }
public override string ToString()
{
return Name + " " + Surname;
}
}
// cb is your ComboBox
// Three persons in the ComboBox
cb.Items.Add(new Person { Name = "Bill", Surname = "Gates" });
cb.Items.Add(new Person { Name = "Larry", Surname = "Ellison" });
cb.Items.Add(new Person { Name = "Peter", Surname = "Norton" });
// and then somewhere the user selects an item in the combobox
// and then we can
Person selectedPerson = (Person)cb.SelectedItem;
string selectedPersonDescription = cb.SelectedText;
You can retrieve not only the description of the selected item, but the "whole" selected item! You see the advantage? (as I said before, the "description" for the items is automatically calculated by the ComboBox class by using the ToString() method)
So clearly the ComboBox is saving the "whole" objects you Add(...) to it, and calculating the descriptions (with ToString()) to show to the user.

It's thanks to polymorphism. Because string derives from object, you can pass it to the method, as well as any other instance of type deriving from object (which is almost everything).

Related

How to get specific names from a binding List? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I have a binding list with streets. It includes a name and an ID. I want to show the names of the streets in a combobox. The thing is I only want street names to show with a specific start letter. Like my combobox should only show street names that start with the letter S.
If it helps, I use Windows forms and I try to use the Mvvm model.
Does anyone have the link for a solution? I got it to work that my combobox shows all the street names but not the specific names I want.
This simple program makes a list of streets and adds two streets to this list.
Then all streets starting with "S" are put into "streetsStartingWithS". This is done with LINQ. Then these streets are printed.
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
List<Street> streets = new List<Street>();
streets.Add(new Street("Superstreet", 1));
streets.Add(new Street("Anotherstreet", 2));
IEnumerable<Street> streetsStartingWithS = streets.Where(s => s.Name.StartsWith("S"));
foreach (Street street in streetsStartingWithS){
Console.WriteLine(street.Name);
}
}
}
public class Street{
public string Name {get;set;}
public int Id {get;set;}
public Street (string name, int id){
Name = name;
Id = id;
}
}
Output:
Superstreet

How to Split string into an array using C#? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
When Domain Model property Name gets data from the database it's a string "David,James", but I have created another View Model to convert that string into an array ["David","James"]. I have used my ViewModel in the read method now, now the ViewModel should read the Name property as ["David","James"]. I am not sure how to make it happen.
I would appreciate if anybody has any suggestion on how to make it happen.
Domain Model:
public class FullName
{
public Int32 Id { get; set; }
public String Name { get; set; }
public String Address {get; set;}
}
View Model:
public class NameViewModel
{
public Int32 Id { get; set; }
public List<string> Name { get; set; }
public String Address { get; set;}
}
Read Method:
public ActionResult Name_Read([DataSourceRequest]DataSourceRequest request)
{
try
{
DataSourceResult result = Identity.ToDataSourceResult(request, NameViewModel => new
{
Id = NameViewModel.Id,
Name = NameViewModel.Name ,
Address = NameViewModel.Address,
});
return Json(result);
}
I think you're looking for something like this:
DataSourceResult result = Identity.ToDataSourceResult(request, dataModel => new NameViewModel
{
Id = dataModel.Id,
Name = dataModel.Name.Split(","),
Address = dataModel.Address,
});
// typical delimiter characters
char[] delimiterChars = { ' ' };
// verify the name exists
if (!String.IsNullOrEmpty(name))
{
// Get the list of strings
string[] strings = name.Split(delimiterChars);
if (strings != null)
{
if (strings.Length == 1)
{
firstName = strings[0];
}
else if (strings.Length == 2)
{
firstName = strings[0];
lastName = strings[1];
}
else if (strings.Length == 3)
{
firstName = strings[0];
middleName = strings[1];
lastName = strings[2];
}
}
}
I am not at Visual Studio, but I think that is right.
When Domain Model property Name gets data from the database it's a string "David,James"
That is a terrible mistake in database Design. The ideal solution would be to fix the Backend Database to actually have two fields for those distinct values.
Failing that, the next step would be to try and split on the DB side. Many modern DBMS support Views, wich can have columns computed from actuall rows. That way you could avoid issues, like different code splitting the same input differently. And you could even henceforth treat it like it was always two Columns.
If you really want or need to it in code and given this exact input format, String.Split() can deal with this. Of coruse you can get fancier, and use stuff like Regular Expressions instead. But for this example, Split seems perfectly suiteable for the case.

Modeling JSON message [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I'm using a web service with this request format:
{
"type":"LogonReq",
"id":"b43b301c-5216-4254-b3fc-cc863d4d6652",
"date":"Wed, 16 Aug 2017 17:35:34 UTC",
"parameters":[
{
"userName":"user",
"password":"password"
}
]
}
Even though every message in the API requires only 1 set of parameters, the API still requires "parameters" to be an array.
Is it better practice to have the caller create the list or to create the list in the MessageBase constructor, or something altogether different ?
Which way would satisfy an OOP purist code reviewer?
public class MessageBase<T>
{
public MessageBase() { this.parameters = new List<T>(); }
public string type { get; set; }
public string id { get; set; }
public string date { get; set; }
public List<T> parameters { get; set; }
}
public class LogonMessage{
public string userName { get; set; }
public string password { get; set; }
}
var logon = new MessageBase<LogonMessage>()
{
date = DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss UTC"),
id = Guid.NewGuid().ToString(),
type = "LogonReq",
};
logon.parameters.Add(new LogonMessage() { userName = "user", password = "password" });
or
public class MessageBase<T>
{
public string type { get; set; }
public string id { get; set; }
public string date { get; set; }
public List<T> parameters { get; set; }
}
public class LogonMessage{
public string userName { get; set; }
public string password { get; set; }
}
var logon = new MessageBase<LogonMessage>()
{
date = DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss UTC"),
id = Guid.NewGuid().ToString(),
type = "LogonReq",
parameters = new List<LogonMessage>() { new LogonMessage() { userName = "user", password = "password" } }
};
You will probably find many interesting opinions and answers to this. I can only give you mine based on my experience.
I myself would probably initialize the list within the constructor
However, since you are trying to get a good idea around the phylosophy of coding, here are some things to consider :
1) Does the MessageBase object make sense or is it useful with a NULL list? Is there any scenario where I want this list as null?
2) Actually, I would expect an OOP purist to say that you should not expose the "parameters" as a List. By exposing the object as a property, someone can do this:
login.parameters.Add()
Or this
logon.parameters = anotherListOfMine
In a way it does break encapsulation. You could make the list property read only (ie, with a protected/private setter) but "clients" of this class will still be able to access all properties and methods of the List and modify/handle them.
Now, you have to expose this in some way as you will be serializing/deserializing into JSON, so that poses a problem! Maybe you can have a private/protected List field and expose the values through a readonly property that exposes an IEnumerable and behind the scenes, you are doing:
get { return myPrivateList.ToArray(); }
3) But again, do you really win that much? Your next question should be "Who is my client?" If you are exposing this class to other developers, or is part of a framework, you might want to apply something like my point number 2, and limit the exposure. If this is internal to your application and your team maybe you should be pragmatic and simply expose the List as you are doing right now.
4) Alternatively, while still making it open, you could instead have a property of type IEnumerable so you can pass in any type.
5) Another option is to expose your list because you need to serialize it, but make it readonly. Have instead different methods, or non-serializable properties, of username and password. If these parameters are always the same that is. I am thinking this might not be your case.
I think I could go on and on this. I will stop here before you hit the downvote button :).

How to return a new arrays via method while inputs are "string name" and "int size" [closed]

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
I will try to make clear my problem :
Let's assume that i have a coach company and my buses has a few different service lines.
My aim is to separately store data of services for per service in in a string array "string[]".
As my thought, the name of array must be consist of (Date time + service number)
The dream was to put all passenger and the number of sold coaches information into a string[]
For instance :
//** "2303201601" >>> day + month + year + service number
string[] "2303201601" = new string[44]; // of course doesn't work :P
so i tried my chance with the following code :
public static Array new_list (string name_list, int size)
{
string [] name_list = new string[size];
return name_list;
}
Please help me :D ?
Ok I think this is what you want, though your question is not clear. Build an object to hold all your data properly. Strings make bad objects
public class Bus
{
public Bus()
{
ServiceNumbers = new List<string>();
}
public DateTime Date {get; set;}
public int ServiceNumber {get; set;}
public List<string> ServiceNumbers {get; set;}
}
Now just use it
List<Bus> buses = new List<Bus>();
Bus busx = new Bus()
{
Date = new DateTime(year, month, day),
ServiceNumber = "X"
}
busx.ServiceNumbers.Add("servicenumberx");
buses.add(busx);
I'm presuming here that the string is just a storage mechanism and there is no special reason for it. i.e. you have another piece of technology that holds string only, etc.
You can use Dictionary. It will be like this:
var someVar=new Dictionary<string, string[]>();
someVar.Add("date+servnum", yourarray);
var yourArray = someVar["date+servnum"];
You can do this
public class service{
private string name;
private string[] info;
public service(string name,int size){ this.name=name; info=new string[size];
public getInfo(){ return info;}
}
And then, if you need an array of services you can do it:
List<services> allServices=new List<services>();
I do not know if I understand the problem correctly

get model from List of a model [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Is there a way to get the specific items from the list of a model without using a foreach of the list? like if you return a List<model> holding a model with a few differnt items to specifically call those item.
If you want a list of a specific item that's within your list then you can use LINQ to return those items, for example:
var customerNames = customersList.Select(customer => customer.Name);
This would give you a string collection with all of your customer names equal to the amount that was in your original list.
Or if you would like to retrieve a number of different items from your model list then you may want to look into creating a class specifically for stripping out those items, for example:
public class CustomerContactDetails
{
public string Address { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
}
...
var contactDetails = customersList.Select(customer => new CustomerContactDetails { Address = customer.Address, Email = customer.Email, Telephone = customer.Telephone });
You can use C# LambdaExpression, like this:
var yourModel = modelList.Where(x => x.Id = 12).Select(x).First();

Categories

Resources