How to populate dependant checkboxlist in c# - c#

I have three dependant checkboxlists.
1. Countries
2. States
3. Cities
I want to list all the States if the particular Country is selected in the Countries checkboxlist. And similarly if i select any State then the respective Cities should be populated in the cities checkboxlist.
I have created separate functions for States for every Country and calling them with the following code:
private void Country_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (string s in Country.CheckedItems)
{
if (Country.CheckedItems.Contains("US"))
{
US_States_Checked();
}
if (Country.CheckedItems.Contains("Canada"))
{
Canada_States_Checked();
}
}
}
public void Canada_States_Checked()
{
string[] canada_states = new string[12];
canada_states[0] = "Alberta";
canada_states[1] = "British Columbia";
canada_states[2] = "Manitoba";
canada_states[3] = "New Brunswick";
canada_states[4] = "Newfoundland and Labrador";
canada_states[5] = "Northwest Territories";
canada_states[6] = "Nova Scotia";
canada_states[7] = "Ontario";
canada_states[8] = "Prince Edward Island";
canada_states[9] = "Quebec";
canada_states[10] = "Saskatchewan";
canada_states[11] = "Yukon Territory";
State.Items.AddRange(canada_states);
}
I have the following problems:
1. Which property is used for detecting when the checkbox is UnChecked?
2. How to make a check on the name of selected state/country and check whether it is Checked or Not? Something like:
if(country.selectedItem.Equals("US") and country.selectedItem is unchecked....)) {
.......
}
How to remove/clear the particular states/cities when the country is unchecked keeping in mind that it shouldn't remove the states of any other country listed in the states checkboxlist?
Problem is simple but a bit tricky.
Thanks

Separate function for each country is pretty bad idea. You should store data outside of your code. Consider using XML or database or JSON to store data. You can read about XML serialization here and here, for example
After loading data from file to memory you can place it in the dictionary like
Dictionary<string, Dictionary<string, List<String>>> data;
//access data
var cities = data["Canada"]["Ontario"];
And final part - pass selected item to your dictionary:
var states = data[country.selectedItem].Keys;
and
var cities = data[country.selectedItem][state.selectedItem];
I suppose that country and state are names of your CheckBoxList objects.
As for CheckBoxList usage - just implement your logic, all needed methods are described here. (I am still not sure, what are you using: WPF or WinForms or what, but you can find proper docs).
SelectedIndices and SelectedItems return selected elements of checkBoxList.
You can check like this:
var selectedItems = country.SelectedItems;
if (selectedItems.Contains("Canada")
{
//Do what you need
}

Related

How do I get my List Box to display the actual names of my properties in my entity framework data base

My list box is showing the data but not the actual names of it here is some code I used to display it but its not showing the names.
public void WireUpList()
{
FoodListBox.DataSource = GetFood();
}
private BindingList<Food> GetFood()
{
var foodList = nRIDataContext.FoodModels.ToList();
var listBinding = new BindingList<Food>(foodList);
return listBinding;
}
At first I had my method as a List not a binding list and I thought that was the solution but I'm still trying to figure it out.

Refer List entrys to a ComboBoxItem

Situation: I have 3 TextBoxes, a button and a ComboBox. When I enter something in every TextBox and trigger the button, I want that the strings I've written in the TextBoxes can be choosen in the ComboBox as a ComboBoxItem. I've got the idea of putting the strings from the TextBoxes into a list and refer the ComboBoxItem to the correct list-entrys. Or is there a more efficient way to set and get these strings?
Would be nice if some could help me writing the code for it.
private void bAdd_Click(object sender, RoutedEventArgs e)
{
Random random = new Random();
int randomNumber = random.Next(0, 100);
int txBetrag;
txBetrag = int.Parse(betrag1.Text);
int txMonate;
txMonate = int.Parse(monate1.Text);
int txZins;
txZins = int.Parse(zins1.Text);
List<int> abList = new List<int>();
comboBox.Items.Add("1");
}
If you simply want to add txBetrag, txMonate and txZins to your combobox then you don't need a list. At the moment you're creating a list, adding nothing to it and then simply adding 1 entry to your comboBox (not even from your list).
To add your items just do:
comboBox.Items.Add(int.Parse(betrag1.Text));
comboBox.Items.Add(int.Parse(monate1.Text));
comboBox.Items.Add(int.Parse(zins1.Text));
If you really need the list as well (perhaps because it is used elsewhere as well) then you can do the following:
abList.Add(int.Parse(betrag1.Text));
abList.Add(int.Parse(monate1.Text));
abList.Add(int.Parse(zins1.Text));
Then use the list to populate the comboBox:
foreach(var item in abList)
{
comboBox.Items.Add(item);
}
UPDATE
Based off your comment it seems like you want ONE entry in the comboBox that is effectively the 3 textbox values concatenated together. So you could do something like this:
comboBox.Items.Add(betrag1.Text + monate1.Text + zins1.Text);
UPDATE 2
Following you're last comment regarding the fact that you want 1 comboBox item that refers to the 3 values, but doesn't display them, yes you can do this.
Assuming you won't have duplicate entries in the comboBox you could use a Dictionary to map your values to an entry rather than use a list. I'm assuming here that you will have more than 1 entry in your comboBox eventually, otherwise it's a bit pointless having a combobox.
var valueComboMapping = new Dictionary<string, int[]>();
valueComboMapping.Add("Entry 1", new int[] {int.Parse(betrag1.Text), int.Parse(monate1.Text), int.Parse(zins1.Text)};
This will enable you to add mappings at a later date. You can then use the Dictionary to create the listings in the comboBox like this:
foreach(var entry in valueComboMapping.Keys)
{
comboBox.Items.Add(entry);
}
To trigger an event off selecting an item in the comboBox using the SelectedIndexChanged event.
Retrieving the Values
To retrieve your mapped values in the SelectedIndexChanged event you can do something like:
private void comboBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
ComboBox comboBox = (ComboBox) sender;
string entryName = (string) comboBox.SelectedItem;
//retrieve the values from the dictionary using the value of 'entryName'.
List values = new List<int>();
if (valueComboMapping.TryGetValue(entryName, out values)
{
//do something if the key is found.
}
else
{
//do something else if the key isn't found in the dictionary.
}
}
To get this to work you would need to create the dictionary as follows:
var valueComboMapping = Dictionary<string, List<int>>();
Instead of:
var valueComboMapping = Dictionary<string, int[]>();
You can add directly to combobox,no need to add to list.You are using int.Parse, it will generate Format exception.
private void button1_Click(object sender, EventArgs e)
{
comboBox1.Items.Add(betrag1.Text);
comboBox1.Items.Add(monate1.Text);
comboBox1.Items.Add(zins1.Text);
}

Acumatica Dynamic MultiSelect Dropdown

I have a screen entry to store transaction data, I want to use dynamic with multiselect combobox to select status and status data is taken from the table, but when some of the data status is selected, the amount of stored data does not match that has been selected,
I have tried the following code, but it's doesn't work for me.
public class StatusMultiStringListAttribute : PXStringListAttribute
{
public StatusMultiStringListAttribute() : base()
{
PXResultset<StatusTable> rslt = PXSelect<StatusTable>.Select(new PXGraph());
List<string> values = new List<string>();
List<string> labels = new List<string>();
foreach (PXResult<StatusTable> item in rslt)
{
BSMTStatus e = (StatusTable)item;
values.Add(e.StatusID);
labels.Add(e.Description);
}
this._AllowedValues = values.ToArray();
this._AllowedLabels = labels.ToArray();
MultiSelect = true;
}
}
is there any other solution, sorry my English is bad, thanks.
I noticed your comment on http://asiablog.acumatica.com/2016/03/multiselect-combo-box.html and saw that you posted some additional code. Based on your sample code, I identified two problems:
First of all, the values you're loading from the StatusTable DAC contain trailing spaces which are not trimmed. You haven't provided the declaration of the StatusTable DAC, but it's safe to assume from your screenshot that this field has the IsFixed attribute set to true. With these settings, the system will add white space at the end of your value. To save space in the target field, I would recommend to add a Trim() to the constructor code:
foreach (PXResult<StatusTable> item in rslt)
{
BSMTStatus e = (StatusTable)item;
values.Add(e.StatusID.Trim()); //Remove any white-space
labels.Add(e.Description);
}
Second, the status field where you're storing the selected values is not long enough to accommodate multiple selections. It's currently defined as 20 characters ([PXDBString(20, IsFixed=true)]), and even assuming you remove the whitespace you would still be limited to 4 choices. I suggest you to change it to 255, and to also remove IsFixed=true since it's not needed for this field:
[PXDBString(255)]
[PXDefault]
[PXUIField(DisplayName = "Status")]
[StatusStringList]
public virtual string Status

oData SharePoint Add List Item Containing Value Properties

How do you save "Value" and "DataServiceCollection" objects that are part of another SharePoint list item? These are the only properties in my model that are not getting saved.
The generated Food SharePoint model has these sort of properties:
public class Food
{
DataServiceCollection<FoodIngredientValue> Ingredient;
FoodStateValue State;
string _StateValue
}
First, I don't know why there are two ways to add a state value in the model generated by SharePoint. I try populating either one and the state value doesn't populate in SharePoint.
Secondly, I tried populating the Ingredient collection through hard coding FoodIngredientValue objects to the food model before saving and also by querying SharePoint and assigning them to the Ingredient property but it doesn't get saved in SharePoint.
I add a new food item to the SharePoint list using the code below and I verified all three properties are populated in my model but none of them get saved.
public bool Insert(Food food)
{
var dataContext = new FoodDataContext(new Uri(EndpointUrl)) { Credentials = CredentialCache.DefaultNetworkCredentials };
dataContext.AddToFoods(food);
var response = dataContext.SaveChanges().FirstOrDefault();
return response.StatusCode == 201;
}
This was a great blog post explaining how to link complex list items (DataServiceCollecton and Value objects) in the SharePoint oData API:
http://blog.heeresonline.com/2014/07/sharepoint-wcf-dataservices-choice-lookup-column-editing/
The important thing to remember is to add the new item to the data context before you begin populating complex fields of type DataServiceCollection or Value objects. In the case of properties of type DataServiceCollection, there is a little more work that needs to be done to link them properly so they are saved in the data context as shown below for Ingredient. Here is an example of the code that finally worked:
var foodItem = new FoodItem();
dataContext.AddToFoods(foodItem); // Add to context before populating fields so the values are tracked.
foodItem = Mapper.Map(newFood, foodItem);
// DataValue Properties like StateValue objects can now be added since it is tracked by the context.
var state = StateValue.CreateStateValue("Montana");
foodItem.StateValue = state;
// Need to link special DataServiceCollection lists like Ingredient using a reference.
if (newFood.Ingredient != null)
{
newFood.Ingredient.ForEach(c =>
{
var ingredient = FoodIngredient.CreateFoodIngredientValue(c);
dataContext.AttachTo("FoodIngredientValue", ingredient);
foodItem.FoodIngredient.Add(ingredient);
dataContext.AddLink(foodItem, "FoodIngredient", ingredient);
});
}

Using Lists With Textboxes

This is my code for adding to my list:
List<string> myList = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
ListViewItem myList = new ListViewItem(txtBox1.Text);
myList.SubItems.Add(txtBox2.Text);
myList.SubItems.Add(txtBox3.Text);
myList.SubItems.Add(txtBox4.Text);
listView1.Items.Add(myList);
txtBox1.Text = "";
txtBox2.Text = "";
txtBox3.Text = "";
txtBox4.Text = "";
}
This adds to my list and clears and lets me add another post to my list. The problem is I want to be able to repopulate the textboxes to allow me to update a post in the list.
To make my point more clear, my list looks like this:
Code | Name | Price | In stock
------------------------------
123 aa 122 2
124 bb 111 5
Say I want the first post, can I somehow set all the data back into the textboxes by that identifier or do I have search by index? I would like to be able to put the code in the first textbox then hit a button called retrieve that populates the other textfield kinda like going by the unique key in an sql table but I cant find any info on wether its possible or not.
Why don't you create a class that has Code, Name, Price, In stock, and use a List
Public MyItem
{
public string Code;
public string Name,
public float Price;
public bool inStock;
}
List<MyItem> myList = new List<MyItem>();
private void button1_Click(object sender, EventArgs e)
{
MyItem temp = new MyItem()
temp.Code=txtBox1.Text;
temp.Name=(txtBox2.Text);
temp.Price=(txtBox3.Text);
temp.inStock=(txtBox4.Text);
mylist.add(temp);
txtBox1.Text = "";
txtBox2.Text = "";
txtBox3.Text = "";
txtBox4.Text = "";
}
If you implement it this way then you can just use the index to go through all the items in the list. With the example above you would probably need to convert some of the values from the text boxes before you can use them (price to double)
Also if you want to add the items to a Listview and display them a certain way then override the toString property in the MyItem class and you can display whatever text you want. Hope this helps.
You shouldn't store data only in controls. I would create a class to hold all the info about a particular item, and populate THAT with the contents of the textboxes, and store it in some collection (Maybe a dictionary if you want to look one up by code)
You can then add a reference to this object in the "Tag" property of ListViewItem, so you can immediately grab it from any selected ListViewItem.
I dont quite understand what you mean by saying "can I somehow set all the data back into the textboxes by (that identifier) " which identifier ?!
but i would get data like this:
var item = listview1.items.where(x=>x.SubItems[0].value == mycodeId).firstordefault();
now i have the item i can retrieve data from it:
textbox1.Text = item[1].value;

Categories