I have a Struct that looks like this:
public struct Server
{
public String ServerName, ServerUrl, ServerEnvironment;
};
Then I create a List of Structs:
List<Server> MyServers = new List<Server>();
...and read about eight records into it from a small XML file. This is working well, and if I hover over "MyServers" in the debugger, it looks something like this:
MyServers Count=8
[0] {MyApp.Server}
ServerEnvironment "DEV"
ServerName "My Dev Server #1"
ServerUrl "https://mydev1.mycompany.com/"
[1] {MyApp.Server}
etc...
Then if I do something like MessageBox.Show(MyServers[0].ServerName);, it displays the expected value.
Now what I would like to do is create a ComboBox from the ServerName fields. When the user selects one, I think I would then use the SelectedIndex property of the ComboBox to access the other information (ServerUrl and ServerEnvironment) for the selected ServerName.
I thought I could do something like this:
comboBoxServers.DataSource = MyServers ... something ... ServerName;
But I can't seem to find anything that works. Is this even possible, or do I need to create a separate, simple List with only the ServerName strings and use that for the ComboBox DataSource?
You can use only DisplayMember to show names as Text in combobox.
Then comboBox.SelectedValue will return whole object.
But for using DisplayMember you need change field ServerName to the property
public struct Server
{
public string ServerName { get; set; }
}
comboBoxServers.DisplayMember = "ServerName";
comboBoxServers.DataSource = MyServers;
If you don't want change fields of struct to the property you can override ToString method for your struct.
ComboBox simply calling .ToString() on every item in the datasource, if DisplayMember not assigned, for generating Text of item.
public override string ToString()
{
return Name;
}
Then you can access selected server information through comboBoxServers.SelectedValue which return whole instance of Server
var selectedServer = (Server)comboBoxServers.SelectedValue;
selectedServer.ServerUrl;
selectedServer.ServerEnvironment; // ...
Create List Server:
List<Server> Servers= new List<Server>()
{
new Server {ServerEnvironment = "DEV", ServerName = "My Dev Server #1"},
new Server {ServerEnvironment = "DEV1", ServerName = "My Dev Server #2"},
};
Then add list to comboBox:
comboBoxServers.DataSource = Servers;
comboBoxServers.ValueMember = "ServerEnvironment ";
comboBoxServers.DisplayMember = "ServerName" ;
This might do the trick for you
comboBoxServers.ValueMember = ServerUrl;
comboBoxServers.DisplayMember = ServerName;
comboBoxServers.DataSource = MyServers;
DisplayMember: Gets or sets the property to display for any ListControl. The String specifying the name of an object property that is contained in the collection specified by the DataSource property.
ValueMember: Gets or sets the path of the property to use as the actual value for the items in the ListControl. This String representing a single property name of the DataSource property value, or a hierarchy of period-delimited property names that resolves to a property name of the final data-bound object.
So now when the user selects one in the comboBoxServers you can access the other information (ServerUrl and ServerEnvironment) for the selected ServerName like
string urlenv = comboBoxServers.SelectedValue;
string serName = comboBoxServers.Text;
Related
I'm trying to get the LookUpEdit to show an initial value when the form is displayed. I'm binding a list of countries as the datasource and then setting the EditValue when the form loads which should show the country as the selected item in the LookUpEdit. Unfortunately, it just shows an empty value. The LookUpEdit appears to otherwise work and allows me to scroll through the list of countries and select an item and the value is passed back when I submit the form.
The Country class:
public class Country
{
public Country();
public int CountryId {get; set;}
public string CountryName {get; set;}
public string IsoCode {get; set; }
}
The code behind the form containing the LookUpEdit:
this.country.Properties.DataSource = this.Countries;
this.country.Properties.DisplayMember = "CountryName";
this.country.Properties.ValueMember = "CountryId";
this.country.EditValue = initialCountry;
this.country.DataBindings.Add("EditValue", viewModel.Address, "AddressCountry", false, DataSourceUpdateMode.OnPropertyChanged);
In this example this.Countries is a populated List<Country> and initialCountry is set to an instance of Country and viewModel.Address contains a property Country AddressCountry.
I've tried both setting the EditValue directly only and setting the data binding to EditValue on it's own as well. Whatever I try, the LookUpEdit is always blank when the form loads and I need it to be set to the initialCountry. I'm sure it's something really simple but I'm not seeing it so any help is much appreciated.
In addition to the Marko's answer:
There is a special mode of data binding to the entire business objects in lookup:
this.country.Properties.DataSource = this.Countries;
this.country.Properties.DisplayMember = "CountryName";
this.country.Properties.KeyMember = "CountryId";
this.country.EditValue = initialCountry;
This mode allows the lookup mechanism to find a match between the editor's value (a Country business object) and another Country business objects in the lookup data source, via the key field ("CountryId") is assigned to the RepositoryItemLookUpEditBase.KeyMember property.
Here are some additional benefits of this mode:
you can use multiple key fields ("composite/compound key" feature);
// field names delimited with the ';' character
this.city.Properties.KeyMember = "CountryId;RegionId;CityName";
you can match the business objects, loaded from the separate data-contexts, and use all the advantages of lazy-loading approach:
// The CountryId value is enough for match.
// All the another fields(e.g. CountryName) can be skipped while loading
this.country.EditValue = new Country() { CountryId = 5 }
You should not set this.country.EditValue to an instance of Country, but to CountryId, since this is your ValueMember.
this.country.EditValue = initialCountry.CountryId;
EDIT: if you want to get the selected object you should use GetDataSourceRowByKeyValue
var selectedCountry = this.country.GetDataSourceRowByKeyValue(this.country.EditValue) as Country;
Edit Value requires Data with Exact Data Type as it in Database,
so assign data with convert function of appropriate data type
Consider the following text as two lists(separated with ':'), as you can see the second rows are always unique but items in the first row can be repetitive;
Book:m234
Clover:h67
Pencil:a12
Book:x67
I want to populate a listbox with items in the first column(Book, Clover, ...) but the problem is that when I'm going to retrieve the selected item in the listbox, I can't be sure about it's respective value in second column. (for example in case of 'Book');
NOTE: I'm not looking for any workaround for solving this problem because there are many. What I want to know is that:
Is it possible to pass and object to ListBox.Items.Add() in a way that the object carries two values(each value/property for each column) and in time of getting the selected item, we would have an object with the two values(maybe as the properties of the object)?
Is such a thing possible in C#? (.NET 4.5)
You can pass objects that pair data with names to your ListBox, and control what gets displayed and what gets returned back to you by using DisplayMember and ValueMember:
class ListBoxItem {
public string DisplayName {get;set;}
public string Identifier {get;set;}
}
...
ListBox.Items.Add(new ListBoxItem {
DisplayName = "Book", Identifier = "m234"
});
ListBox.Items.Add(new ListBoxItem {
DisplayName = "Clover", Identifier = "h67"
});
ListBox.Items.Add(new ListBoxItem {
DisplayName = "Pencil", Identifier = "a12"
});
ListBox.Items.Add(new ListBoxItem {
DisplayName = "Book", Identifier = "x67"
});
ListBox.DisplayMember = "DisplayName";
ListBox.ValueMember = "Identifier";
Now your list box displays the same list of strings, but the values returned for end-user selections would be different.
I have a custom object with several properties, one of which returns a list. This is the code for the object:
public class SearchResult
{
private int eventId;
private String eventTitle;
private int startDate;
private List<String> tags;
// Properties
public int EventId { get { return this.eventId; } }
public String EventTitle { get { return this.eventTitle; } }
public int StartDate { get { return this.startDate; } }
public List<String> Tags { get { return this.tags; } }
public SearchResult(int eventId, String eventTitle, int startDate, List<String> tags)
{
// Constructor code
}
public List<String> GetTags()
{
return this.tags;
}
}
I also have a DataGridViewComboBoxColumn that I want to bind to the Tags property. Basically, each SearchResult object will be displayed in its own row, and I want the List<String> in the Tags property of each object to be displayed in a ComboBox cell in that row. This is the code I have so far for my DataGridView:
BindingList<SearchResult> results = new BindingList<SearchResult>();
results.Add(new SearchResult(1, "This is a title", 2012, new List<String> { "Tag1", "Tag with a long name1" }));
results.Add(new SearchResult(2, "The quick brown fox", 2012, new List<String> { "Stack", "Overflow" }));
results.Add(new SearchResult(3, "In this tutorial, you create a class that is the type for each object in the object collection. ", 2012, new List<String> { "NYSE", "FTSE" }));
results.Add(new SearchResult(4, "another long piece of title text", -999, new List<String> { "Rabbits", "Chickens" }));
MyDataGrid.AutoGenerateColumns = false;
MyDataGrid.AllowUserToAddRows = false;
MyDataGrid.AllowUserToDeleteRows = false;
MyDataGrid.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.None;
MyDataGrid.BackgroundColor = System.Drawing.SystemColors.Control;
MyDataGrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
MyDataGrid.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders;
MyDataGrid.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.DisplayedCells;
MyDataGrid.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
DataGridViewTextBoxColumn eventIdColumn = new DataGridViewTextBoxColumn();
eventIdColumn.DataPropertyName = "EventId";
eventIdColumn.HeaderText = "Event ID";
eventIdColumn.ReadOnly = true;
eventIdColumn.Width = 84;
DataGridViewTextBoxColumn eventTitleColumn = new DataGridViewTextBoxColumn();
eventTitleColumn.DataPropertyName = "EventTitle";
eventTitleColumn.HeaderText = "Event Title";
eventTitleColumn.ReadOnly = true;
eventTitleColumn.Width = 368;
DataGridViewTextBoxColumn startDateColumn = new DataGridViewTextBoxColumn();
startDateColumn.DataPropertyName = "StartDate";
startDateColumn.HeaderText = "Start Date";
startDateColumn.ReadOnly = true;
startDateColumn.Width = 130;
//I think I need to insert the code for the tags column here, but I'm not sure
MyDataGrid.Columns.Add(eventIdColumn);
MyDataGrid.Columns.Add(eventTitleColumn);
MyDataGrid.Columns.Add(startDateColumn);
//MyDataGrid.Columns.Add(tagsColumn);
MyDataGrid.DataSource = results;
I derived this code from a tutorial I found online, and it works perfectly.
I've been trying to bind the Tags property of SearchResult to a DataGridViewComboBoxColumn, but I'm not sure how. I've been looking at this question, which provides this code:
column.DataPropertyName = "Foo";
column.DisplayMember = "SomeNameField";
column.ValueMember = "Bar"; // must do this, empty string causes it to be
// of type string, basically the display value
// probably a bug in .NET
column.DataSource = from foo in Foo select foo;
grid.DataSource = data;
The reason I'm having trouble is because of a few nuances of the linked question that I don't understand.
According to the documentation and the linked question, DisplayMember should be linked to the property that "contains a description of the instance", but since SearchResult objects are added dynamically and don't have any description associated with them, should I just leave it blank?
ValueMember is giving me similar problems, since I'm unsure what to put even after reading its documentation.
In the linked question, the accepted answer binds the entire datagrid at once using LINQ. Is that how I should be doing this? I'm not sure how to modify that code for my situation, but I thought it would be something along these lines.
:
tagsColumn.DataPropertyName = "Tags";
tagsColumn.DisplayMember = ""; // I'm unsure of what to put here
tagsColumn.ValueMember = ""; // Once again, I don't know what to set this to
I also presume I should have a line that sets the DataSource for the column, e.g.
tagsColumn.DataSource = <some LINQ query, perhaps?>
but I don't know because the only mostly relevant C# source I've been able to find is that question.
UPDATE:
I did find a second question that suggests code similar to this for data binding:
// reference the combobox column
DataGridViewComboBoxColumn cboBoxColumn = (DataGridViewComboBoxColumn)dataGridView1.Columns[0];
cboBoxColumn.DataSource = Choice.GetChoices();
cboBoxColumn.DisplayMember = "Name"; // the Name property in Choice class
cboBoxColumn.ValueMember = "Value"; // ditto for the Value property
Based on that, I a) added the GetTags() method to SearchResult and added this code into my DataGridView initialisation code:
DataGridViewComboBoxColumn tagsColumn = new DataGridViewComboBoxColumn();
tagsColumn.DataSource = SearchResult.GetTags(); // ERROR
tagsColumn.DisplayMember = ""; // Still not sure
tagsColumn.ValueMember = ""; // ??
However, Visual Studio gives me an error on the second line when I try to run this:
An object reference is required for the non-static field, method, or property 'SearchResult.GetTags()'
UPDATE 2:
I'm still searching around for this without success. I don't understand how with other properties (e.g. EventId) I can simply declare the data property name as EventId, and it will display in the table, but I cannot do this with ComboBox columns.
Since the objects are instantiated in a separate class and put in a list, it doesn't seem to make sense to me that I should have to loop through the entire array of objects (of which there may be several hundred) to bind the Tags property to the ComboBox column for each instance, when I don't need to loop through the list of SearchResult objects to bind other properties, e.g. EventId.
Why does this binding-properties-by-name only work for some properties and not others?
I don't quite understand why you want to use DataGridViewComboBoxColumn to display a list of elements. This column kind is designed to allow user to select one of many possibilities. It seams it is not your case because you don't have public string SelectedTag{get;set;} property to store it. As I understand your model you have many tags already selected for your SearchResult and you want to display them in grid.
As documentation states:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcomboboxcolumn.datasource
Getting or setting this [DataSource] property gets or sets the DataSource property of the object returned by the CellTemplate property. Setting this property also sets the DataSource property of every cell in the column and refreshes the column display. To override the specified value for individual cells, set the cell values after you set the column value.
DataGridViewComboBoxColumn simply does not have capability to bind items property to data source because it assumes that there is only one list of elements that is used as data source for all rows of data grid.
I also assume that you would set ReadOnly = true property for this column as you have for all other. If so it would prevent user form seeing list of tags because drop down list would never be displayed.
If you wand to display list of strings in read only mode I would suggest to flatten this list of tags to single string:
public string Tags { get { return string.Join(", ", tags); } }
and display it in text column.
For the error , i can suggest you to make an instance of the class and then call the method as its not static or you can make your method static.
Moreover As you needs the comboboxcolumn ,
DataGridViewComboBoxColumn tagsColumn = new DataGridViewComboBoxColumn();
tagsColumn.DataSource = SearchResult.GetTags(); // ERROR
tagsColumn.DisplayMember = ""; // Still not sure
tagsColumn.ValueMember = ""; // ??
Mostly we have dropdowns for objects like Country(id,name) so DisplayMember = name will be shown as text in dropdown while ValueMember = id will be used in the referencing tables in database.But this is not your case.
Here you have a list of strings to show in dropdown , so you don't need to set them.
As written here
If the DataSource property is set to a string array, then ValueMember
and DisplayMember do not need to be set because each string in the
array will be used for both value and display.
I'm using SubSonic 2.2 for my DAL and extended one of my classes with a calculated property that returns a string containing another property with indenting based on the level of the outline at which the item occurs. The code for the property is below. The problem is that when I try to use this property as the DisplayMember for a ListBox control on a form (the reason I wrote it in the first place) it won't work. The ListBox reverts to displaying the ID property which is set as the ValueMember. To test that the property was working I looped through the collection of objects that I was populating the ListBox with and, using MessageBox.Show(obj.property), confirmed that it was indeed returning the value I'm looking for. Am I missing something or should this work? btw - There may be a better way to do the indenting but that's not what I'm after at the moment, thanks!
Code follows:
public partial class InteriorsCategory : ActiveRecord, IActiveRecord
{
public string ListDisplay
{
get
{
string returnValue = "";
for (int i = 1; i < this.SpecLevel; i++)
{
returnValue += " ";
}
returnValue += this.CategoryName;
return returnValue;
}
}
}
<>
I definitely get data in my collection and the binding I'm doing is exactly the same as yours (binding code posted below). The return value of the ListDisplay property that I'm using is a string concatenation of two values in the object. Think of it as a "full name" property that concatenates the FirstName a space and the LastName properties into a single string which it returns. I am trying to bind the ListDisplay property to the DisplayMember property of the listbox, but all that shows in the listbox is the Id field which I am binding to the ValueMember.
private void FillCategories()
{
lstPackageCategories.DataSource = new InteriorsCategoryCollection().Load();
lstPackageCategories.DisplayMember = "CategoryName";
lstPackageCategories.ValueMember = "Id";
((InteriorsCategoryCollection)(lstPackageCategories.DataSource)).Sort("SpecSection", true);
lstPackageCategories.SelectedItem = lstPackageCategories.Items[0];
currentCategory = (InteriorsCategory)lstPackageCategories.SelectedItem;
RefreshAvailableItems();
}
If your able to see your data in the collection, then it sounds like there is a problem on the binding of your ListBox. Here is an example of how I bind a ListBox using a SubSonic collection of values.
ISOCountryCodeCollection countrys =
new ISOCountryCodeCollection().OrderByAsc(ISOCountryCode.Columns.Country).Load();
Country.DataSource = countrys;
Country.DataValueField = "ThreeChar";
Country.DataTextField = "Country";
Country.DataBind();
In the example above, I'm binding the 3 character country code to the "DataValueField" and the full country name to the "DataTextField".
My project display's program names from the database into dropdownlist and each program has a ID. I want to display both name and id in the dropdownlist so that they can be differenciated from each other.
eg: 'california lifeline (CLA)'
where 'california lifeline' is the name of the program and the id is 'CLA'. I have created a stored procedure which displays data based on the program ID.
This the code of my dropdownlist control.
private void LoadProgramName()
{
_drp_program = (DropDownList)Page.FindControl("bodyuc$drp_program");
dsprg = rProxy.GlobalFetchFromDB(strCountyName, "DBO.oea_sp_get_onoff_programNames");
_drp_program.DataSource = dsprg;
_drp_program.DataTextField = "PROG_NAME";
_drp_program.DataValueField = "PROGRAM_ID";
_drp_program.DataBind(); ;
ListItem lst_prog = new ListItem();
lst_prog.Value = "";
lst_prog.Text = "--Select One--";
_drp_program.Items.Insert(0, lst_prog);
_drp_program.Items.Insert(1, "ALL");
}
BTW, the dropdown is a part of pagecontrol.
Help is Appriceated.
If your GlobalFetchFromDB() returns instances of an object which you can "extend" as a partial class, then I'd add a "helper" property to the class that formats your displayed string.
One advantage to this is that the format can be dependent on the values of other properties in the instance.
For example:
public partial class ProgramItem
{
public string DisplayName { get { return PROG_NAME.ToUpper(); } }
}
Then use _drp_program.DataTextField = "DisplayName";
An alternative is to construct a class that encapsulates the returned items and adds the DisplayName as a decorator.
Instead of binding _drp_program to dsprg, loop through the results in dsprg and add each item individually.
foreach(dsprgObject in dsprg)
{
_drp_program.Items.add(new ListItem(dsprgObject .ColA + " " + dsprgObject .ColB, dsprgObject.PROGRAM_ID));
}
You can try
_drp_program.DataSource = from item in dsprg
select new
{
PROG_NAME = string.Format("{0}({1})", item.PROG_NAME, item.PROGRAM_ID) ,
PROGRAM_ID = item.PROGRAM_ID
};
instead of
_drp_program.DataSource = dsprg;
Usually the fastest way is to concatenate ID and NAME in an SQL query (but you're using an sp so that's a bit difficult). Also, since you binding your control in code, you can concatenate ID and Name in code and populate your dropdownlist manually (either by calling Items.Insert or by binding your dropdown to a collection which members have a field/property that contains the concatenated value). AFAIK, you can only specify a field/property name for DataTextField and DataValueField, no expressions etc...