For each listbox item in variable - c#

somehow i seem to be blind this morning ;)
i have the following code[1] which does read
the object collection out of an ListBox.
with the string b i can "retrieve" the strings
in b there are filenames and directory paths stored
that i want to backup with xcopy code [2].
Code:
private void btnBenutz_Click(object sender, EventArgs e)
{
lblAusgabe2.Text = "";
ListBox.ObjectCollection a = listBox1.Items;
foreach (string x in a)
{
b = x;
lblAusgabe2.Text += "\n" + b;
}
}
More code:
Process.Start("XCOPY.EXE", "/E /I /Y" + b + pfadauswahl + "\\Backup\\" + dt.ToString("yyyy-MM-dd") + "\\UserData\\");
how can i use b as an array which i probably have to ? otherwise only the first item will always been read out? Also the process start i have to use outside of the btnBenutz... so some variable has to be initialized in the public partial class Form2 : Form

Define b as List<string>. You also use a better name like fileNameList:
private List<string> fileNameList; // a class field, not a local variable
Then add the file names to the list:
private void btnBenutz_Click(object sender, EventArgs e)
{
lblAusgabe2.Text = "";
ListBox.ObjectCollection a = listBox1.Items;
foreach (string x in a)
{
fileNames.Add(x);
lblAusgabe2.Text += Environment.NewLine + x; // Why are you doing this?
}
}
Then in another place, run the xopy command for each file:
foreach(string fileName in fileNameList)
{
Process.Start("XCOPY.EXE", "/E /I /Y " + fileName + pfadauswahl + "\\Backup\\" + dt.ToString("yyyy-MM-dd") + "\\UserData\\");
}
if that's what you are trying to achieve!

private void btnBenutz_Click(object sender, EventArgs e)
{
var sb = new StringBuilder();
foreach (string x in listBox1.Items)
{
sb.Append("\n" + x);
}
// then use sb.ToString() somewhere...
}

As you commented you want to call it from other places also like another button click then
Do something like this :
1) Declare list of string at class level
List<string> fileNameList ;
2) Create a function with some meaningfull name let's say StartXcopy like below
public void StartXcopy()
{
ListBox.ObjectCollection a = listBox1.Items;
fileNameList = new List<string>();
foreach (string x in a)
{
fileNameList.Add(x);
lblAusgabe2.Text += "\n" + x;
}
foreach (string filename in fileNameList)
{
System.Diagnostics.Process.Start("XCOPY.EXE", "/E /I /Y" + filename + pfadauswahl + "\\Backup\\" + dt.ToString("yyyy-MM-dd") + "\\UserData\\");
}
}
3) Then call this function from where you want, like below in button click
private void btnBenutz_Click(object sender, EventArgs e)
{
lblAusgabe2.Text = "";
StartXcopy();
}
Note : Here i am assuming you are always iterating through listBox1 items.

Related

Add multiple items into array and display array in textbox

I currently have a form which takes in 3 user inputs from 2 textboxes and 1 numericUpDown.
I want to be able to get the values put in here when a button is clicked, and display the value of all 3 into a seperate text box.
The issue arises when there is multiple additions.
I tried creating an array but it still only displays the last input.
private void AddButton_Click(object sender, EventArgs e)
{
string newItem = NameTextBox.Text + "\t" + QuantityBox.Value.ToString() + "\t" + PriceBox.Text;
List<String> newItemList = new List<string>();
newItemList.Add(newItem);
for(int i = 0; i < newItemList.Count; i++)
{
BasketBox.Text = newItemList[i] + "\n";
}
}
Make your list outside the function, so u can maintain the list of inputs,
and display updated list on every click.
List<String> newItemList = new List<string>();
private void AddButton_Click(object sender, EventArgs e)
{
string newItem = NameTextBox.Text + "\t" + QuantityBox.Value.ToString() + "\t" + PriceBox.Text;
newItemList.Add(newItem);
for(int i = 0; i < newItemList.Count; i++)
{
BasketBox.Text = newItemList[i] + "\n";
}
}
You can do it like this:
private void AddButton_Click(object sender, EventArgs e)
{
string newItem = NameTextBox.Text + "\t" + QuantityBox.Value.ToString() + "\t" + PriceBox.Text;
List<String> newItemList = new List<string>();
newItemList.Add(newItem);
for(int i = 0; i < newItemList.Count; i++)
{
BasketBox.Text += newItemList[i] + "\n"; // this will add the text to your box
}
}
This will 'erase' old text in BasketBox:
BasketBox.Text = newItemList[i] + "\n"
This will add text in BasketBox:
BasketBox.Text += newItemList[i] + "\n"
There is a cool method String.Join which does the concatenation of string items from a list in one blow:
BasketBox.Text = String.Join(Environment.NewLine, newItemList);
If you declare the list outside than each time the button is clicked an item will be added to it and all items will be displayed:
List<String> newItemList = new List<string>();
private void AddButton_Click(object sender, EventArgs e)
{
string newItem = NameTextBox.Text + "\t" + QuantityBox.Value.ToString() + "\t" + PriceBox.Text;
newItemList.Add(newItem);
BasketBox.Text = String.Join(Environment.NewLine, newItemList);
}
Edit:
This of course will only work if you have set the property Multiline to true.

How to take user input from a text box and display using a list C#?

private void addButton_Click(object sender, EventArgs e)
{
List<String> names = new List<String>();
names.Add(textBox1.Text);
names.Add(textBox2.Text);
names.Add(textBox3.Text);
displayTextBox.Text = displayMembers(names);
displayTextBox.Text = string.Join(" ", names);
}
public string displayMembers(List<String> names)
{
foreach (String s in names)
{
return s.ToString();
}
return null;
}
This is what i have so far, but what i need to do is be able to clear the textbox and type in something new and it will display in displayText box as well as what was entered the first time... I am new to programming and cannot figure out how to keep adding to the displaybox. Thanks
I think you are looking for this? I am guessing you want to append whatever is typed in to the displayTextBox control.
BTW, your displayMembers() won't work like you want, it returns the very first element in the enumeration.
The code below will append all the entered names to the DisplayTextBox:
displayTextBox.Text = displayTextBox.Text +
" " + textBox1.Text + " " +textBox2.Text +" "+
textBox3.Text +" "+textBox4.Text;
Alternatively you should store a list of names like this:
declare an instance List variable:
private List<string> _names = new List<string>();
Then instead of changing the text of the displayTextBox simply add the name to the list:
_names.Add(textBox1.Text + " " +textBox2.Text +" "+
textBox3.Text +" "+textBox4.Text);
Then use the list to drive what is displayed in displayTextBox:
displayTextBox.Text = string.Join(" ", _names);
So to wrap it all together, change this:
//instance var
private List<string> _names = new List<string>();
private void addButton_Click(object sender, EventArgs e)
{
_names.Add(textBox1.Text + " " +textBox2.Text +" "+ textBox3.Text +" "+textBox4.Text);
displayTextBox.Text = string.Join(" ", _names);
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}

How to let the program show the words after using dictionary?

I am using Windows Form Application, in the application, there is two rich Textbox and one Button, I want the RichTextbox 2 to display RichTextbox 1 after using the Dictionary.How to do that?What is the code for the Button?
public Form1()
{
InitializeComponent();
Dictionary<char, string> dictionary = new Dictionary<char, string>();
dictionary.Add('a', "%");
dictionary.Add('A'," %");
dictionary.Add('b', " &");
dictionary.Add('B', " &");
dictionary.Add('c', " <");
dictionary.Add('C', " <");
}
private void button_Click(object sender, EventArgs e)
{
second_richtextbox= (???)
}
So that when I type cab it will translate to "<%&"
I want to translate the letter to different symbol.
Here's one way you could do it, using LINQ:
private void button_Click(object sender, EventArgs e)
{
second_richtextbox.Text = string.Join("",
first_richtextbox.Text
.Select(ch =>
dictionary.ContainsKey(ch) ? dictionary[ch] : ch.ToString()));
}
Or a more straightforward way using a loop and StringBuilder (I'd probably do it this way):
var result = new StringBuilder();
for (int i = 0; i < first_richtextbox.Text.Length; i++)
{
if (dictionary.ContainsKey(text[i]))
{
result.Append(dictionary[text[i]]);
}
else
{
result.Append(text[i]);
}
}
second_richtextbox.Text = result.ToString();
Try this code on your Click Event of Button
string frstvalue = richTextBox1.Text;
string finalvalue = "";
char[] a = richTextBox1.Text.ToArray();
foreach (char c in a)
{
if (dictionary.ContainsKey(c))
{
string value = dictionary[c];
finalvalue += value;
}
}
richTextBox2.Text = finalvalue;
I hope it will help

Reading images from a directory and show them on the screen

I can reach with foreach to directory but, because of working like stack, I only reach last picture in the directory. I have lot of image that starting 1.jpg until 100.
namespace deneme_readimg
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DirectoryInfo dir = new DirectoryInfo("C:\\DENEME");
foreach (FileInfo file in dir.GetFiles())
textBox1.Text = file.Name;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
I am unsure what you are asking or what you are trying to achieve, but if you want to see all of the names, you could change the foreach loop into:
foreach (FileInfo file in dir.GetFiles())
textBox1.Text = textBox1.Text + " " + file.Name;
As suggested by #LarsKristensen I'm posting my comment as an answer.
I would use the AppendText method, unless your requirement is to add to the text box on every click I would first make a call to Clear.
namespace deneme_readimg
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DirectoryInfo dir = new DirectoryInfo("C:\\DENEME");
// Clear the contents first
textBox1.Clear();
foreach (FileInfo file in dir.GetFiles())
{
// Append each item
textBox1.AppendText(file.Name);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
Just collect all the data you need to output in StringBuilder;
when ready publish it:
DirectoryInfo dir = new DirectoryInfo("C:\\DENEME");
// Let's collect all the file names in a StringBuilder
// and only then assign them to the textBox.
StringBuilder Sb = new StringBuilder();
foreach (FileInfo file in dir.GetFiles()) {
if (Sb.Length > 0)
Sb.Append(" "); // <- or Sb.AppendLine(); if you want each file printed on a separate line
Sb.Append(file.Name);
}
// One assignment only; it prevents you from flood of "textBox1_TextChanged" calls
textBox1.Text = Sb.ToString();
for displaying just File name. Use a multiline textbox
StringBuilder sb = new StringBuilder();
foreach (FileInfo file in dir.GetFiles())
sb.Append(file.Name + Environment.NewLine);
textBox1.Text =sb.ToString().Trim();
if you want to show images then you need to use some datacontainer like ListBox or DataGridView and add row for each image.

BackgroundWorker & Progressbar Issues c# Visual Studio 2010

Im trying to get my head around backgroundworker and the progressbar, so far i have got it to work but not exactly how i want it to work. Basically i am sorting/renaming folders and copying them to a different location, this works and the code is self explanatory, the output folders generated are as expected. However for each folder i intend to search through i have to right click it to get the number of files and then in the code i have to set the progressBar1.Maximum to that value in order for it to show the coreect progression of the progress bar. How is it possible to get this to set the number of files automatically since it goes through each folder anyway? Some folders have thousands of files and others have millions. beyond this i want to add a label so that it displays the name of the file it is processing along with the progressbar updates.
namespace Data_Sorter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnSelect_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
tbFilePath.Text = folderBrowserDialog1.SelectedPath.ToString();
}
private void btnSort_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int totalFiles = 0;
foreach (var file in Directory.GetFiles(tbFilePath.Text, "*.txt", SearchOption.AllDirectories))
{
backgroundWorker1.ReportProgress(totalFiles);
string fullFilename = file.ToString();
string[] pathParts = fullFilename.Split('\\');
string date = pathParts[6];
string fileName = pathParts[7];
string[] partName = fileName.Split('_');
string point = partName[3];
Directory.CreateDirectory("Data Sorted Logs\\" + point + "\\" + date + "\\");
if (Directory.Exists(("Data Sorted Logs\\" + point + "\\" + date + "\\")))
{
string destPath = (point + "\\" + date + "\\");
File.Copy(fullFilename, "C:\\Documents and Settings\\PC\\Desktop\\Sorter\\Data Sorter\\bin\\Debug\\Data Sorted Logs\\" + destPath + fileName); }
else
{
MessageBox.Show("destination folder not found " + date + point);
}
totalFiles++;
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Done");
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Maximum = 6777; // set this value at the maximum number of files you want to sort //
progressBar1.Value = e.ProgressPercentage;
}
}
You can find out the file number simply reading the GetFiles length.
You can pass the relative percentage using the expression: (i * 100) / totalFiles, in this way it's not necessary to set the Maximum value for the progress.
You can also report the filename to the progressbar passing it as the UserState in the progressChanged event.
Try the code below:
namespace Data_Sorter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnSelect_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
tbFilePath.Text = folderBrowserDialog1.SelectedPath.ToString();
}
private void btnSort_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int totalFiles = 0;
string[] files = Directory.GetFiles(tbFilePath.Text, "*.txt", SearchOption.AllDirectories);
totalFiles = files.Length;
int i = 0;
foreach (var file in files)
{
backgroundWorker1.ReportProgress((i * 100) / totalFiles, file);
i++
string fullFilename = file.ToString();
string[] pathParts = fullFilename.Split('\\');
string date = pathParts[6];
string fileName = pathParts[7];
string[] partName = fileName.Split('_');
string point = partName[3];
Directory.CreateDirectory("Data Sorted Logs\\" + point + "\\" + date + "\\");
if (Directory.Exists(("Data Sorted Logs\\" + point + "\\" + date + "\\")))
{
string destPath = (point + "\\" + date + "\\");
File.Copy(fullFilename, "C:\\Documents and Settings\\PC\\Desktop\\Sorter\\Data Sorter\\bin\\Debug\\Data Sorted Logs\\" + destPath + fileName); }
else
{
MessageBox.Show("destination folder not found " + date + point);
}
totalFiles++;
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Done");
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
progressBar1.Text = e.UserState.ToString();//or yourNewLabel.Text = e.UserState.ToString();
}
}
Move the call to GetFiles up so you can get the length of the array it returns:
string[] files = Directory.GetFiles(tbFilePath.Text, "*.txt",
SearchOption.AllDirectories));
// Note - you won't be able to set this UI property from DoWork
// because of cross-thread issues:
// progressbar1.Maximum = files.Length;
int fileCount = files.Length;
foreach (var file in files ...

Categories

Resources