Populating ComboBox with some data and then reading the selected row - c#

Good day all. I am trying to accomplish the following:
In a C# WinForm I am having a ComboBox.
In a local data-base I have some "groups" that after execution become folder in "D://" ( they are five )
After that in all the folders I have some files ( the number varies )
I do not know how to populate the ComboBox with the names of those files, and after that when pressing a button I need to interact with the name selected in the ComboBox.
I have absolutely no idea on how to do that. I do not beg for any code ( altho it will be well received ) I just want the guideline ( do "this" first they you can do "that" and at the end you do "that" ) and I will do all the rest. It is just I can not figure that out. Thank you all !

First get the names of the files that is something like this:
string[] files=Directory.GetFiles("//path");
Now you have an array of all file names in the specific folder given above. Now take this string and populate it to the combo box that is something like this.
foreach(string file in files){
comboBox1.Items.add(file);
}
After that you have to create the event behind the combo box. If you drag-drooped combo box, then you can make its event by going to properties. Then code something like this behind the item select event behind combo box.
protected void combobox(bla bla)
{
if(comboBox1.SelectedItem == "An item")
//Do whatever
//it maybe selectedItem or selectedText or something like this
}
I code roughly so it may contain some errors.

Based on the help given I have done:
public string seltest = null;
string group1 = GroupsDBForm.gone;
string[] tests1 =
Directory.GetFiles("D:\\Riddler\\groups\\" + group1).Select(path => Path.GetFileName(path)).ToArray();
foreach (string t1 in tests1)
{
test_list.Items.Add(group1+"\\"+t1);
}
private void begin_test_btn_Click(object sender, EventArgs e)
{
seltest = "D:\\Riddler\\groups\\" + test_list.Text;
Do_Test_Form DoTest = new Do_Test_Form();
DoTest.ShowPath = seltest;
DoTest.MdiParent = this.ParentForm;
DoTest.Show();
}
( Those are the parts of the project connected to the issue, and because they are connected to other parts is might be lessunderstandeble what are the other names mentioned )
I know it is far from the best code but it works. I post it if this help another person with a close to this issue !
Thank you again Jamil!

Related

Reading a .txt file line by line into multiple text boxes with buttons in a c# windows form

I have got a txt file with 10 lines in it, each line is a record with 5 different fields;
Farrell,Jade,Louise,2011/09/13,F
I am using the commas to split record by FamilyName, FirstName, MiddleName, EnrolmentDate and Gender. I want each field to have its own text box then use buttons to look through the different records.
Everything so far is working under the load button which reads the data from the file and puts it into the text boxes using the code below which works but it only shows the first record so i want a buttons to show the next record, previous record, first and last record and also a button to sort the data from A-Z by the family name. Any help on how to go forward would be great! thanks!
private void Load_BT_Click(object sender, EventArgs e)
{
OpenFileDialog filechooser = new OpenFileDialog();
StreamReader filereader = new StreamReader("StudentFile.txt");
String inputrecord = filereader.ReadLine();
string[] inputfields;
if (inputrecord != null)
{
inputfields = inputrecord.Split(',');
FamName_TXT.Text = inputfields[0];
FirstName_TXT.Text = inputfields[1];
MiddleName_TXT.Text = inputfields[2];
Enrolment_txt.Text = inputfields[3];
Gender_TXT.Text = inputfields[4];
}
else
{
MessageBox.Show("End of File");
}
}
I think there are some design issues here, but i will address your immediate concern. The problem is you only read one line. You need to iterate over all the lines in the textfile. I am assuming you want the load button to load all the data at once.
string[] allRecords = filereader.ReadAllLines();
foreach(string inputRecord in allRecords) {
string[] inputfields = inputRecord.Split(',');
//insert the textbox.Text += inputfields[0] + "\n"; etc
}
if you want a single button to resort the data across all the textboxes.
you really should create a class called Person with properties that correspond to your fields and override compareTo so you can sort by last name or maybe use linq to do the sort for you.
you need a list that will host all of these person objects
from there you can populate the textboxes accordingly
Create a sort button that will reorder the list or create a new list and repopulate the textboxes.
1-3 would be done in the load button. The reason for the person class is because you want all the data you read in from the file to be associate with an object. if you try to do the sorting directly from the textboxes as you seem to be trying to do you will run into issues such as how to make sure the data doesnt get jumbled. It certainly may be possible but it is not an elegant way and would be more work in my mind

How to retrieve each item in a ListBox C#

I am new to C#, although I did take a quarter of Java last year. I have an assignment due tomorrow, so here is my question. I made a sample little program just so I can hopefully get what I'm looking for. I am wondering, how the heck do I look at the listBox and say, for example, if the item soccer is selected, do one thing, but if anything else is selected, do another thing? I will upload a piece of code that doesn't do what its supposed to do, and you all can call me stupid, and then give me the answer.
private void submitButton_Click(object sender, EventArgs e)
{
string best;
best = namesListBox.SelectedItem.ToString();
if ((string)namesListBox.SelectedItem == "Soccer")
{
MessageBox.Show("Fried chicken, don't let that bird die in vain.");
}
else
{
MessageBox.Show("Long long ago, in the land of the Hobbit...");
}
}
private void exitButton_Click(object sender, EventArgs e)
{
Close();
}
}
}
Every time this code runs, I always get Long, long ago.... That is not what I want to see. Any help would be appreciated, I'm about to give up on this program. This is not the actual program, that one is alot more complicated, I just made this one to demonstrate my question... Thanks in advance
Yuriy,
It looks like you are casing the selected item to a string. I have a feeling this may be the problem.
What exactly are you using the string 'best' for? you defined it, but it is not used in your example.
Is this what you are looking for? Try using the ToString() method, and trim it so that whitespace will not throw your code off:
string selectedItem = namesListBox.SelectedItem.ToString().Trim();
if (selectedItem == "Soccer")
MessageBox.Show("Soccer is selected.");
else
MessageBox.Show("NOT SELECTED");
Maybe it is a casing error? If you don't want to worry about uppercase or lowercase, try appending .ToLower() to your string:
string selectedItem = namesListBox.SelectedItem.ToString().Trim().ToLower();
if (selectedItem == "Soccer".ToLower())
// Handle code accordingly.
else
// Handle accordingly.
You can also search your ListBox for a string and find out where it is. Then determine whether the user has selected that particular item:
int selIndex = namesListBox.FindString("Soccer");
This will return a zero-based index of the location of the first item containing the word "Soccer" in it.
Now handle the selected index:
if (namesListBox.SelectedIndex != -1 &&
namesListBox.SelectedIndex == selIndex)
MessageBox.Show("First item containing \"Soccer\" is selected.");
else
MessageBox.Show("First item containing \"Soccer\" is not selected.");
It is also quite possible that you are using a ListView object rather than an actual ListBox. If this is the case, you will have to take a different approach. This example still uses your ListBox name:
// This assumes that you cannot select multiple items, and that you
// only have one column in your ListView.
string selectedItem = namesListBox.SelectedItems[0].SubItems[0].Text;
if (selectedItem.Trim() == "Soccer") // Continue as before...
Does this work with your project?
EDIT:
Wait. Are you trying to change the selected item to "best" before evaluating?
If so, do it like this:
int selIndex = namesListBox.SelectedIndex;
namesListBox.Items.RemoveAt(selIndex);
namesListBox.Items.Insert(selIndex, "best");
EDIT:
Be sure to include code that handles no selection:
// Will not execute block of code if nothing is selected.
if (namesListBox.SelectedIndex == -1)
{
MessageBox.Show("No item is selected.");
return;
}
I am assuming you are using WPF, and you are using ListBox like this :
<ListBox x:Name="lstGames">
<ListBoxItem Content="Soccor"/>
<ListBoxItem Content="Cricket"/>
</ListBox>
Replace this best = namesListBox.SelectedItem.ToString(); with
best = ((ListBoxItem)namesListBox.SelectedItem).Content.ToString();
and accordingly others too.
Because if you are using itemssource property of ListBox and binding say list of only strings, then your present code will work for you surely, if you have checked UpperCase/LowerCase.
If you are using some item like a Game object with multiple properties then your code won't work and more can be said if you tell how you are binding your listbox to a collection object.
The only thing I was looking for was how to write an if statement and this part of the code you wrote worked perfectly. I guess I had whitespace throwing it off, or I was just overthinking it. But anyhow, my issue is resolved. Thank you very much.
string selectedItem = namesListBox.SelectedItem.ToString().Trim();
if (selectedItem == "Soccer")
MessageBox.Show("Soccer is selected.");
else
MessageBox.Show("NOT SELECTED");

Listview Add Items not appearing C#

I'm working on a small program as part of my A Level Computing course that is designed to track orders. It is written in C# using the Windows Forms.
I am having an issue where I enter all the information for a new order and then press OK and it should update the ListView with the information. I have my ListView in Detail view with 4 columns but nothing ever gets added to the ListView. The section of code that should add the items to the ListView is being executed and is not throwing any errors or causing the program to crash but nothing is being added. Its weird because I am using the exact same method that I used in my little prototype mock up but for some reason now it is not working.
All the things I've found on here or on the internet seem to suggest its an issue with the View mode of the ListView and I've tried modifying this property to no avail.
Any ideas why this section of code is refusing to add anything to the ListView?
//Create an array to store the data to be added to the listbox
string[] orderDetails = { Convert.ToString(id + 1), rNameBox.Text, dateBox.Value.ToString(), orderBox.Text };
//DEBUGGING
Console.WriteLine(orderDetails[0]);
Console.WriteLine(orderDetails[1]);
Console.WriteLine(orderDetails[2]);
Console.WriteLine(orderDetails[3]);
//END DEBUGGING
//Add the order info to the ListView item on the main form
var listViewItem = new ListViewItem(orderDetails);
ths.listView1.Items.Add(listViewItem);
If you need any more information just say. Apologies if this is in the wrong format or something this is my first time here.
Your problem is that your ListViewItem contains a string array and it has no useful way of displaying it.
What you should be doing (there are a number of ways of doing this, but here's one) is creating a class, OrderDetail, with an Id, a Name, a Date, and so on. Give it a ToString() method (public override string ToString()) which returns what you want to display, e.g.:
public override string ToString()
{
return this.Name;
}
Create an instance of OrderDetail and set its properties. Create ListViewItem giving it the OrderDetail instance and add to the ListView. Repeat for as many OrderDetail instances you want.
Cheers -
Added: code which works:
int id = 12;
string rNameBoxText = "rName";
DateTime dateBoxValue = DateTime.Now;
string orderBoxText = "order";
string[] orderDetails = { Convert.ToString(id + 1), rNameBoxText, dateBoxValue.ToString(), orderBoxText };
//DEBUGGING
Console.WriteLine(orderDetails[0]);
Console.WriteLine(orderDetails[1]);
Console.WriteLine(orderDetails[2]);
Console.WriteLine(orderDetails[3]);
//END DEBUGGING
this.listView1.Columns.Clear();
this.listView1.Columns.Add("Id");
this.listView1.Columns.Add("rName");
this.listView1.Columns.Add("Date");
this.listView1.Columns.Add("Order");
this.listView1.View = View.Details;
//Add the order info to the ListView item on the main form
var listViewItem = new ListViewItem(orderDetails);
this.listView1.Items.Add(listViewItem);

Disabling dropdown options if already selected

I have a site where people can upload images into a sort of "image mosiac". They can select from a drop down of 36 different positions. Is there a way to disable certain selections from the dropdown if it has already been selected. I don't care if it is grayed out, removed, disabled, or simply having an error message in the error label (which is already there and functioning) saying "please select a different location" (or whatever I decide later).
I just don't want people to select a duplicate location and have the app submit the video. What kind of checking can I put in this?
protected void PopulateImagePosition()
{
String[] imagePositions = video.ListImagePositions();
image_position.Items.Add(new ListItem("----- Please Select -----", ""));
foreach (String tmpPosition in imagePositions)
{
String[] parts = tmpPosition.Split(new char[] { '|' });
image_position.Items.Add(new ListItem(parts[1], parts[0]));
}
}
This is C# .NET. If I need to have additional; code please let me know, any help would be appreciated. Thank in advance!
Got to try stating the obvious
foreach (String tmpPosition in imagePositions)
{
// add logic here to skip if imagePosition has already been selected
// or just don't include it in imagePositions if it has already been selected
String[] parts = tmpPosition.Split(new char[] { '|' });
image_position.Items.Add(new ListItem(parts[1], parts[0]));
}

listview virtual list, e.ItemIndex crashing!

the problem is probably simple, the post is longer than I wished, but I've tried providing as much info and detail as possible.
I didn't write this GUI app, nor designed, however like most of us I've inherited it.
It had a (regular) ListView, actually the app has several ListView(s), not sure if that matters yet.
Because the # of items arriving to this one ListView (screen/form) can get very large 10K+ I decided to convert it to virtual list, however I'm experiencing some early problems.
One of the biggest problems, is that the items are being populated asynchronously by hitting a button on the form.
When they arrive (from service/network/database) the items are built into ListViewItem(s) and added to someListItems which is an ArrayList.
In my RetrieveVirtualItem method I need to handle both cases when the list is empty and when I already have something (after the button was hit) and that's when I hit the wall (no pun intended)
with the following line of code:
if ( someListItems.Count > e.ItemIndex )
It basically causes (no idea why) a call to Dispose method on the main form which results in the entire application crashing hard. BUT!!, it only happens when I click on the form and list. If the form is just loaded and populated it is fine..the second you left click on the mouse, BOOM!
It took my couple of hours to figure out that the line above was the culprit, as the call stack wasn't very apparent to point that out, and another minute to find out that e.ItemIndex is the culprit. But WHY??? I
n msdn examples they access e.ItemIndex to perform tests and it seems fine.
The Virtual Mode is set in the constructor of the form:
myListView.VirtualMode = true;
VirtualListSize is set right after data arrives asynchronously:
myListView.VirtualListSize = someArrayList.Count;
This is my RetrieveVirtualItem implementation:
private void blah_RetrieveVirtualItem( object sender, RetrieveVirtualItemEventArgs e )
{
// someListItems is an ArrayList that is created when the object/class loads..and populated with ListViewItems.
// i.e. private ArrayList someListItems = new ArrayList();
// it is populated asynchronously by hitting a button on the form, hence it's empty when the form loads..
if ( someListItems.Count <= 0 )
{
e.Item = new ListViewItem( "" );
e.Item.SubItems.Add( "" );
e.Item.SubItems.Add( "" );
}
else
{
// the of code below is the problem, and more specifically - e.ItemIndex causes somehow to call Dispose on the main form..
// the reason I have this code is because if I take it out, all items will show up, no problem, but it will crash when I try to scroll down..
// with message like this:
// Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
if ( someListItems.Count > e.ItemIndex )
{
// took out my code out to eliminate possibility that it's my code. :)
int x = e.ItemIndex * e.ItemIndex;
e.Item = new ListViewItem( x.ToString() );
// but I had something like that just for a test:
// ListViewItem item = ( ListViewItem )someListItems[e.ItemIndex];
// e.Item = item;
// remember that someListItems already has ListViewItems
}
}
}
The method that gets called asynchronously, creates ListViewItems and populates someListItems looks something like that:
private void ExampleMethod_That_PopulatesSomeArrayList(ArrayList ar)
{
//Im only showing more essential code..
SomeArrayList.Items.Clear();
myListView.VirtualListSize = ar.Count;
foreach ( SomeObject o in ar )
{
ListViewItem lvi = new ListViewItem( SomeObject.somePropertyID, 0 );
// I've tried changing the above line to: lvi = new ListViewItem( SomeObject.somePropertyID, 0 ); // and having the ListViewItem lvi on the class level. i.e private ListViewItem lvi
// didn't help.. :(
lvi.SubItems.Add( o.someProperty1 );
lvi.SubItems.Add( o.someProperty2 );
// there's quite few of these subitems..2 is enough for this example...
}
// the orignal code, before I changed it to virtual list was adding the items somewhere here..after finished looping, now I'm just trying to reuse that array of ListViewItems.
}
There's also another problem that the items don't really show up at all unless I take out the:
if ( someListItems.Count > e.ItemIndex )
but then I experience the index of out of range issue when I try scrolling.
UPDATE:
I've noticed that if I set the size of virtual list, only after the loop is finished and therefore it is zero (0) at the beginning (I can always reset it to zero), then everything works and don't need to check for size, all I have to do is this:
After the loop in: private void ExampleMethod_That_PopulatesSomeArrayList(ArrayList ar)
this.myListView.VirtualListSize = someListItems.Count;
which I would like to thank for Hans Passant for noticing the discrepancy.
So this is the complete, for now (I'm sure that I'll add some code or change as I would like to add some caching, but at least I have something...
private void blah_RetrieveVirtualItem( object sender, RetrieveVirtualItemEventArgs e )
{
e.Item = ( ListViewItem )someListItems[e.ItemIndex];
}
The only thing I'm not sure what Hans Passant mentioned is this: "it really isn't okay for this event handler to never allocate a ListViewItem. " which I'm not sure if I understand, because the ListViewItems are allocated and inserted into someListItems array. I do have a try catch around, and I did before as well.
Also, I was thinking and I would appreciate someone's input on this idea:
Create a separate object that would hold all the properies of SomeObject or insert SomeObject(s) into the List and create new ListViewItems as required?
e.g:
private void blah_RetrieveVirtualItem( object sender, RetrieveVirtualItemEventArgs e )
{
// that list would be build sometime during the loop iteration in
// (I'm using the original method name mentioned way above in this post)
// ExampleMethod_That_PopulatesSomeArrayList(ArrayList ar)
SomeObject o = listOfObjects[e.ItemIndex];
e.Item = new ListViewItem();
e.Item.SubItems.Add(o.prop1);
e.Item.SubItems.Add(o.prop2);
e.Item.SubItems.Add(o.prop3);
}
To answer this question. The virtual list was crashing because the VirtualListSize wasn't being set correctly.
Basically, to help others here, if you have a virtual list, always make sure that the VirtualListSize corresponds to the actual number of items you're trying to show. If not, all hell breaks loose. If you do update, remove, add, anything, you need to reset VirtualListSize to the correct number.
I ended up deriving from ListView and storing my listviewitems in an array.

Categories