Is it possible to add to checkedListBox item also value and title
checkedListBox1.Items.Insert(0,"title");
How to add also value?
checkedListBox1.Items.Insert(0, new ListBoxItem("text", "value"));
Try setting the DisplayMember and ValueMember properties. Then you can pass an anonymous object like so:
checkedListBox1.DisplayMember = "Text";
checkedListBox1.ValueMember = "Value";
checkedListBox1.Items.Insert(0, new { Text= "text", Value = "value"})
Edit:
To answer your question below, you can create a class for your item like so:
public class MyListBoxItem
{
public string Text { get; set; }
public string Value { get; set; }
}
And then add them like this:
checkedListBox1.Items.Insert(0, new MyListBoxItem { Text = "text", Value = "value" });
And then you can get the value like this:
(checkedListBox1.Items[0] as MyListBoxItem).Value
Related
I'm using ASP.NET to create a dynamic web form with variable controls. Some of the controls that I want to create are dropdownlists, and I would like them to be populated with certain custom subitems. How can I do this? I'm unable to populate the ddl with the subitems themselves (they are not of string type), but am also unable to populate the ddl with a string member variable (subitem.displayName) without losing the entire subitem. Here is some code for reference:
public class SubItem
{
string displayName;
string value;
...
}
At first I tried to add the objects to the ddl directly:
DropDownList x;
x.ItemType = SubItem; //error "type not valid in this context"
x.Add(subitem); // error
Ideally, I could solve this by displaying subitem.name in the ddl, but with the functionality of a subitem being parsed, so that in an event handler I can access all of the subitem's properties. Is there something like the following that exists?
DropDownList x;
x.ItemType = SubItem;
x.DisplayType = SubItem.displayName;
x.Items.Add(subitem);
Thanks in advance!
You can only bind something do a DropDownList that has and IEnumerable interface. Like a List or Array.
//create a new list of SubItem
List<SubItem> SubItems = new List<SubItem>();
//add some data
SubItems.Add(new SubItem() { displayName = "Test 1", value = "1" });
SubItems.Add(new SubItem() { displayName = "Test 2", value = "2" });
SubItems.Add(new SubItem() { displayName = "Test 3", value = "3" });
//create the dropdownlist and bind the data
DropDownList x = new DropDownList();
x.DataSource = SubItems;
x.DataValueField = "value";
x.DataTextField = "displayName";
x.DataBind();
//put the dropdownlist on the page
PlaceHolder1.Controls.Add(x);
With the class
public class SubItem
{
public string value { get; set; }
public string displayName { get; set; }
}
When I set a DataSource on a control and want to use .ToString() as DisplayMember, I need to set the DisplayMember last or the ValueMember will override it.
MSDN on empty string as display member:
The controls that inherit from ListControl can display diverse types of objects. If the specified property does not exist on the object or the value of DisplayMember is an empty string (""), the results of the object's ToString method are displayed instead.
Code to reproduce:
Class:
class SomeClass
{
public string PartA { get; set; }
public string PartB { get; set; }
public string WrongPart { get { return "WRONG"; } }
public override string ToString()
{
return $"{PartA} - {PartB}";
}
}
Form:
var testObj = new SomeClass() { PartA = "A", PartB = "B" };
comboBox1.DataSource = new [] { testObj };
comboBox1.DisplayMember = "";
comboBox1.ValueMember = "WrongPart";
comboBox2.DataSource = new[] { testObj };
comboBox2.ValueMember = "WrongPart";
comboBox2.DisplayMember = "";
You can try it by making a new form and adding 2 combobox's.
Result:
Conclusion and question:
This can be easily fixed by setting them in the correct order however this is prone to errors, it also does not show this behavior if I use an actual property as DisplayMember instead of ""/ToString.
I would really like to know why it displays this behavior and if I could possibly set .ToString() explicitly as DisplayMember (for code clarity).
I have searched in the reference source and found this bit:
if (!newValueMember.Equals(valueMember)) {
// If the displayMember is set to the EmptyString, then recreate the dataConnection
//
if (DisplayMember.Length == 0)
SetDataConnection(DataSource, newValueMember, false);
SetDataConnection method signature:
private void SetDataConnection(object newDataSource, BindingMemberInfo newDisplayMember, bool force)
This sets a new DisplayMember
displayMember = newDisplayMember;
so now we've come to the root of the issue
I have one form in a Windows application as per below image:
I try to use this code to display text in comboBox in "Designer.cs":
this.cmbLanguage.FormattingEnabled = true;
this.cmbLanguage.Items.AddRange(new object[] {
Language.LSelectLang.LANGUAGE_ENGLISH, //"English",
"Chinese_TC",
"Chinese_SC",
Language.LSelectLang.LANGUAGE_GERMAN, //"German",
Language.LSelectLang.LANGUAGE_FRENCH, //"French",
Language.LSelectLang.LANGUAGE_JAPANESE, //"Japanese",
Language.LSelectLang.LANGUAGE_SPANISH, //"Spanish",
Language.LSelectLang.LANGUAGE_HINDI}); //"Hindi"});
It's OK with it, but I want to also pass a value type to access specific text display in combo box.
So, how to pass that in my combo box?
Unluckily, Win Form does not define ListItem like Web, but you can define your own class, then override ToString method:
public class YourItem<T>
{
public string Text { get; set; }
public T Value { get; set; }
public override string ToString()
{
return Text;
}
}
Then you can use:
var item = new YourItem<string>() {
Text = "text",
Value = "value"
};
cmbLanguage.Items.Add(item);
To access value:
var selectedItem = (YourItem<string>) cmbLanguage.SelectedItem;
var value = selectedItem.Value;
I am facing a problem. I have set of some enum in my app. Like
public enum EnmSection
{
Section1,
Section2,
Section3
}
public enum Section1
{
TestA,
TestB
}
public enum Section2
{
Test1,
Test2
}
EnmSection is main enum which contains the other enum(as string) which are declared below it. Now i have to fill the values of EnmSection in a drop-down.I have done it.
Like this...
drpSectionType.DataSource = Enum.GetNames(typeof(EnmSection));
drpSectionType.DataBind();
Now my drop-down has values: Section1,Section2,Section3
Problem is:
I have another drop-down drpSubSection. Now i want to fill this drop-down whatever i have selected in the drpSectionType.
for ex If I selected Section1 in drpSectionType then drpSubsection should contain the value
TestA,TestB. Like this:
protected void drpSectionType_SelectedIndexChanged(object sender, EventArgs e)
{
string strType = drpSectionType.SelectedValue;
drpSubsection.DataSource = Enum.GetNames(typeof());
drpSubsection.DataBind();
}
Here typeof() is expecting the enum.But i am getting selected value as string. How can i achieve this functionality.
Thanks
What if you reference an assembly that contains another enum with a value named Section1?
You'll just have to try all the enums you care about, one at a time, and see which one works. You'll probably want to use Enum.TryParse.
Something like this might work, but you have to do some exception handling:
protected void drpSectionType_SelectedIndexChanged(object sender, EventArgs e)
{
string strType = drpSectionType.SelectedValue;
EnmSection section = (EnmSection)Enum.Parse(typeof(EnmSection), strType);
drpSubsection.DataSource = Enum.GetNames(typeof(section));
drpSubsection.DataBind();
}
This might be a bit over the top but it would work if you bind bind Arrays of IEnumItem to your drop down and set it up to show their display text.
public interface IEnumBase
{
IEnumItem[] Items { get; }
}
public interface IEnumItem : IEnumBase
{
string DisplayText { get; }
}
public class EnumItem : IEnumItem
{
public string DisplayText { get; set; }
public IEnumItem[] Items { get; set; }
}
public class EnmSections : IEnumBase
{
public IEnumItem[] Items { get; private set; }
public EnmSections()
{
Items = new IEnumItem[]
{
new EnumItem
{
DisplayText = "Section1",
Items = new IEnumItem[]
{
new EnumItem { DisplayText = "TestA" },
new EnumItem { DisplayText = "TestB" }
}
},
new EnumItem
{
DisplayText = "Section2",
Items = new IEnumItem[]
{
new EnumItem { DisplayText = "Test1" },
new EnumItem { DisplayText = "Test2" }
}
}
};
}
}
drpSubsection.DataSource = Enum.GetNames(Type.GetType("Your.Namespace." + strType));
If the enums are in another assembly, (i.e. they're not in mscorlib or the current assembly) you'll need to provide the AssemblyQualifiedName. The easiest way to get this will be to look at typeof(Section1).AssemblyQualifiedName, then modify your code to include all the necessary parts. The code will look something like this when you're done:
drpSubsection.DataSource = Enum.GetNames(Type.GetType("Your.Namespace." + strType + ", MyAssembly, Version=1.3.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089"));
Could any body give a short example for binding a value from list array to listbox in c#.net
It depends on how your list array is.
Let's start from an easy sample:
List<string> listToBind = new List<string> { "AA", "BB", "CC" };
this.listBox1.DataSource = listToBind;
Here we have a list of strings, that will be shown as items in the listbox.
Otherwise, if your list items are more complex (e.g. custom classes) you can do in this way:
Having for example, MyClass defined as follows:
public class MyClass
{
public int Id { get; set; }
public string Text { get; set; }
public MyClass(int id, string text)
{
this.Id = id;
this.Text = text;
}
}
here's the binding part:
List<MyClass> listToBind = new List<MyClass> { new MyClass(1, "One"), new MyClass(2, "Two") };
this.listBox1.DisplayMember = "Text";
this.listBox1.ValueMember = "Id"; // optional depending on your needs
this.listBox1.DataSource = listToBind;
And you will get a list box showing only the text of your items.
Setting also ValueMember to a specific Property of your class will make listBox1.SelectedValue containing the selected Id value instead of the whole class instance.
N.B.
Letting DisplayMember unset, you will get the ToString() result of your list entries as display text of your ListBox items.