I have a combo box that populates data from the database, which, based on a list box selection populates the data within a given list box through an SQL query. Problem is that the display member property wont show. I wont show the back-end sql because that works fine and the list box actually populates just not the display member. So the data in the list box is blank.
Here is the code:
The Combobox method:
private void populateFromMedication()
{
MedicationList medicationItem = new MedicationList();
// if item is selected
if( !( ( Locations )cmbLocationDescriptionList.SelectedItem == null ) )
{
// set location to be the seletect location from the combo
location = ( Locations )cmbLocationDescriptionList.SelectedItem;
List<MedicationList> fromMedicatitionList = new List<MedicationList>();
// retrieve a list of medication from the database
fromMedicatitionList = LocationData.RetrieveMedicationByLocation( location.LocationID, GlobalVariables.SelectedResident.ResidentID );
//bind the list for to the medication list
lstMedicationForCurrentLocation.ItemsSource = fromMedicatitionList;
lstMedicationForCurrentLocation.DisplayMemberPath = "Description";
}
}
On form Initialization:
public FormInitialize()
{
InitializeComponent();
LoadData();
LoadResidentData();
populateFromMedication();
}
MedicationList Class:
public class MedicationList
{
public int MedicationID { get; set; }
public string Description
{
get
{
return Description;
}
set
{
Description = value;
OnPropertyChanged( "Description" );
}
}
}
You need to check that
1) There is a property in MedicationList by the name Description and that OnPropertyChanged is applied on its setter.
string _Description;
public string Description
{
get
{
return _Description;
}
set
{
_Description = value;
OnPropertyChanged("Description");
}
}
For more on OnPropertyChanged read this
2) Try giving Displaymember before providing Itemsource.
Related
i am trying to select a given number from my list box but when i run the code it returns null
i have tried .selectedvalue i have tried .selecteditem and .selecteditems
all return null
ID = ExpireditemInfo.GetItemText(ExpireditemInfo.SelectedItem);
ID is a string
This is my source i use dapper
loadinventory = iteminfo.GetExpireinfo(now,expirationDate);
ExpirationID.DataSource = loadinventory;
ExpirationID.DisplayMember = "Expireing_ID";
my data model
public string Transaction_ID { get; set; }
public string Type_Of_Transaction { get; set; }
public string Name { get; set; }
public string Quantity { get; set; }
public string Unit { get; set; }
public string Expireing_ID
{
get
{
return $"{Transaction_ID}";
}
}
i want to select the number 6 from the list-box etc and store that selection in a string which i will then convert to an int to pass along through a stored procedure. the int is for the id column of a database so it has to be an in when passing to the database.
is it that the 6 is not being recognized as a string and if so how do i select it?
i am trying to select a given number from my list box but when i run the code it returns null
After seeing the way you are binding to your ListBox, it seems you are not setting the ValueMember property, doing so you can have an actual DisplayMember and a ValueMember that represents the actual underlying value of that display object.
Here's what I would do, this is just one example:
// Holds the actual selected items value
public string ExpirationIDValue {get; private set;}
// Anytime the selected index changes, we update our property. You can
// put this on the constructor and or on load.
ExpirationID.SelectedIndexChanged += ExpirationID_SelectedIndexChanged;
// Event handler for when selection changes
private void ExpirationID_SelectedIndexChanged(object sender, EventArgs e)
{
if (sender is ListBox listBox && listBox.SelectedValue != null)
{
ExpirationIDValue = listBox.SelectedValue.ToString();
}
}
// This was for testing, just to get some data, you can ignore this
DataTable dataTable = new DataTable();
dataTable.Columns.Add(new DataColumn("Expireing_ID",typeof(string)));
dataTable.Columns.Add(new DataColumn("Expireing_ID_Display",typeof(string)));
int i = 1;
while(i < 10)
{
dataTable.Rows.Add(i.ToString(),$"Display {i}");
i++;
}
// Here you need to make sure you set these properties to your actual
// property names.
ExpirationID.DataSource = dataTable;
ExpirationID.DisplayMember = "Expireing_ID_Display";
ExpirationID.ValueMember = "Expireing_ID";
Note: your selectedindexchanged event may fire early and cause an exception, what you can do is create a variable bool and on loading set it true and then in the event make sure that it's not true. At the end of loading the data, set that back to false.
Hopefully this will fix your issue, if there's something you don't understand or need further clarification, please let me know.
keycode: public string ExpirationIDValue { get; private set; }
private void ExpirationID_SelectedIndexChanged(object sender, EventArgs e)
{
**keycode:** ExpirationIDValue =ExpirationID.GetItemText(
ExpirationID.SelectedItem);
int ID;
ID = Convert.ToInt32(ExpirationIDValue);
loadinventory = iteminfo.ExpireitemInfo(ID);
ExpireditemInfo.DataSource = loadinventory;
ExpireditemInfo.DisplayMember = "Expireing_info";
}
Please note the valuemember was not necessary.
How can I show Text in ComboBox when no item selected in Windows Application using LINQ C#
Here is my code how I get all rooms.... in Combobox.
private void LoadRoom()
{
try
{
db = new HotelEntities();
// cmbProvince.Text = "";
var Room = (from u in db.Room
select new { u.RoomId, u.RoomNumber }).ToList();
cmbRoom.Text = ".. Select.."; // This one do not working.
cmbRoom.DisplayMember = "RoomNumber";
cmbRoom.ValueMember = "RoomId";
cmbRoom.DataSource = Room;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thank you!
If you set the DataSource of a combobox, a currencymanager is used on the background and its position is selected (the first item).
Instead of setting DataSource, try adding the items:
cmbRoom.Items.AddRange(Room);
NB, setting Text as a placeholder will not work if an item is chosen and cleared later, unless you add an extra check (in TextChanged or SelectedIndexChanged)
Fast solution
Create a source class for your ComboItems, with (at least) the properties to Display and the inner value of the property. If you create a generic class you can use it for all your combo boxes.
class ComboDisplay<TSource>
{
public string Display {get; set;}
public TSource Value {get; set;}
}
cmbRoom.DisplayMember = nameof(ComboDisplay.Display);
cmbRoom.ValueMember = nameof(ComboDisplay.Value);
When you create the data source for your combobox, make sure you add a default value. In the example below I assume that you want to select items of type Room in your combo:
IEnumerable<Room> availableRooms = myDbContext.Rooms
.Where(room => room.IsAvailable)
.Select(room => new ComboDisplay<Room>
{
Display = room.Name,
Value = new Room
{
Id = room.Id,
...
},
})
// add a dummy value if nothing is selected
.Concat(new Room[]
{
Display = "Please select a room",
Value = null, // meaning: nothing selected
});
After selection, use comboBox1.SelectedValue to get the selected Room, or null if nothing is selected.
Create a Special Combobox class
If you have to use this regularly, consider creating a generic sub class of ComboBox that can display items of a certain TSource, and will return null if nothing is selected:
class MyComboBox<TSource> : ComboBox
{
public MyComboBox() : base()
{
base.DataSource = this.EmptyList;
base.DisplayMember = nameof(ComboDisplay.Display);
base.ValueMember = nameof(ComboDisplay.Value);
}
private static readonly EmptyItem = new ComboDisplay
{
Display = "Please select a value",
Value = null,
}
Make a property that returns the available combo items. Make sure that the EmptyItem is always in the collection:
public IReadonlyCollection<TSource> ComboItems
{
get {return (IReadOnlyCollection<TSource>)base.DataSource;}
set
{
// TODO: check if the empty element is in your list; if not add it
base.DataSource = value;
}
}
Finally: the function to get the Selected value, or null if nothing is selected:
public TSource SelectedValue
{
get => return (TSource)base.SelectedValue;
set
{
// TODO: check if value is in ComboItems
base.SelectedValue = value;
}
}
I believe I have read every document on the internet regarding this issue and I'm still having trouble.
I have a DataGridView populated by two List and combined into a var
topList = ShippingOrder.GetTopGroups();
topItemsList = ShippingOrder.GetCurrentTopSheet();
topList.AddRange(topItemsList);
var newList = topList.OrderBy(x => x.GroupOrder).ToList();
One of the columns in the DdataGridView is a ComboBox. It's populated from a separate List
alertList = GetComboBoxValue();
It's values are associated with the datagridview combox.
emailRecipientDataGridViewComboBoxColumn.DataSource = alertList;
emailRecipientDataGridViewComboBoxColumn.DataPropertyName = "EmailAlert";
emailRecipientDataGridViewComboBoxColumn.DisplayMember = "PopUpText";
emailRecipientDataGridViewComboBoxColumn.ValueMember = "PopUpValue";
The DataPropertyName corresponds to topList.EmailAlert.
The DisplayMember corresponds to alertList.PopUpText.
The ValueMember corresponds to alertList.PopUpValue.
Then the datagrid is filled
dgvTopSheet.DataSource = newList;
CurrencyManager cm = (CurrencyManager)(dgvTopSheet.BindingContext[newList]);
cm.Refresh();
Once the datagrid is filled, everything looks good except the combobox value is not showing. I can use the dropdown arrow and the values acquired from the alertList show up but the comboxbox value isn't binding the value from topList on load.
As I understand from the 50 plus documents I've read on the datagridviewcombobox the DataPropertName is the field needed to bind the control to the data in the dgv. This doesn't appear to be working and 4 hours later I'm a bit frustrated. Something simple seems to be alluding me greatly.
Any help is appreciated.
eta -
The BusinessObjects Class
public class BusinessObjects : INotifyPropertyChanged
{
public BusinessObjects()
{
}
private string popUpText;
public string PopUpText
{
get { return popUpText; }
set
{
popUpText = value;
OnPropertyChanged(new PropertyChangedEventArgs("PopUpText"));
}
}
private string popUpValue;
public string PopUpValue
{
get { return popUpValue; }
set
{
popUpValue = value;
OnPropertyChanged(new PropertyChangedEventArgs("PopUpValue"));
}
}
}
The ShippingOrder Class
public class ShippingOrder : INotifyPropertyChanged
{
private string emailAlert;
public string EmailAlert
{
get { return emailAlert; }
set
{
emailAlert = value;
OnPropertyChanged(new PropertyChangedEventArgs("EmailAlert"));
}
}
private string partNumber;
public string PartNumber
{
get { return partNumber; }
set
{
partNumber = value;
OnPropertyChanged(new PropertyChangedEventArgs("PartNumber"));
}
}
}
sample data looks like:
ShippingOrder.PartNumber = "1234Dp01".
ShippingOrder.EmailAlert = "BSmith#example.com".
BusinessObject.PopUpText = "Bob Smith".
BusinessObject.PopUpValue = "BSmith#example.com".
What I would like to do is to populate a drop down menu from a database.
First of all I plan to use a combo box.
I have created an object that contains the data that I need to take from the database. The object is as follows
namespace RLMD
{
public class FlashCardLevel
{
private int intFCLId;
private String strFCLName;
public FlashCardLevel(int intFCLId, String strFCLName)
{
this.intFCLId = intFCLId;
this.strFCLName = strFCLName;
}
public int IntFCLId
{
get { return intFCLId; }
set { this.intFCLId = value; }
}
public String StrFCLName
{
get { return strFCLName; }
set { this.strFCLName = value; }
}
}
}
What I need to do is to add a list of items from a database, but for ease of use I have simulated given some sample data.
public List<FlashCardLevel> Rifle(List<FlashCardLevel> fcLevel)
{
fcLevel.Add(new FlashCardLevel(1, "Severe"));
fcLevel.Add(new FlashCardLevel(2, "Moderate"));
fcLevel.Add(new FlashCardLevel(3, "Mild"));
fcLevel.Add(new FlashCardLevel(4, "Slight"));
return fcLevel;
}
I'm calling the method here.
List<FlashCardLevel> fcLevel = new List<FlashCardLevel>();
talkToDatabase.Rifle(fcLevel);
this.comboCardLevel.DataSource = fcLevel;
this.comboCardLevel.DisplayMember = "Name";
this.comboCardLevel.ValueMember = "Value";
The combobox is displaying no information.
I would appreciate any help
Updated:
The DisplayMember Property should be referring to FlashCardLevel (class), Property StrFCLName and ValueMember should be pointing to IntFCLId.
List<FlashCardLevel> fcLevel = new List<FlashCardLevel>();
talkToDatabase.Rifle(fcLevel);
this.comboCardLevel.DataSource = listFromDatabase;
this.comboCardLevel.DisplayMember = "StrFCLName";
this.comboCardLevel.ValueMember = "IntFCLId";
The DisplayMember and ValueMember should point to your properties name.
this.comboCardLevel.DisplayMember = "IntFCLId";
this.comboCardLevel.ValueMember = "StrFCLName";
I have the following issue: I am creating a Windows Phone 7 application and I am using a ListBox which is bound to an ObservableCollection people. The implementation of this you see below:
public class Person
{
private string _id { get; set; }
private string _name { get; set; }
public Person(string Id, string Name, string Title)
{
_id = Id;
_name = Name;
}
public string Id
{
get { return _id; }
set
{
_id = value;
FirePropertyChangedEvent("Id");
}
}
public string Name
{
get { return _name; }
set
{
_name = value;
FirePropertyChangedEvent("Name");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void FirePropertyChangedEvent(string propertyName)
{
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
The people Collection is filled with Person objects. They are created in the following function... listValues is my ListBox.
void svc_GetHierachyCompleted(object sender, HCMobileSvc.GetHierachyCompletedEventArgs e)
{
var data = e.Result.ToArray();
listValues.ItemsSource = null;
people.Clear();
int i = 0;
foreach(var item in data)
{
if (i == 0)
{
// Manager
mgrField1.Text = item[1].ToString();
mgrField2.Text = item[2].ToString();
i++;
}
else
{
// Untergebenen hinzufügen
people.Add(new Person(item[0].ToString(), item[1].ToString(), item[2].ToString()));
}
}
// Update List
listValues.ItemsSource = people;
}
Now I have a DataTemplate with two textblocks bound to both properties Id and Name. When the SelectionChanged event is fired I try to rebuild the entire list (so I call the function above again) using the following code:
string id = people[listValues.SelectedIndex].Id;
MessageBox.Show(id);
CreateHierachy(id);
The CreateHierachy just only queries a WebService which then goes into the method above. The problem is, as soon as I select a value in the ListBox I get the following error:
ArgumentOutOfRangeException {"\r\nParameter name: index"}
The error is caused by the line listValues.SelectedIndex.
I absolutely have no idea why that happens. What I know is that the MessageBox shows me the correct SelectedIndex value. What I also know is that when I remove the line people.Clear() that the error goes away but the ListBox does not get Updated.
Any ideas where the problem might be?
Thanks!!!
Bye,
WorldSignia
You should check here for SelectedIndex being >= 0:
if (listValues.SelectedIndex >= 0)
string id = people[listValues.SelectedIndex].Id;