How to keep multiple folder choices? - c#

I have a folder browser button and a combobox which shows selected path. I want it keep previously selected paths. I wrote this code and it works fine. But I wanna know if there is more efficient way to do this.
private void Form1_Load_1(object sender, EventArgs e)
string hurrem, hurrem2, hurrem3, hurrem4, hurrem5;
hurrem = Settings.Default["com1"].ToString();
hurrem2 = Settings.Default["com2"].ToString();
hurrem3 = Settings.Default["com3"].ToString();
hurrem4 = Settings.Default["com4"].ToString();
hurrem5 = Settings.Default["com5"].ToString();
comboBox2.Items.Add(hurrem);
comboBox2.Items.Add(hurrem2);
comboBox2.Items.Add(hurrem3);
comboBox2.Items.Add(hurrem4);
comboBox2.Items.Add(hurrem5);
comboBox2.SelectedIndex = 0;
and
private void button1_Click(object sender, EventArgs e)
{
//..code
Settings.Default["com5"] = Settings.Default["com4"];
Settings.Default["com4"] = Settings.Default["com3"];
Settings.Default["com3"] = Settings.Default["com2"];
Settings.Default["com2"] = Settings.Default["com1"];
Settings.Default["com1"] = path1.ToString();
Settings.Default.Save();

You can use the LimitedStack from here: Limit size of Queue<T> in .NET?. You could then add methods for serializing/deserializing the data using Settings.Default.
public void Save()
{
int i = 0;
foreach (var item in _stack)
{
Settings.Default["com" + i++] = item;
}
Settings.Default.Save();
}
public void Load()
{
for (int i = 0; i < Limit; i++)
{
_stack.Add((T)Settings.Default["com" + i++]);
}
}
Storing the items (assuming you have the limited stack saved in a variable called myStack):
myStack.Push(path1.ToString());
myStack.Save();
Adding the items to the combobox:
for (int i = 0; i < myStack.Limit; i++)
{
comboBox2.Items.Add(myStack.Pop());
}

Related

Adding textbox values to an array not working C#

I'm trying to add textbox and numericUpandDown values to an array, but it doesn't seem to be working.
Carro []carros = new Carro[1];
private Carro carro;
public Form1()
{
..
}
private void Form1_Load(object sender, EventArgs e)
{
..
}
private void AdicionarCarro()
{
this.carro = new Carro(textboxCor.Text, textboxMarca.Text, textboxModelo.Text,
(int.Parse(numUpDownCilindrada.Text)), (int.Parse(numUpDownVelocidade.Text)));
}
private Carro[] AdicionarArray(Carro carro, Carro[] array)
{
AdicionarCarro();
int novoTamanho = array.Length + 1;
Carro[] carros = new Carro[novoTamanho];
for (int i = 0; i < array.Length; i++)
{
carros[i] = array[i];
}
carros[novoTamanho] = carro;
return carros;
}
private void buttonGravar_Click(object sender, EventArgs e)
{
AdicionarArray(carro, carros);
}
When I type the values and click on the "buttonGravar", it gives me this
Error:
I'd be much delighted to get some tips/help on it.
Using System.Collection.Generic.List<T> would be much simpler, since it doesn't have a fixed size:
List<Carro> carros = new List<Carro>();
carros.AddRange(array);
carros.Add(carro);
return carros;
Better way:
private List<Carro> Carros;
public Form1()
{
Carros = new List<Carro>();
..
}
private void Form1_Load(object sender, EventArgs e)
{
..
}
private void AdicionarCarro()
{
var carro = new Carro(textboxCor.Text, textboxMarca.Text, textboxModelo.Text,
(int.Parse(numUpDownCilindrada.Text)), (int.Parse(numUpDownVelocidade.Text)));
Carros.Add(carro);
}
private void buttonGravar_Click(object sender, EventArgs e)
{
AdicionarCarro();
}
To help you understand your code:
carros[novoTamanho] = carro;
should be
carros[novoTamanho - 2] = carro;
Reason:
Array index starts from 0. novoTamanh represents new length (starting at 1, not 0 unlike index), which is outside array.
It's an index out of range exception because your array Carro is of size tmanho:
Carro[] carros = new Carro[novoTamanho];
and carros can contain exactly "novoTamanho" items indexed from "0" to "novoTamanho -1"
You can simply solve this by defining:
int novoTamanho = array.Length + 2;
Or if you do not want to manage indexes, use Lists:
List<Carro> listCarro = new List<Carro>;
listCarro.AddRAnge(array);
listCarro.Add(carro);
return listCarro.ToArray();

accessing form elements from a class

i was trying to make this code:
public void _open_Click_1(object sender, EventArgs e)
{
_playList.Items.Clear();
_openFile.Multiselect = true;
_openFile.Filter = "Mp3 Files|*.mp3|Avi Files|*.avi|Mp4 Files|*.mp4";
_openFile.ShowDialog();
doc = _openFile.SafeFileNames;
path = _openFile.FileNames;
for (int i = 0; i < doc.Length; i++)
{
_playList.Items.Add(doc[i]);
}
}
from a class
so i created a class called mplayer
and then an instance of the form
and put all that code in there
what suppose to happen is when i click a button
file dialog opens
and all selected song names would go into a listbox
for some reason it doesn't open and no compilation nor exception errors pops
please advise
As I can see the event handler is correctly assigned. Btw try this code, it is working in my project:
public Form1()
{
InitializeComponent();
_open.Click += new EventHandler(_open_Click_1);
}
private void _open_Click_1(object sender, EventArgs e)
{
_openFile = new OpenFileDialog();
_playList.Items.Clear();
_openFile.Multiselect = true;
_openFile.Filter = "Mp3 Files|*.mp3|Avi Files|*.avi|Mp4 Files|*.mp4";
_openFile.ShowDialog();
var doc = _openFile.SafeFileNames;
var path = _openFile.FileNames;
for (int i = 0; i < doc.Length; i++)
{
_playList.Items.Add(doc[i]);
}
}
Note: I was using local variables for the selected file names and path.
maybe i wasn't explaining myself very well. im trying to call a class which does that. like this
public static class mplayer
{
public static void openMusic()
{
PhoenixDownloader.searchForm frm = new searchForm();
frm._playlist.items.clear();
frm._openfile.multiselect = true;
frm._openfile.filter = "mp3 files|*.mp3|avi files|*.avi|mp4 files|*.mp4";
frm._openfile.showdialog();
frm.doc = frm._openfile.safefilenames;
frm.path = frm._openfile.filenames;
for (int i = 0; i < frm.doc.length; i++)
{
frm._playlist.items.add(frm.doc[i]);
}
}
}
}
and on the event part:
public void _open_Click_1(object sender, EventArgs e)
{
mplayer();
}
and it it doesn't happen

Updating array of labels from backgroundworkers

I am trying to update an array of Labels which are on a form from a backgroundworker. Here is my code:
for (int i = 0; i < 6; i++)
{
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
arrLabel[i].Text = values[i].ToString();
});
}
else
{
arrLabel[i].Text = values[i].ToString();
}
}
This does not work, but if I try to change text property of each label instead of the array, it works. How can I fix this? Also is there a shorter/better way of updating form controls from backgroundworkers than what I am doing for every single control on my form?
Edit: here is how I defined the array:
private Label[] arrLabel = new Label[6];
and here is the function that I call to assign the array:
private void makeLabelArrays()
{
for (int i = 0; i < 6; i++)
{
arrLabel[i] = (Label)Groupbox1.Controls["label" + (i + 1).ToString()];
}
}
I'm assuming what some of your code looks like; I may be wrong.
You can use the ReportProgress() method to send two pieces of information back to the UI thread - the percentage of completeness (doesn't really apply in your case so I specified 0) and some piece of data (any object you want, just a number in this case).
Then you can get the data in the ProgressChanged event and execute code that touches the UI.
private List<Label> arrLabel = new List<Label>();
private List<string> values = new List<string>();
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var bw = (BackgroundWorker)sender;
for (int i = 0; i < 6; i++)
bw.ReportProgress(0, i);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
var currentIndex = Convert.ToInt32(e.UserState);
arrLabel[currentIndex].Text = values[0].ToString();
}
Make sure you enable reporting progress, as it's disabled by default.
backgroundWorker1.WorkerReportsProgress = true;
try the following
private delegate void delegateAssignText();
public void AssignText()
{
if (this.InvokeRequired)
{
Invoke(new delegateAssignText(AssignText));
return;
}
for (int i = 0; i < 6; i++)
{
arrLabel[i].Text = values[0].ToString();
}
}

Get the index of array of picturebox clicked

I am creating some picturebox dynamically and click event for picturebox as follows
Image myImage = Image.FromFile("image/Untitled6.png");
PictureBox[] txtTeamNames = new PictureBox[5];
for (int i = 0; i < txtTeamNames.Length; i++)
{
var txt = new PictureBox();
txtTeamNames[i] = txt;
txtTeamNames[i].Image = myImage;
txtTeamNames[i].Height = 53;
txtTeamNames[i].Width = 48;
this.panel1.Controls.Add(txtTeamNames[i]);
txtTeamNames[i].Visible = true;
txtTeamNames[i].Click += new EventHandler(this.clcikeventhandle);
}
When someone clicks on any picture box, how do I find its array index and name?
void clickEventHandler(object sender, EventArgs e)
{
//???
}
You can access the PictureBox via the sender argument. So try this:
PictureBox[] txtTeamNames;
void YourMethod()
{
Image myImage = Image.FromFile("image/Untitled6.png");
txtTeamNames = new PictureBox[5];
//The same as your code
}
void clcikeventhandle(object sender, EventArgs e)
{
int index = txtTeamNames.IndexOf(sender As PictureBox);
}
EDIT: Approach #2
But if you are not happy with declaring that array in the class scope you can try this approach:
//Same as your code
for (int i = 0; i < txtTeamNames.Length; i++)
{
//Save as your code
txtTeamNames[i].Tag = i; // ADD THIS LINE
}
Then:
void clcikeventhandle(object sender, EventArgs e)
{
int index = int.Parse((sender as PictureBox).Tag.ToString());
}
Another suggestion - create a custom class, which inherits from PictureBox. It will have an extra Index property. And you can set it between these two lines:
txtTeamNames[i].Visible = true;
//assign the index here
txtTeamNames[i].Click += new EventHandler(this.clcikeventhandle);
like so:
txtTeamNames[i].Index = i;
Then in the handler:
void clickEventHandle(object sender, EventArgs e)
{
PictureBox pbox = sender As PictureBox;
int index = pbox.Index();
string name = pbox.Name();
}
You keep the same scope of variables, which may be useful if you are concerned about it. If you are okay with upgrading scope of txtTeamNames to class level, see another answer by Hossein Narimani Rad.
namespace your_name_project
{
public partial class Form_Begin : Form
{
PictureBox[] pictureBoxs = new PictureBox[6];
public Form_Begin()
{
InitializeComponent();
pictureBoxs[0] = pictureBox1; pictureBoxs[1] = pictureBox2; pictureBoxs[2] = pictureBox3;
pictureBoxs[3] = pictureBox4; pictureBoxs[4] = pictureBox5; pictureBoxs[5] = pictureBox6;
}
//continue
List<PictureBox> pictureBoxes = new List<PictureBox>();
private void buttonX1_Click(object sender, EventArgs e)
{
for (int i = 0; i <3; i++)
{
pictureBoxs[i].Image =your_name_project.Properties.Resources.image_1;// load image1 and Image_2from resource in property of picturebox
}
for (int i = 3; i < 6; i++)
{
pictureBoxs[i].Image = your_name_project.Properties.Resources.Image_2;
}
}
}
}
I've tried the 1st approach cited above, but it did not work for me. I needed to change the syntax in order to work. I am unsure why, but my way for approach 1 to work would be:
PictureBox[] txtTeamNames;
void YourMethod()
{
Image myImage = Image.FromFile("image/Untitled6.png");
txtTeamNames = new PictureBox[5];
//The same as your code
}
void clcikeventhandle(object sender, EventArgs e)
{
int index = Array.IndexOf(txtTeamNames, sender); //DIFFERENT HERE
}
If anyone has an idea...

Delete a set of panels with UserControls created in a loop

I created a panel with a button "add" and a button "delete". If you click on "add" a panel is created right below this header, you can create as much as you want, they are listed.
On each panel there is a checkbox and I would like to delete the panel if the checkbox is checked once the button delete is clicked.
I can get the intuition of a loop : for, but still too novice to get through this without a little tip.
-
public partial class Test_auto : Form
{
ArrayList strategyFutureList = new ArrayList();
public Test_auto()
{
InitializeComponent();
Instance = this;
}
//Create a new future strategy
public void CreateStrategyFuture()
{
ConsoleStrategyItem strategyItemFuture = new ConsoleStrategyItem();
strategyItemFuture.Location = new Point(3, 3);
futureContainer.Height += 85;
strategyFutureList.Add(strategyItemFuture);
futureContainer.Controls.Add(strategyItemFuture);
ConsoleStrategyItem.Instance.txtStrategyName.Text = "Strat Future " + strategyFutureList.IndexOf(strategyItemFuture) + " ";
ConsoleStrategyItem.Instance.Name = "strategyFuture" + strategyFutureList.IndexOf(strategyItemFuture);
ConsoleStrategyItem.Instance.cbxDeleteStrategy.Name = "cbxDeleteFuture" + strategyFutureList.IndexOf(strategyItemFuture);
}
//Makes it appear
private void btnAddStrategyFuture_Click_1(object sender, EventArgs e)
{
CreateStrategyFuture();
}
//Delete a-some selected strategies
public void DeleteStrategyFuture()
{
for (int i = 0; i < strategyFutureList.Count; i++)
{
if (ConsoleStrategyItem.Instance.cbxDeleteStrategy.Checked = true)
{
}
}
}
private void btnDeleteStrategyFuture_Click(object sender, EventArgs e)
{
DeleteStrategyFuture();
}
}
you don't have to create a separate ArrayList to maintain the list of UserControls being added to the futureContainer, you can simply iterate through the Controls collection of it.
simply do this in your DeleteStrategyFuture() method
public void DeleteStrategyFuture()
{
var length=futureContainer.Controls.Count;
foreach(int i=0; i< length; i++)
{
if(futureContainer.Controls[i].GetType()==typeof(ConsoleStrategyItem))
{
bool isChecked =((ConsoleStrategyItem)futureContainer.Controls[i])
.Instance.cbxDeleteStrategy.Checked;
if(isChecked)
{
futureContainers.Controls.Remove(futureContainers.Controls[i]);
}
}
}
}

Categories