Refer List entrys to a ComboBoxItem - c#

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);
}

Related

How to insert an item into an array at a specific index in c#?

I have 2 text boxes (txt1, txt2), 2radio button (rb1, rb2), 2 numericupdown box(nud1,nud2) & combo box.
I want to store the data from the above in an array, in the named places. array name is mycode.
example:
rb1 = mycode[3], combobox=mycode[0], txt1=mycode[6]....etc
Eventually I want to concatnate some of the named idexes in my array. And show in the message box
example:
my code is mycode[3] + mycode[7]
how to do it?
but I don't know best optios is to do this arry, list or any other?
Is this what you are looking for??
myCode[0] = myValue
To use an array, you can create an empty array like this;
var arr = Object[7] //This allows you to add different data types, and 7 sets the array length to hold 7 items
arr[0] = txt1.text;
arr[1] = txt2.text;
You can concatenate this way:
Console.Write($" my code is {arr[1]} + {arr[2]}")
Array is too primitive for your needs. as #timur suggested, you can create a Dictionary<TKey,TValue> which your "TKey" is string and your "TValue" is object. you can use it like this:
// Create a new dictionary of objects, with string keys.
//
Dictionary<string, object> mycode=
new Dictionary<string, object>();
// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
mycode.Add("txt1", "Hello");
mycode.Add("rb1", 2);
you can use actual control references instead of their names as string. all of controls are inherited from Control class. so you can use Dictionary<Control, object>.
here i provide you a simple exapmle with a form that have a TextBox (textBox1), a NumericUpDown (numericUpDown1) and a Button (button1).
Dictionary<Control, object> myDictionary = new Dictionary<Control, object>();
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
if (myDictionary.ContainsKey((Control)sender))
myDictionary[(Control)sender] = ((NumericUpDown)sender).Value;
else
myDictionary.Add((Control)sender, ((NumericUpDown)sender).Value);
}
private void button1_Click(object sender, EventArgs e)
{
if (myDictionary.ContainsKey(numericUpDown1))
textBox1.Text = ((decimal)myDictionary[numericUpDown1]).ToString();
}
with this approach you must do a lot of cast and you must be careful.

Combobox returns null when value is typed

Sorry if it has some obvious solution, but I am trying to solve it for hours but could not find a solution.
I use several ComboBoxes in my WindowsFormsApplication to relate ids with names. The problem is that when a user select an item from the combobox list, it works fine, but when he types an item, the SelectedValue property of the combobox is null.
To simulate the problem, I created a from with one button and a combobox.
In my actual application, I populate the comboboxes with data from tables in a sqlserver database, but for simplicity, here I populate it with a list:
public Form1()
{
InitializeComponent();
List<KeyValuePair<short,short>> l = new List<KeyValuePair<short,short>>();
l.Add(new KeyValuePair<short,short>(1,10));
l.Add(new KeyValuePair<short,short>(2,20));
l.Add(new KeyValuePair<short,short>(3,30));
this.comboBox1.DataSource = l;
this.comboBox1.DisplayMember = "Value";
this.comboBox1.ValueMember = "Key";
}
private void button1_Click(object sender, EventArgs e)
{
if (this.comboBox1.SelectedValue == null)
MessageBox.Show("NULL");
else
MessageBox.Show(this.comboBox1.SelectedValue.ToString());
}
For example, when user select the second item (20) from the list and clicks on the button, messagebox shows 2 as it is expected, but if he types the number 20 into the combobox, the SelectedValue is null.
This problem could be solved by changing the style of combobox:
this.comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
But it prevents user to type into the combobox, so I am forced to use the default ComboBoxStyle.DropDown.
Thats because the combo box does not select the item that you have typed. Add this option
comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
Then it will select the item when ever it was able to find it.
By default it is set to AutoCompleteMode.None.
(I think) This is mainly designed for suggestions but it can solve your problem here. also if you want to show the suggestions:
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
by default it is set to AutoCompleteSource.None.
https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.autocompletemode%28v=vs.110%29.aspx
An option that you have is using the EventHandler on the comboBox1.TextChange event that will allow you to personally handle how the text is translated into the different options.
This can be added to the designer (similar to a button).
this.comboBox1.TextChanged += new System.EventHandler(this.UpdateValue);
Then depending on how want to read the results and see if you have a match you can create a converter, use another key/value, or you can do a boring old tryparse as I will show you. You will need the list as a property that you can reference to see if you have found the proper results.
private void UpdateValue(object sender, EventArgs e)
{
short result;
if (short.TryParse(comboBox1.Text, out result))
{
var matches = from val in l where val.Value == result select val.Key;
{
foreach (short m in matches)
this.comboBox1.SelectedValue = m;
}
}
}
Good luck! Let me know if you need more examples with the event handler. Don't forget to vote.

Delete row from datatable based on condition

In my DataGrid I used a ComboBox in the first column, so it will fetch some data from the database using the DisplayMember and ValueMember concepts. Now I want to remove the value from the ComboBox which is previously selected.
Populating the ComboBox code is given below:
dTable = getDummyTable.GetDummyTble("Dummy", "DNO", "All");
dCmbData = dTable;
cmbDeno.DataSource = dTable;
cmbDeno.DisplayMember = "dyName";
cmbDeno.ValueMember = "dyRemarks";
The next row of selection there should not be a duplicate value in the ComboBox.
How can I achieve this?
Can anyone help me with this?
well try this one out. You have the DataTable which you are using to bind all combos (correct me if I'm wrong). Now all we need to do is that when an item is selected from any combo, we need to remove that item from all the other combos). You will need to declare a class level dictionary to store which combo had what value stored previously:
IDictionary<ComboBox, DataRow> _prevSelection;
//Please don't mind if syntax is wrong worked too long in web
comboBox.OnSelectedIndexChanged += fixItems;
private void fixItems(object sender, EventArgs e)
{
var cbo= sender as ComboBox;
if(cbo==null) return;
var prev = _prevSelection[cbo];
var row=<GET ROW FROM DATATABLE FOR CURRENT SELECTED VALUE>;
_prevSelection[cbo] = row;
UpdateOtherCombos(cbo, prev, cbo.SelectedItem.Value);
}
private void UpdateOtherCombos(ComboBox cbo, DataRow prev, object toRemove)
{
foreach(var gridrow in <YourGrid>.Rows)
{
var c = <FIND COMBO IN ROW>;
if(cbo.Id == c.Id) continue;//combo that triggered this all
var itemToRemove=null;
foreach(var item in c.Items)
{
if(item.Value == toRemove)
{
itemToRemove = item;
break;
}
}
//or you can get index of item and remove using index
c.Items.Remove(itemToRemove);
//Now add the item that was previously selected in this combo (that
//triggered this all)
c.Items.Add(new ComboBoxItem{Value = prev["ValueColumn"],
Text = prev ["TextColumn"]});
}
}
This is just to give you an idea that may help you to find an optimal solution rather than iterating over all combos as it will slow down if you have too many rows in grid or too many items in combos. Still even with this you need to put up some functions/code to make it working. Also please note that I have not worked on WinForms for some time and you need to check if things like ComboBoxItem etc. and any functions called on them exist. :)

Getting multiple values from a List box in C# windows form

I have a list box that is pulling it's data from a sql table. I have its selection mode set to multisimple.
I have the display member for each item set to the Name field from the sql table and the value member for each item set to the ID field from the sql table.
When I select multiple items from the list, how do I get the multiple values? I am able to get the text of one item by using the listboxname.Text but I don't know how to get each value that has been selected all at once.
Any help will be greatly appreciated.
Use the SelectedItems property, the following will get a List<string> representing the selected items:
var items = listBox1.SelectedItems.Cast<object>()
.Select(x=>Convert.ToString(x)).ToList();
To get the exact values (ID), it depends on the underlying item type. If you use a DataTable as DataSource for your listBox, the underlying item type is DataRowView, so the code to get the values IDs should be:
var ids = listBox1.SelectedItems.Cast<DataRowView>()
.Select(row=>row.Row.Field<string>("ID")).ToList();
//suppose the ID field is string
If the underlying item type is just a normal class with 2 properties Name and ID, such as call it Item, the code is simpler like this:
var ids = listBox1.SelectedItems.Cast<Item>()
.Select(item=>item.ID).ToList();
Method 1 : You can use SelectedIndices property of the ListBox to get the All selected items Index values.
then for each selected index you can get the Value of the Item.
Try This:
private void button1_Click(object sender, EventArgs e)
{
List<String> SelectedItems=new List<String>();
foreach (int i in listBox1.SelectedIndices)
{
SelectedItems.Add(listBox1.Items[i].ToString());
}
}
Note : List SelectedItems contains all SelectedItems from the ListBox
Method 2:
You can use SelectedItems property of the ListBox to get the All selected item values directly.
Try This:
private void button1_Click(object sender, EventArgs e)
{
List<String> SelectedItems=new List<String>();
foreach (String s in listBox1.SelectedItems)
{
SelectedItems.Add(s);
}
}
Note : List SelectedItems contains all SelectedItems from the ListBox

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