Disabling dropdown options if already selected - c#

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

Related

Search for word in ListBox written on InputBox (C# VS)

I have a ListBox with words and I need to click a button that opens an InputBox where I can search for a word and the program will run the ListBox and highlight the word I wrote in the InputBox if it's there. If the program reaches the end of the list and doesn't find the word then I'll get a MessageBox saying the word I'm looking for isn't there. I need to use some sort of cycle for this program.
I know how to make the button, InputBox and the error MessageBox, but I don't know how to do the searching and cycle.
I've read a lot of similar questions here but I don't think any of them return the result I'm looking for.
Can anyone help me? Or redirect me to a post with the answer?
This is for Winforms.
That should get you on track, it's pretty much self-explanative:
whenever text changes
find matching items in list
select them
Code:
private void textBox1_TextChanged(object sender, EventArgs e)
{
var textBox = sender as TextBox ?? throw new InvalidOperationException();
var text = textBox.Text;
if (string.IsNullOrWhiteSpace(text))
return; // nothing to search for
const StringComparison comparison = StringComparison.InvariantCultureIgnoreCase; // maybe change this
// find items matching text
var indices = new List<int>();
for (var i = 0; i < listBox1.Items.Count; i++)
{
var item = listBox1.Items[i];
if (string.Equals(item?.ToString(), text, comparison))
indices.Add(i);
}
// select them in list
if (!indices.Any())
return;
listBox1.SelectedIndices.Clear();
foreach (var index in indices)
listBox1.SelectedIndices.Add(index);
}
Of course, list selection mode has to be multiple for it to work properly.
Also, you will need to clear selection if there are no matches so as to not leave the UI in an ambiguous state (not done).

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!

Replacing listBox items during repopulation

I'm building a contact manager program and I have a button that when pressed, updates a listBox of names. Unfortunately, I'm expecting my user to not always be putting the names in before closing the program. I have decided to make new contacts in the list appear as random numbers before a name is entered, so some of my items will be numbers and some will be names. I can't seem to get the names to show up, though. I've been storing the names as strings inside of text files contained inside folders of unique random numbers. What I want is to be able to load all the folder names into the list, then check to see if a name is associated with the item, and if it is, replace the number with the respective name. The following code is as far as I have gotten before I got stumped.
private void button5_Click(object sender, EventArgs e)
{
//populate the list of people
listBox1.Items.Clear();
string[] dirs = Directory.GetDirectories(#"C:\PersonalManager\");
foreach (string dir in dirs)
{
//replace numbered items with names
for (int i = 0; i < listBox1.Items.Count; i++)
{
String Text = Convert.ToString(listBox1.Items[i]);
Text = Text.Replace(File.ReadAllText(#"C:\PersonalManager\"+listBox1.Items[i]+#"\first.txt")); //first.txt is the file containing the name
listBox1.Items[i] = Text;
}
listBox1.Items.Add(Path.GetFileName(dir));
}
}
I'm also pretty sure there is an overload bug in there somewhere, as Visual Studio refuses to compile it. Maybe I should go about this in a different way? What would any of you suggest? I have searched all through Google, and Bing but have yet to figure out what I'm doing wrong. Sorry if my code is a mess, it's my first time.
P.S. I'm a beginner, so I can't wrap my head around too much code without comments every now and then.
I'm pretty sure that this line is breaking your code:
Text = Text.Replace(File.ReadAllText(#"C:\PersonalManager\"+listBox1.Items[i]+#"\first.txt"));
The string.Replace does not have a overload with just one parameter. It has always two.
Just to give you a starting point:
private void button5_Click(object sender, EventArgs e)
{
//populate the list of people
listBox1.Items.Clear();
string[] dirs = Directory.GetDirectories(#"C:\PersonalManager\");
foreach (string dir in dirs)
{
var filePathToRead = Path.Combine(dir, "first.txt");
var allTextOfTheFile = File.ReadAllText(filePathToRead);
// now you can work with the content of the file
listBox1.Items.Add(Path.GetFileName(dir));
}
}

Combobox crashes when selecting item with keyboard

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..

Categories