Using Lists With Textboxes - c#

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;

Related

Cant read a simple listBox Text/Number [duplicate]

I am trying to get the value of the selected item in the listbox using the code below, but it is always returning null string.
DataSet ds = searchforPrice(Convert.ToString(listBox1.SelectedItem));
Here I am trying to pass the value of selected item as string to method searchforPrice to retrive dataset from the database.
How can i retrive the value of selected item as string?
I am adding items to listbox from combo box which in turn loads the items from the database.
listBox1.Items.Add(comboBox2.Text);
Anybody has answer for this..
If you want to retrieve the display text of the item, use the GetItemText method:
string text = listBox1.GetItemText(listBox1.SelectedItem);
If you are using ListBox in your application and you want to return the selected value of ListBox and display it in a Label or any thing else then use this code, it will help you
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label1.Text = listBox1.SelectedItem.ToString();
}
To retreive the value of all selected item in à listbox you can cast selected item in DataRowView and then select column where your data is:
foreach(object element in listbox.SelectedItems) {
DataRowView row = (DataRowView)element;
MessageBox.Show(row[0]);
}
string textValue = ((ListBoxItem)listBox1.SelectedItem).Content.ToString();
If you want to retrieve your value from an list box
you should try this:
String itemSelected = numberListBox.GetItemText(numberListBox.SelectedItem);
Get FullName in ListBox of files (full path) list (Thomas Levesque answer modificaton, thanks Thomas):
...
string tmpStr = "";
foreach (var item in listBoxFiles.SelectedItems)
{
tmpStr += listBoxFiles.GetItemText(item) + "\n";
}
MessageBox.Show(tmpStr);
...
You can Use This One To get the selected ListItme Name ::
String selectedItem = ((ListBoxItem)ListBox.SelectedItem).Name.ToString();
Make sure that Your each ListBoxItem have a Name property
Elaborating on previous answer by Pir Fahim, he's right but i'm using selectedItem.Text (only way to make it work to me)
Use the SelectedIndexChanged() event to store the data somewhere.
In my case, i usually fill a custom class, something like:
class myItem {
string name {get; set;}
string price {get; set;}
string desc {get; set;}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
myItem selected_item = new myItem();
selected_item.name = listBox1.SelectedItem.Text;
Retrieve (selected_item.name);
}
And then you can retrieve the rest of data from a List of "myItems"..
myItem Retrieve (string wanted_item) {
foreach (myItem item in my_items_list) {
if (item.name == wanted_item) {
// This is the selected item
return item;
}
}
return null;
}
set properties listbox1 DisplayMember = "Text";
set properties listbox1 ValueMember = "Value";
Event
private void listbox1_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedValue = listbox1.SelectedValue.ToString();
}
The correct solution seems to be:
string text = ((ListBoxItem)ListBox1.SelectedItem).Content.ToString();
Please be sure to use .Content and not .Name.
If you want to retrieve the item selected from listbox, here is the code...
String SelectedItem = listBox1.SelectedItem.Value;

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

How to populate dependant checkboxlist in 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
}

Getting value of selected item in list box as string

I am trying to get the value of the selected item in the listbox using the code below, but it is always returning null string.
DataSet ds = searchforPrice(Convert.ToString(listBox1.SelectedItem));
Here I am trying to pass the value of selected item as string to method searchforPrice to retrive dataset from the database.
How can i retrive the value of selected item as string?
I am adding items to listbox from combo box which in turn loads the items from the database.
listBox1.Items.Add(comboBox2.Text);
Anybody has answer for this..
If you want to retrieve the display text of the item, use the GetItemText method:
string text = listBox1.GetItemText(listBox1.SelectedItem);
If you are using ListBox in your application and you want to return the selected value of ListBox and display it in a Label or any thing else then use this code, it will help you
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label1.Text = listBox1.SelectedItem.ToString();
}
To retreive the value of all selected item in à listbox you can cast selected item in DataRowView and then select column where your data is:
foreach(object element in listbox.SelectedItems) {
DataRowView row = (DataRowView)element;
MessageBox.Show(row[0]);
}
string textValue = ((ListBoxItem)listBox1.SelectedItem).Content.ToString();
If you want to retrieve your value from an list box
you should try this:
String itemSelected = numberListBox.GetItemText(numberListBox.SelectedItem);
Get FullName in ListBox of files (full path) list (Thomas Levesque answer modificaton, thanks Thomas):
...
string tmpStr = "";
foreach (var item in listBoxFiles.SelectedItems)
{
tmpStr += listBoxFiles.GetItemText(item) + "\n";
}
MessageBox.Show(tmpStr);
...
You can Use This One To get the selected ListItme Name ::
String selectedItem = ((ListBoxItem)ListBox.SelectedItem).Name.ToString();
Make sure that Your each ListBoxItem have a Name property
Elaborating on previous answer by Pir Fahim, he's right but i'm using selectedItem.Text (only way to make it work to me)
Use the SelectedIndexChanged() event to store the data somewhere.
In my case, i usually fill a custom class, something like:
class myItem {
string name {get; set;}
string price {get; set;}
string desc {get; set;}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
myItem selected_item = new myItem();
selected_item.name = listBox1.SelectedItem.Text;
Retrieve (selected_item.name);
}
And then you can retrieve the rest of data from a List of "myItems"..
myItem Retrieve (string wanted_item) {
foreach (myItem item in my_items_list) {
if (item.name == wanted_item) {
// This is the selected item
return item;
}
}
return null;
}
set properties listbox1 DisplayMember = "Text";
set properties listbox1 ValueMember = "Value";
Event
private void listbox1_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedValue = listbox1.SelectedValue.ToString();
}
The correct solution seems to be:
string text = ((ListBoxItem)ListBox1.SelectedItem).Content.ToString();
Please be sure to use .Content and not .Name.
If you want to retrieve the item selected from listbox, here is the code...
String SelectedItem = listBox1.SelectedItem.Value;

Add all elements of array to datagridview rows except one

I'm reading a text file line by line, and inserting it into an array.
I then have this list called custIndex, which contains certain indices, indices of the items array that I'm testing to see if they are valid codes. (for example, custIndex[0]=7, so I check the value in items[7-1] to see if its valid, in the two dictionaries I have here). Then, if there's an invalid code, I add the line (the items array) to dataGridView1.
The thing is, some of the columns in dataGridView1 are Combo Box Columns, so the user can select a correct value. When I try adding the items array, I get an exception: "The following exception occurred in the DataGridView: System.ArgumentException: DataGridViewComboBoxCell value is not valid."
I know the combo box was added correctly with the correct data source, since if I just add a few items in the items array to the dataGridView1, like just items[0], the combo box shows up fine and there's no exception thrown. I guess the problem is when I try adding the incorrect value in the items array to the dataGridView1 row.
I'm not sure how to deal with this. Is there a way I can add all of the items in items except for that value? Or can I add the value from items and have it show up in the combo box cell, along with the populated drop down items?
if(choosenFile.Contains("Cust"))
{
var lines = File.ReadAllLines(path+"\\"+ choosenFile);
foreach (string line in lines)
{
errorCounter = 0;
string[] items = line.Split('\t').ToArray();
for (int i = 0; i <custIndex.Count; i++)
{
int index = custIndex[i];
/*Get the state and country codes from the files using the correct indices*/
Globals.Code = items[index - 1].ToUpper();
if (!CountryList.ContainsKey(Globals.Code) && !StateList.ContainsKey(Globals.Code))
{
errorCounter++;
dataGridView1.Rows.Add(items);
}
}//inner for
if (errorCounter == 0)
dataGridView2.Rows.Add(items);
}//inner for each
}//if file is a customer file
Say your text file contains:
Australia PNG, India Africa
Austria Bali Indonisia
France England,Scotland,Ireland Greenland
Germany Bahama Hawaii
Greece Columbia,Mexico,Peru Argentina
New Zealand Russia USA
And lets say your DataGridView is setup with 3 columns, the 2nd being a combobox.
When you populate the grid and incorrectly populate the combobox column you will get the error.
The way to solve it is by "handling/declaring explicitly" the DataError event and more importantly populating the combobox column correctly.
private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
//Cancelling doesn't make a difference, specifying the event avoids the prompt
e.Cancel = true;
}
private void dataGridView2_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
e.Cancel = true;
}
So imagine the 2nd column contained a dropdownlist of countries and the 1st & 3rd column contained text fields.
For the 1st and 3rd columns they are just strings so I create a class to represent each row:
public class CountryData
{
public string FirstCountry { get; set; }
public string ThirdCountry { get; set; }
}
For the 2nd column "Countries" combobox cell's I have created a separate class because I will bind it to the 2nd columns datasource.
public class MultiCountryData
{
public string[] SeceondCountryOption { get; set; }
}
Populating the grid with combobox columns and the like as shown here: https://stackoverflow.com/a/1292847/495455 is not good practice. You want to separate your business logic from your presentation for a more encapsulated, polymorphic and abstract approach that will ease unit testing and maintenance. Hence the DataBinding.
Here is the code:
namespace BusLogic
{
public class ProcessFiles
{
internal List<CountryData> CountryDataList = new List<CountryData>();
internal List<MultiCountryData> MultiCountryDataList = new List<MultiCountryData>();
internal void foo(string path,string choosenFile)
{
var custIndex = new List<int>();
//if (choosenFile.Contains("Cust"))
//{
var lines = File.ReadAllLines(path + "\\" + choosenFile);
foreach (string line in lines)
{
int errorCounter = 0;
string[] items = line.Split('\t');
//Put all your logic back here...
if (errorCounter == 0)
{
var countryData = new CountryData()
{
FirstCountry = items[0],
ThirdCountry = items[2]
};
countryDataList.Add(countryData);
multiCountryDataList.Add( new MultiCountryData() { SeceondCountryOption = items[1].Split(',')});
}
//}
}
}
}
In your presentation project here is the button click code:
imports BusLogic;
private void button1_Click(object sender, EventArgs e)
{
var pf = new ProcessFiles();
pf.foo(#"C:\temp","countries.txt");
dataGridView2.AutoGenerateColumns = false;
dataGridView2.DataSource = pf.CountryDataList;
multiCountryDataBindingSource.DataSource = pf.MultiCountryDataList;
}
I set dataGridView2.AutoGenerateColumns = false; because I have added the 3 columns during design time; 1st text column, 2nd combobox column and 3rd text column.
The trick with binding the 2nd combobox column is a BindingSource. In design time > right click on the DataGridView > choose Edit Columns > select the second column > choose DataSource > click Add Project DataSource > choose Object > then tick the multiCountry class and click Finish.
Also set the 1st column's DataPropertyName to FirstCountry and the 3rd column's DataPropertyName to ThirdCountry, so when you bind the data the mapping is done automatically.
Finally, dont forget to set the BindingSource's DataMember property to the multiCountry class's SeceondCountryOption member.
Here is a code demo http://temp-share.com/show/HKdPSzU1A

Categories