Combobox crashes when selecting item with keyboard - c#

I have a problem with the code below, basically what is does is read from a path where files with extension .config are stored, it reads the names of the files without extension and displays them all in a combobox. That works fine and if you click on the down arrow and select a name it actually does what it's supposed to, however, once I have selected an item from the dropdown with the mouse and I go back and start typing inside the combobox my application crashes throwing a exception.
I've tried adding a try-catch-finally but it keeps throwing the same error. Could it be the loop that is causing my application to crash once I start typing in the combobox?
p.d. If I just use the mouse to select an item from the dropdown menu my application works fine but once I've selected an item with the mouse and use the keyboard to type another item name inside the combobox my app crashes. Any pointers would be helpful.
// Gets all the file names from the path assigned to templatePath
// and assigns it to the string array fname
string[] fname = Directory.GetFiles(templatePath);
// Begin sorting through the file names assigned to the string array fname
foreach (string file in fname)
{
// Remove the extension from the file names and compare the list with
// the dropdown selected item
if (System.IO.Path.GetFileNameWithoutExtension(file) == cbTemplates.SelectedItem.ToString())
{
// StreamReader gets the contents from the found file and assigns
// them to the labels
using (var obj = new StreamReader(File.OpenRead(file)))
{
lbl1.Content = obj.ReadLine();
lbl2.Content = obj.ReadLine();
lbl3.Content = obj.ReadLine();
lbl4.Content = obj.ReadLine();
lbl5.Content = obj.ReadLine();
lbl6.Content = obj.ReadLine();
lbl7.Content = obj.ReadLine();
lbl8.Content = obj.ReadLine();
lbl9.Content = obj.ReadLine();
lbl10.Content = obj.ReadLine();
obj.Dispose();
}
}
}

My guess is this is probably causing the error:
cbTemplates.SelectedItem.ToString()
When you start typing in the combobox, the SelectedItem becomes null.
You should test whether the cbTemplates.SelectedItem is null before attempting to invoke ToString() on it. And if you're trying to match on the text of the combo-box, you might try using cbTemplates.Text instead.
And as others commented on your question, you don't need to call Dispose inside using and you should consider the possibility that the file might not contain 10 lines..

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

Populating ComboBox with some data and then reading the selected row

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!

Strip leading characters from a directory path in a listbox in C#

So i am attempting to teach myself C#, I have a program that I originally wrote in batch and am attempting to recreate in C# using WPF. I have a button that allows a user to set a directory, that directory selected is then displayed in a text box above a listbox which adds every subfolder, only first level, to the listbox. Now all this works fine but it writes out the entire directory path in the listbox. I have been trying to figure out how to strip the leading directory path off the list box entries for over an hour to no avail. Here is what I have so far:
private void btn_SetDirectory_Click(object sender, RoutedEventArgs e)
{
//Create a folder browser dialog and set the selected path to "steamPath"
var steamPath = new FolderBrowserDialog();
DialogResult result = steamPath.ShowDialog();
//Update the text box to reflect the selected folder path
txt_SteamDirectory.Text = steamPath.SelectedPath;
//Clear and update the list box after choosing a folder
lb_FromFolder.Items.Clear();
string folderName = steamPath.SelectedPath;
foreach (string f in Directory.GetDirectories(folderName))
{
lb_FromFolder.Items.Add(f);
}
}
Now I tried changing the last line to this, and it did not work it just crashed the program:
foreach (string f in Directory.GetDirectories(folderName))
{
lb_FromFolder.Items.Add(f.Substring(f.LastIndexOf("'\'")));
}
I am fairly certain that the LastIndexOf route is probably the right one but I am at a dead end. I apologize if this is a dumb question but this is my first attempt at using C#. Thanks in advance.
This can solve your issue
string folderName = steamPath.SelectedPath;
foreach (string f in Directory.GetDirectories(folderName))
{
// string[] strArr = f.Split('\\');
lb_FromFolder.Items.Add(f.Split('\\')[f.Split('\\').Length-1]);
}
You can use this code:
string folderName = steamPath.SelectedPath;
foreach (string f in Directory.GetDirectories(folderName))
{
lb_FromFolder.Items.Add(f.Remove(0,folderName.Length));
}

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

C# Text box remaining empty

I'm calling a public method from another class. It takes in a List as a parameter, and goes through the list printing out each item into a text field. The problem is the text field is remaining empty!. I've checked that the list is populated by outputing the item to the console before I put it into the text box, and the text is coming up fine there.
The list contains strings, and should output each string to the textfield followed by a semi colon.
This is the method which is being called:
public void fillAttachment(List<string> attachList)
{
for (int i = 0; i < attachList.Count; i++)
{
Console.WriteLine("List: " + attachList[i]);
txtAttach.Text += attachList[i] + ";";
}
}
I would solve it in this way:
foreach(var attach in attachList)
{
Console.WriteLine(attach);
txtAttach.AppendText(string.Format("{0};", attach));
}
Setting the text property on a text box and it not displaying could be one of the following:
You are not looking at the same control as you are setting the text in
Could you have instantiated a second copy of the form object and it is this form that you are setting the txtAttach text property in?
Could the control that you are expecting to be populated be a different one? Right click the text box that you want the text to appear in click properties and check the name.
Something else is clearing the textbox after you set it
Right click the txtAttach.Text and click Find All References, this will show you all the places that the Text property is referenced - written and read - in your project. This is a very useful way to locate other interaction with this control.
Fomatting is making the text box appear empty
Is the Font too small, or in the same colour as the background. Can you select the text in the text box?
The easiest way to test all of the above is to create a new text control on your form with a different name, change your code to populate it, check that it is indeed populated, then replace the old one.
As an aside, you could also reduce the code with a single line as follows:
public void fillAttachment(List<string> attachList)
{
txtAttach.Text = String.Join(";", attachList.ToArray());
}
Although this obviously skips out the console write line function.
Not sure why yours doesn't work but I would have done it like this...
public void fillAttachment(List<string> attachList)
{
string result = "";
//OR (if you want to append to existing textbox data)
//string result = txtAttach.Text;
for (int i = 0; i < attachList.Count; i++)
{
Console.WriteLine("List: " + attachList[i]);
result += attachList[i] + ";";
}
txtAttach.Text = result;
}
Does that work for you? If not then there is something else very wrong that is not obvious from your code

Categories