Creating a new list Item from a string - c#

I have a program with a combo box, a list for that box and a string.
The string is created from user input via a text box and is saved each time the program closes. So if I type "Input Text" then close and open the program the combo box will have a list containing 1 string which displays "Input Text"
The issue is I want to keep adding to the list with new information but at the moment its just constantly overriding what I put in last time.
How do I add to my list with a new item each time the string is different?
private void Form1_Load(object sender, EventArgs e)
{
//Load Settings
saveLocationTextBox.Text = MySettings.Default["SaveSaveLocationText"].ToString();
List<string> list = new List<string>();
list.Add(saveLocationTextBox.Text);
comboBox.DataSource = list;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//Save User Input
MySettings.Default["SaveSaveLocationText"] = saveLocationTextBox.Text;
MySettings.Default.Save();
}

The problem is that you are saving only the selected item text in your settings, not all the items in the combo box.
I suggest to get all the items in the combo first and put them in a comma delimited string.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//Save User Input
string[] itemsToStore = new string[comboBox.Items.Count];
for (int i = 0; i < comboBox.Items.Count; i++)
{
itemsToStore[i] = comboBox.GetItemText(comboBox.Items[i]);
}
MySettings.Default["SaveSaveLocationText"] = saveLocationTextBox.Text;
MySettings.Default["SaveSaveLocationItems"] = string.Join(",", itemsToStore);
MySettings.Default.Save();
}
private void Form1_Load(object sender, EventArgs e)
{
//Load Settings
saveLocationTextBox.Text = MySettings.Default["SaveSaveLocationText"].ToString();
string listItems = MySettings.Default["SaveSaveLocationItems"].ToString();
List<string> list = new List<string>();
list.AddRange(listItems.Split(','));
comboBox.DataSource = list;
}

instead of overriding the text in the file do:
var items = comboBox.Items.Select(item => comboBox.GetItemText(item)).ToList();
items.Add(saveLocationTextBox.Text);
MySettings.Default["SaveSaveLocationText"] = string.Join(";", items);
And then when reading it:
var text = MySettings.Default["SaveSaveLocationText"].ToString();
comboBox.DataSource = text.Split(';').ToList();

Related

C# accept a value more than once from textbox

I need to accept more than one value from the same textbox and store it into an arrya . I need something close to the below code :
string[] countries = new string[3];
private void accept_Click(object sender, EventArgs e)
{
countries[0] = textBox1.Text+" 1 ";
countries[1] = textBox1.Text + " 2 ";
countries[2] = textBox1.Text + " 3 ";
}
private void finish_Click(object sender, EventArgs e)
{
foreach (string coun in countries)
MessageBox.Show("You have entered " + coun);}
}
}
How do you split the different countries?
If you split it on each space you can do it like this:
string[] countries = textBox1.Text.Split(null);
If that is not a good solution maybe try and explain the expected output.
You can simply use a multiline textbox and split the input on newlines:
var countries = countriesTextBox.Text.Split(Environment.NewLine);
Why not just use a list? The following code will add the country's name entered in the textbox to the List<string> every time you click the accept button.
var countries = new List<string>();
private void accept_Click(object sender, EventArgs e)
{
countries.Add(textBox1.Text);
}
private void finish_Click(object sender, EventArgs e)
{
foreach (string coun in countries)
MessageBox.Show("You have entered " + coun);
}
If you want to allow the user to enter multiple countries at once, the following will work if you put a comma in between each country name when entering them into the textbox:
var countries = new List<string>();
private void accept_Click(object sender, EventArgs e)
{
var input = textBox1.Text.Split(',');
countries.AddRange(input);
}
private void finish_Click(object sender, EventArgs e)
{
foreach (string coun in countries)
MessageBox.Show("You have entered " + coun);
}

How To Delete Multiple Items from ListView C# With Delete Button

So, I have a simple ListView that users can add information to and a delete button that is only capable of deleting one selected item at a time. I'm trying to make it so that when multiple items are selected and 'delete' is pressed it deletes those selected items instead of just one. Your help is appreciated!
Add recipient code:
private void addtoRecipients_Click(object sender, EventArgs e)
{
if (recipientEmailBox.Text != "")
{
string[] S = new string[4];
S[0] = recipientEmailBox.Text;
S[1] = recipientNameBox.Text;
S[2] = txtLocation.Text;
S[3] = txtSubject.Text;
ListViewItem I = new ListViewItem(S);
recipientBox.Items.Add(I);
UpdateNoOfEmails();
}
}
My Delete Button Code (only deletes one selection at the moment)
private void deleteEntryBTN_Click(object sender, EventArgs e)
{
try { recipientBox.Items.Remove(recipientBox.SelectedItems[0]); }
catch { }
UpdateNoOfEmails();
}
Clear All Recipients Code
private void clearBTN_Click(object sender, EventArgs e)
{
recipientBox.Items.Clear();
UpdateNoOfEmails();
}
In my case, the simplest way to do it was with a while loop. This is what my new delete button code looks like:
private void deleteEntryBTN_Click(object sender, EventArgs e)
{
try
{
while (recipientBox.SelectedItems.Count > 0)
{
recipientBox.Items.Remove(recipientBox.SelectedItems[0]);
}
}
catch { }
UpdateNoOfEmails();
}

Retrieving value from combo box selected item

I am using Windows Application.I Put some data as direct values in combo box.I defined var type to combo box.I put these combo box on form load.Now I want to retrieve the value of selected item on my button2_click event and I tried below code to retrieve it,but it giving me error of The name comboBox does not exist in current context.Can any one suggest me how to fix it.
namespace WinDataStore
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var daysOfWeek =
new[] { "RED", "GREEN", "BLUE"
};
// Initialize combo box
var comboBox = new ComboBox
{
DataSource = daysOfWeek,
Location = new System.Drawing.Point(180, 140),
Name = "comboBox",
Size = new System.Drawing.Size(166, 21),
DropDownStyle = ComboBoxStyle.DropDownList
};
// Add the combo box to the form.
this.Controls.Add(comboBox);
}
private void button1_Click(object sender, EventArgs e)
{
// Create a new instance of FolderBrowserDialog.
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
// A new folder button will display in FolderBrowserDialog.
folderBrowserDlg.ShowNewFolderButton = true;
//Show FolderBrowserDialog
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
//Show selected folder path in textbox1.
textBox1.Text = folderBrowserDlg.SelectedPath;
//Browsing start from root folder.
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
if (!textBox1.Text.Equals(String.Empty))
{
if (System.IO.Directory.GetFiles(textBox1.Text).Length > 0)
{
foreach (string file in System.IO.Directory.GetFiles(textBox1.Text))
{
//Add file in ListBox.
listBox1.Items.Add(file);
}
}
else
{
// listBox1.Items.Add(String.Format(“No files Found at location:{0}”, textBox1.Text));
}
}
string s = (string)comboBox.SelectedItem;
listBox1.Items.Add(s);
}
}
}
comboBox was local variable in Form1 .ctor. You can't access it from another method
options:
1) access to the control by name
private void button2_Click(object sender, EventArgs e)
{
var comboBox = this.Controls["comboBox"] as ComboBox;
...
}
2) make it a private member of the form as controls normally are, if they are created in designer
ComboBox comboBox;
public Form1()
{
InitializeComponent();
// Initialize combo box
comboBox = new ComboBox() {...};
...
}
Currently the Combobox appears to be a local variable. Try to make it a global field variable and you should be able to access it.

Pass file path from file in listbox to dataconext C#

I am populating a listbox with a file. This can be done by two methods, the open file dialog command initiated by a button press and a drag/drop action into the listbox. I want to pass on the file path (for the file in the listbox) to other areas of my code, for example the DataContext that reads the file in the listbox. Basically I want the file path to automatically update when the listbox is populated. I am new to C# so sorry if I haven't explained myself properly or provided enough information. The code for populating my listbox (named FilePathBox) and the 'Run' button is as follows:
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
var openFileDialog = new Microsoft.Win32.OpenFileDialog();
//openFileDialog.Multiselect = true;
openFileDialog.Filter = "Csv files(*.Csv)|*.Csv|All files(*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (openFileDialog.ShowDialog())
{
FilePathBox.Items.Clear();
foreach (string filename in openFileDialog.FileNames)
{
ListBoxItem selectedFile = new ListBoxItem();
selectedFile.Content = System.IO.Path.GetFileNameWithoutExtension(filename);
selectedFile.ToolTip = filename;
FilePathBox.Items.Add(selectedFile);
}
}
}
private void FilesDropped(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
FilePathBox.Items.Clear();
string[] droppedFilePaths = e.Data.GetData(DataFormats.FileDrop, true) as string[];
foreach (string droppedFilePath in droppedFilePaths)
{
ListBoxItem fileItem = new ListBoxItem();
fileItem.Content = System.IO.Path.GetFileNameWithoutExtension(droppedFilePath);
fileItem.ToolTip = droppedFilePath;
FilePathBox.Items.Add(fileItem);
}
}
}
private void RunButton_Click(object sender, RoutedEventArgs e)
{
DataContext = OldNewService.ReadFile(#"C:\Users\Documents\Lookup Table.csv");
}
I added a comment, but I think what you need a way to get the selected file path when the RunButton is clicked, so just add this to your RunButton_Click method,
private void RunButton_Click(object sender, RoutedEventArgs e)
{
string selection = (string)FilePathBox.SelectedItem;
DataContext = OldNewService.ReadFile(selection);
}

textbox save and show from a .txt file

I have a WinForm of 15 textboxes in a row and each one has a save and show button next to it. The user can write text in these boxes and when they open the form they can click show and view the text they wrote and then save it and close the app and its still there to be shown.
For the code I thought I could use it individually on each textbox and button
namespace UniversityProject
{
public partial class managementsystem : Form
{
private const string fileName = #"C:\txtBoxdata.txt";
public managementsystem()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox3.Text = File.ReadAllText(fileName);
}
private void button2_Click(object sender, EventArgs e)
{
File.WriteAllText(fileName, textBox3.Text);
}
I thought it would work by changing the textBox numbers but I think it might have something to do with the read all. As all the textboxes show the same data which is incorrect.
Let me try to clarify your question:
You have a bunch of textboxes where each represents a single line in a text file. Each time the user clicks on a button next to a textbox you want to replace the corresponding line.
Replacing a single line in a text file is quite easy. Just read all the lines into an array, replace the line and write everything back to the file:
private static void ReplaceLineInFile(string path, int lineNumber, string newLine)
{
if (File.Exists(path))
{
string[] lines = File.ReadAllLines(path);
lines[lineNumber] = newLine;
File.WriteAllLines(path, lines);
}
}
The only thing left is to know which line should be replaced. You can add a handler for each button (notice that the line numbers start with 0):
private void button1_Click(object sender, EventArgs e)
{
ReplaceLineInFile(fileName, 0, textBox1.Text);
}
private void button2_Click(object sender, EventArgs e)
{
ReplaceLineInFile(fileName, 1, textBox2.Text);
}
etc.
This is not very elegant because it duplicates the same code. It would be better to use a single event handler for all buttons and then figure out which textbox it adresses and which line should be replaced. I would recommend to have arrays for the textboxes and buttons and build them in the constructor:
private TextBox[] textBoxes;
private Button[] buttons;
public managementsystem()
{
InitializeComponent();
textBoxes = new TextBox[] { textBox1, textBox2, textBox3, textBox4, textBox5 };
buttons = new Button[] { button1, button2, button3, button4, button5 };
}
Your single event handler would be:
private void button_Click(object sender, EventArgs e)
{
Button button = sender as Button;
if (button != null)
{
int lineNumber = Array.IndexOf(buttons, button);
if (lineNumber >= 0)
{
ReplaceLineInFile(fileName, lineNumber, textBoxes[lineNumber].Text);
}
}
}
At some point you might want to save all values and/or create the file. Also you might want to load existing values into your textboxes when the form is loaded:
private void Form1_Load(object sender, EventArgs e)
{
LoadFile();
}
private void LoadFile()
{
if (!File.Exists(fileName))
{
WriteAllLines();
return;
}
string[] lines = File.ReadAllLines(fileName);
if (lines.Length != textBoxes.Length)
{
// the number of lines in the file doesn't fit so create a new file
WriteAllLines();
return;
}
for (int i = 0; i < lines.Length; i++)
{
textBoxes[i].Text = lines[i];
}
}
private void WriteAllLines()
{
// this will create the file or overwrite an existing one
File.WriteAllLines(fileName, textBoxes.Select(tb => tb.Text));
}
Notice that this will still work when you add new textboxes. The only thing you have to change is the creation of the arrays in the constructor. However, if you change the number of textboxes this will delete the existing file. To avoid this you can add or remove new lines manually.
The basic problem is you are trying to save different textbox values into one txt file. Change the txt file-names along with the textBox names, and you will be good to go .. :)
Get a hold of StreamWriter and StreamReader.
Open a new stream with either stream-writer or reader in your OnClick-events. Then use something like
using(StreamWriter sw = new StreamWriter("C:\\Path\\to\\file.txt")){
sw.WriteLine("TEXTBOX1: " + textbox1.text);
sw.Close();
}
Do this for all your textboxes. And eventually use the StreamReader to read from your file
using(StreamReader sr = new StreamReader("C:\\Path\\to\\file.txt")){
string s = sr.ReadToEnd();
//find value for your textbox;
textbox1.Text = s;
sw.Close();
}
Give it a shot!

Categories