i am returning a list from a database like this;
ClsCampus campus = new ClsCampus();
List<ClsCampus> camp = campus.GetCampusAll();
Utility.BindComboBox(ComboBoxCampus, camp, "CampusName", "CampusId");
I have a class name Utillity, in which i have created a static method called BindComboBox.
public static void BindComboBox(DropDownList listName, List<Object> list,
string textField, string valueField)
{
listName.DataTextField = textField;
listName.DataValueField = valueField;
listName.DataSource = list;
listName.DataBind();
}
However, it gives me a compilation error.
So, How do i write a general purpose method where i can bind a generic list of records to a combobox
Error 1
The best overloaded method match for 'KenMISSchool.Repository.Utility.BindComboBox(System.Web.UI.WebControls.DropDownList, System.Collections.Generic.List<object>, string, string)' has some invalid arguments D:\Projects\KenMISSchool\Web\forms\student\registration.aspx.cs 20 9 Web
You are passing List<ClsCampus> but method expects List<Object> so I would change it to generic way:
public static void BindComboBox<T>(DropDownList listName, List<T> list, string textField, string valueField)
{
listName.DataTextField = textField;
listName.DataValueField = valueField;
listName.DataSource = list;
listName.DataBind();
}
and call it like this:
Utility.BindComboBox<ClsCampus>(ComboBoxCampus, camp, "CampusName", "CampusId");
We had a similar idea, but solved it in another way. I'm not sure if it will work for you, but here's a suggestion:
We implemented an Interface called IDropdownable (not the best name, I know), that forced two properties:
public string dropdown_value;
public string dropdown_text;
And we then implemented this interface over all classes that needed to be easily bound to dropdownlists:
public class Foo : IDropdownable
{
//Let's say these fields are already in the class:
private int _id;
private string _name;
private DateTime _date;
//The interface was then implemented:
public string dropdown_value
{
get
{
return this._id.ToString();
}
}
public string dropdown_text
{
get
{
return String.Format("{0} ({1})", this._name, this._date.Year);
//Or simpler: return this._name;
}
}
}
The only thing left was to create a generic function that takes in a IDropdownable parameter and outputs the dropdownlist the way you like it (HTML string, SelectList, List<SelectListItem>, ... many options there).
public List<SelectListItem> GenerateDDL(
List<IDropdownable> items,
string selected_value)
{ ... }
If you want I can give you an approximation of the function.
Comment
We did this in MVC2 ASP.Net 4. To be honest, I'm not sure what type should be returned in classic ASP.NET, but I assume some type of List/Array will work.
Related
I have recently start to practice c# and come across this problem:
I just want to save 'dataTaken' in 'public string date', so i can acces this variable directly.
class Bild
{
public int id;
public String source;
public string dataTaken;
public string data;
private string getAufnahmeDatum () {
string dataTaken = [.....]this.source;
return dataTaken;
}
**//-> data = this.getAufnahmeDatum(); // dose not work.**
}
I get some erros, trying this.
date : 'date' dose not exist in the current context
getAufnahmeDatum:
Method must have an return type
Bild.getAufnahmeDatum must declare a
body because its not marked abstarct,extern or partial
Type Bild already defines a memeber called getAufnahmeDatum with the same
parameter typs
I find it curios that when I dont define public string dataTaken; i get an error too ( dose not exist in th current context).
I thought string dateTaken = [...] should be enough.
PS: Is there a trick to copy that damn erros out of VisualStudio ?
You get exactly these error messages if you write this code inside the class but not within a method!
// fails with the described error
data = this.getAufnahmeDatum();
// works without error
private void Test()
{
data = this.getAufnahmeDatum();
}
You could for example call the code in the constructor of the class
public Bild()
{
data = this.getAufnahmeDatum();
}
This can be done in other way too by using set.
class Bild
{
public int id;
public String source;
public string dataTaken;
public string data
{
set { value = this.getAufnahmeDatum(); }
}
private string getAufnahmeDatum()
{
string dataTaken = this.source;
return dataTaken;
}
}
You can have get property also, if you want data to be read/write.
I've playing around with a class that acts as a public interface for a private List<T> attribute. I noticed that the List<> class has an attribute Length that tells you how many elements it contains.
This is an attribute you cannot alter, and on the intellisense appears with an image of a spanner next to it. It is not a method as it does not require () after coding the name.
I've seen attributes of this type before, but never used them in my own classes. Does anybody have any idea how I can replicate Length in my custom class?
Thanks,
Mark
It's a property with no setter. If you're wrapping a List<T> you can just use it's Count as your own:
public int Count {get {return _myPrivateList.Count; } }
If you're using C# 6, you can use this:
public int Count => _myPrivateList.Count;
If you currently have a class that contains a List, then you can take advantage of the Count property already present on it by exposing a property that simply uses that :
public class YourExampleList<T>
{
// Example of your inner list
private List<T> _list { get; set; }
// Use the Count property to expose a public "Length" equivalent
public int Length { get { return _list.Count; } }
}
This is actually not a method, but a property.
So you could have define in your class
private List<string> myList = new List<string>();
public int NumberOfElements
{
get { return this.myList.Count; }
}
A normal property would be defined such as
public bool ColumnNames { get; set; }
List<T> myList = new List<T>();
Now you can create your own implementation on your custom class. Something like:
public int Length {get {return myList.Count; }}
I must admit that your question is a bit vague. It sounds like you want know how to create a read only attribute / property. This can be achieved by creating a property wrapper for a private field member of your class as follow:
class MyCustomClass
{
private int _length;
public int Length
{
get { return _length; }
}
}
Say for example you have a class like this:
public class MyClass
{
private string _str;
public MyClass()
{
_str = "Sample String";
}
public int Length
{
get
{
return _str.Length;
}
}
}
This is what's happening:
We're declaring a private field at the start of the class named _str.
In the constructor we're then assigning it a value of "Sample String".
After the constructor we're then declaring the public attribute Length of type int, and only giving it a get accessor. Like your example, this only allows the value to be read, and not set.
Within the get we then tell it to return the value of _str's length.
Using code similar to this you can implement a Length attribute for any custom class.
I need to get a private string from a class, and count the frequency of words in the string.
the counting is the easy part... the bit I am struggling with is getting the string from the second class.
Heres what I am trying to get
public class GetString
{
private string myText = "this is the string that i need to get"
private string text;
public GetString()
{
text = myText
}
any and all help would be very much appreciated. I am also told I cannot edit this class
You have three options in my view:
You can make myText public.
You can return myText from another public member, preferably a property.
You can access the value via reflection (see: How to get the value of private field in C#?).
It seems that your getString class (by the way - bad naming a class with lowercase letter) contains a text property. If this property is public you can use it to get the string. If it is not public, there might be a method that exposes it. Your code is not complete, so it cannot be said for certain.
If there are no public properties or methods that expose the string, then the only way to get is through reflection
This seems rather fundemental, you have nothing in your getString class returning the string. Try something like
public class getString
{
private string myText = "this is the string that i need to get"
public String getString()
{
return myText
}
getString a = new getString();
String hiddenString = a.getString();
You cannot use the constructor for this purpose. Try this:
public class Foo
{
private string myText = "this is the string that i need to get";
public Foo()
{
}
public String GetString()
{
return this.myText;
}
}
Every method should either have the void keyword or the return type, which is in your case a String.
Use Properties (property is a member that provides a flexible mechanism to read, write, or compute the value of a private field.):
public string MyText
{
get { return myText; }
private set { myText = value; }
}
To follow on from #Petrichor, you could also potentially use interfaces:
public interface IHasText
{
string GetPrivateText();
}
public class GetString : IHasText
{
private string myText = "this is the string that i need to get";
string IHasText.GetPrivateText()
{
return myText;
}
}
var val = new GetString();
var asInterface = (IHasText)val;
string text = asInterface.GetPrivateText();
Hello fellow stackoverflow members!
I'm very new to the C# language transfer from Java, Obj-C.
It looks pretty same as Java, but I have trouble issue in very simple thing.
I have created two individual class files, Class-A and Class-Human.
Specification for Class-A
it contains the static main method declared.And I've tried to create the new instance of Class-Human.
public static void main(String args[])
{
Human human = new Human("Yoon Lee", 99);
int expected = human.getNetID; //<-gets the error at this moment.
}
Specification for Class-Human
namespace Class-A
{
public class Human
{
public String name;
public int netId;
public Human(String name, int netId)
{
this.name = name;
this.netId = netId;
}
public int getNetID()
{
return netId;
}
}
Why can't copy over into local variable?
The compiler prompts me the error of
'Cannot convert method group of 'getNetID' delegate blah blah'
Thank you.
Change the method-call to:
int expected = human.getNetID();
In C#, method-calls require parantheses () containing a comma-separated list of arguments. In this case, the getNetID method is parameterless; but the empty parantheses are still required to indicate that your intention is to invoke the method (as opposed to, for example, converting the method-group to a delegate-type).
Additionally, as others have pointed out, there is a mismatch betweem the return-type of the method and the variable you're assigning its value to, which you're going to have to resolve somehow (change both the field-type and method return-type to int / parse the string as an integer, etc.).
On another note, C# natively supports properties for getter-setter semantics, so the idiomatic way of writing this would be something like:
//hyphens are not valid in identifiers
namespace ClassA
{
public class Human
{
// these properties are publicly gettable but can only be set privately
public string Name { get; private set; }
public int NetId { get; private set; }
public Human(string name, int netId)
{
this.Name = name;
this.NetId = netId;
}
// unlike Java, the entry-point Main method begins with a capital 'M'
public static void Main(string[] args)
{
Human human = new Human("Yoon Lee", 99);
int expected = human.NetId; // parantheses not required for property-getter
}
}
}
You're trying to use a method as if it's a property. You need parenthesis and to convert the string to int, or just make getNetID return an int.
I think you meant:
public int getNetID()
{
return netId;
}
Or better still, use automatic properties:
public int NetId {get; private set;} //Notice Making N in Net capital
And then:
int expected = human.getNetID();
This will do the trick (-:
It should be human.getNetID()
Edit: And yes, as Oren says - you should change your netId getter to return int. I assume that is what you want to do.
I see that netId is integer.
getNetID() return type is string.
return type is not matching.
netID is declared as an Int:
public int netId;
but your function getNetID returns a string:
public String getNetID()
Therefore, the body of getNetID makes no sense when it tried to return an int as a string:
return netId;
Human human = new Human("Yoon Lee", 99);
int expected = human.getNetID(); //<-gets the error at this moment.
you need to add parentheses after the method call.
The way you have it right now you are fetcing the function itself.
I have a lot of constant string values in my application which I want to have as strongly typed objects in C# for code reuse and readability. I would like to be able to reference the string value like so:
Category.MyCategory //returns a string value ie “My Category”
Category.MyCategory.Type.Private //returns a string value ie “private”
Category.MyCategory.Type.Shared //returns a string value ie “shared”
I have started by implementing the following classes each containing a list of public string valued fields with a public property which exposes the child.
Category, MyCategory, Type
However I already know this is not the way to go so could do with a bit of advice on this one.
An example of this is where I am using the Syndication classes to add a category to an atom feed. I am creating the items in this feed dynamically so need to use the notation as shown.
item.Categories.Add( new SyndicationCategory
{
Scheme = Category.PersonType,
Label="My Category",
Name=Category.MyCategory.Type.Private
});
Keep your string constants close to where you need them, IMO having a class that just declares constants is an OO antipattern
Why not simply implement them as classes with overridden ToString implementations?
public class MyCategory
{
private readonly MyType type;
public MyCategory()
{
this.type = new MyType();
}
public MyType Type
{
get { return this.type; }
}
// etc.
public override string ToString()
{
return "My Category";
}
}
public class MyType
{
public override string ToString()
{
return "My Type";
}
// more properties here...
}
However, for general purposes, consider whether the strings in themselves don't represent concepts that are better modeled as full-blown objects.
I completely agree with Rob. If you still want to have a "bag of strings", you could try using nested classes, something like below. I don't really like it, but it works.
public class Category
{
public class MyCategory
{
public const string Name = "My Category";
public class Type
{
public const string Private = "private";
public const string Shared = "shared";
}
}
}