Hey guys, i figured out how to add items to a listbox one line at a time:
try
{
if (nameTxtbox.Text == "")
throw new Exception();
listBox1.Items.Add(nameTxtbox.Text);
nameTxtbox.Text = "";
textBox1.Text = "";
nameTxtbox.Focus();
}
catch(Exception err)
{
MessageBox.Show(err.Message, "Enter something into the txtbox", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
But I wont to be able to add multiple items to the same line. Like have first_name |
last_name | DoB all on the same line. When I do
listBox1.Items.Add(last_name.Text);
It adds the last name to a new line on the listbox, I need to add it to the same line as the first name.
It sounds like you still want to add one "item", but you want it to contain more than one piece of text. Simply do some string concatenation (or using string.Format), eg.
listBox1.Items.Add(string.Format("{0} | {1}", first_name.Text, last_name.Text));
Usually you don't want to include multiple columns into a ListBox, because ListBox is meant to have only one column.
I think what you're looking for is a ListView, which allows to have multiple columns. In a ListView you first create the columns you need
ListView myList = new ListView();
ListView.View = View.Details; // This enables the typical column view!
// Now create the columns
myList.Columns.Add("First Name", -2, HorizontalAlignment.Left);
myList.Columns.Add("Last Name", -2, HorizontalAlignment.Left);
myList.Columns.Add("Date of Birth", -2, HorizontalAlignment.Right);
// Now create the Items
ListViewItem item = new ListViewItem(first_name.Text);
item.SubItems.Add(last_name.Text);
item.SubItems.Add(dob.Text);
myList.Items.Add(item);
Here has a solution to add multiples items at the same time.
public enum itemsEnum {item1, item2, itemX}
public void funcTest2(Object sender, EventArgs ea){
Type tp = typeof(itemsEnum);
String[] arrItemEnum = Enum.GetNames(tp);
foreach (String item in arrItemEnum){
ListBox1.Items.Add(item);
}
}
Hope this can help.
Related
I am comparing a list of strings with a reference list and storing the strings which are different from the reference list in another list. Now how can i display all the contents of new list using C# coding.
Please help me.
The simplest option would be to just create a large string with one line per item in the list:
var newLineSepratedString = string.Join(Environment.NewLine, myListOfStrings);
This can then be used as the message in your messageBox, or concatenated to some description.
Note that this works fine if the list is small. If you try to display to many items your messagebox will start to become larger than your screen, and that is just not useful. If you need to handle larger sections of text you should create your own dialog with a textbox that can be scrolled.
You only have to build a string with all the list items. Then, you can put this new string into the MessageBox:
List<string> list = new List<string>()
{
"Item 1",
"Item 2",
"Item 3"
};
string allItems = string.Empty;
foreach (string item in list)
{
if (allItems.Length > 0)
{
allItems += "\n";
}
else { } //TODO Nothing
allItems += item;
}
MessageBox.Show($"My Items:\n{allItems}", "Items", MessageBoxButtons.OK, MessageBoxIcon.Information);
This will print all items one down last one.
I have a listview with two columns. The first column is filled with items imported from an external file.
The second column is supposed to be filled with values that are calculated in another function of the software.
How is this possible?
EDIT
string[] arr = new string[4];
ListViewItem itm;
private void button3_Click(object sender, EventArgs e)
{
listView1.Columns.Add("ProductName", 100);
listView1.Columns.Add("Price", 70);
//Add items in the listview
//Add first item
arr[0] = "product_1";
itm = new ListViewItem(arr);
listView1.Items.Add(itm);
//2
arr[0] = "product_2";
itm = new ListViewItem(arr);
listView1.Items.Add(itm);
listView1.CheckBoxes = true;
The result is something like this :
Now I have another function, a simple button. Let's say that I want to press the button and fill the second column of the listview with some values. In this case it is the price of each product.
I wrote the following :
private void button4_Click(object sender, EventArgs e)
{
//1
arr[1] = "20000";
itm = new ListViewItem(arr);
listView1.Items.Add(itm);
//Add second item
arr[1] = "200";
itm = new ListViewItem(arr);
listView1.Items.Add(itm);
}
The result is like this :
The first column is changing as well. I only want to put the prices calculated at one function next to a list of products.
Looks like in your second button you are adding a new item when you actually want to update an existing item. Well add a child to an existing item.
Try this in your second button click.
listView1.Items[index].SubItems.Add("20,000");
Where index is the 0-based index of the item you want to modify. You may wish to use a foreach loop to update all the items. Which would look something like this.
foreach (ListViewItem item in listView1.Items)
{
//Do your calculation or whatever it is you want to per item here...
item.SubItems.Add("20,000");
}
Hopefully this helps. :)
New to c# and .net and I'm trying to throw together a listview that has three columns, Quantity, Item description and Price. I know how to fill the rows with data and I can even add the subitem below but what I can't figure out is how I can group them together as a primary item with "children" items tied to it...
Sorry for my most likely incorrect verbiage, but this is what I am shooting for:
Qty Description Price
1 Widget 2.95
Widget add on .25
Widget insurance 1.25
1 Sprocket 4.95
Sprocket add on .50
I am trying to figure out how to group the subitems below the primary item to make it where when I select, for instance, "Widget insurance", it highlights "Widget add on" and "Wiget" as one entity. So for example if I need to go back and remove "Widget insurance" from the purchase of the "Widget" I can click on any item connected to "Widget", ex. "Widget", "Widget add on" or "Widget insurance" and it will pull up another form that allows me to deselect "Widget insurance", hit OK and it would update the list accordingly...
I've (poorly) thrown together code that visually gives me what I am looking for, but I think I am completely confusing the use of subitem and it's purpose:
string[] newItem = new string[3];
ListViewItem itm;
newItem[0] = "1";
newItem[1] = "Widget";
newItem[2] = "2.95";
itm = new ListViewItem(newItem);
listView1.Items.Add(itm);
string[] newSubItem = new string[3];
ListViewItem sub;
newSubItem[0] = "";
newSubItem[1] = "Widget add on";
newSubItem[2] = ".25";
sub = new ListViewItem(newSubItem);
listView1.Items.Add(sub);
Any help would be greatly appreciated.
Here you are. "Qty" will be ListViewItem's text. "Description" and "Price" will be ListViewItem's SubItems.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
listView1.View = View.Details;
listView1.Columns.Add("Qty", 100, HorizontalAlignment.Left);
listView1.Columns.Add("Description", 100, HorizontalAlignment.Left);
listView1.Columns.Add("Prie", 100, HorizontalAlignment.Left);
var details = new[] {"Widget", "2.95"};
var item = new ListViewItem("1");
item.SubItems.AddRange(details);
listView1.Items.Add(item);
details = new[]{ "Widget add on",".25"};
item = new ListViewItem("");
item.SubItems.AddRange(details);
listView1.Items.Add(item);
}
}
Hope this help.
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
This is my window application code for listview :-
// Create three items and three sets of subitems for each item.
ListViewItem item1 = new ListViewItem("item1", 0);
item1.SubItems.Add("1");
item1.SubItems.Add("2");
item1.SubItems.Add("3");
ListViewItem item2 = new ListViewItem("item2", 1);
item2.SubItems.Add("4");
item2.SubItems.Add("5");
item2.SubItems.Add("6");
ListViewItem item3 = new ListViewItem("item3", 0);
// Place a check mark next to the item.
item3.Checked = true;
item3.SubItems.Add("7");
item3.SubItems.Add("8");
item3.SubItems.Add("9");
// Create columns for the items and subitems.
// Width of -2 indicates auto-size.
listView1.Columns.Add("Item Column", 100, HorizontalAlignment.Left);
listView1.Columns.Add("Column 2", 100, HorizontalAlignment.Left);
listView1.Columns.Add("Column 3", 100, HorizontalAlignment.Left);
listView1.Columns.Add("Column 4", 100, HorizontalAlignment.Center);
//Add the items to the ListView.
listView1.Items.AddRange(new ListViewItem[] { item1, item2, item3 });
Then i add the lisview control in Coded UI test :-
In the coded UI test i used below code
WinList wkList = this.UIForm1Window.UIListView1Window.UIListView1List;
string[] strVal = CommonExtensions.GetValuesOfControls(wkList.Items);
foreach(WinControl control in this.UIForm1Window.UIListView1Window.UIListView1List.Items)
{
int count = control.GetChildren().Count;
object objVal = CommonExtensions.GetValue(control);
WinListItem lstItem = (WinListItem)objVal;
}
in the "strVal " variable gives only values of first column not the subitems.
in add watch window i get below mentioned value:-
strVal[0] = "item1"
strVal[1] = "item2"
strVal[2] = "item3"
I have also used the http://blogs.msdn.com/b/gautamg/archive/2010/02/19/useful-set-of-utility-functions-for-coded-ui-test.aspx?CommentPosted=true#commentmessage
WinListItem listItem = new WinListItem(control);
string[] strSubItems = WinExtensions.GetColumnValues(listItem);
In the above statement i am getting Invalid Io expection stating "The control passed is not a list view item control. This operation is valid only for list view item control."
Please suggest any other alternative ?.
I usually use smth like that:
WinList list;
UITestControlCollection columns = websitesList.Columns; // Get Columns names
// Get values
foreach (WinControl item in list.Items)
{
WinListItem listItem = new WinListItem(item);
string[] subItems = WinExtensions.GetColumnValues(listItem); // So you get value = subitem[i] in column[i]
}