First of all, I'm new to C# and .NET development. I was working on a console app and decided to switch to graphical using WPF. Everything was fine with the console app but I'm having troubles right now. So basically, I have this window:
Window 1
When I click on the "Add Task" button, this new window opens: Window 2. I want to perform a sequential series of save tasks (the app is made to copy directories and eventually encrypt them if the users wants to) and in order to do that, I'm saving all the copy parameters in lists of string in a third class where there's a method to run through them and execute copies.
What I want to do is display all the information the user entered in the Window1 in the datagrid, select the save tasks I want to perform and then call the method that copies when I click on the "Launch Save" button but I can't figure how. I can't retrieve the data stored in the lists in the third class with the Window2 from the Window1, it seems even like I can't store multiple save parameters in the lists I made, only one at a time. Tbh idk what to do, I've been searching for hours for a way to do that but I don't find a clue. I'm pretty sure that the way I'm coding is wrong and that I'm missing some logic/reasoning things that are important (or just a lack of knowledge idk) so that's why I came here asking for help.
Here's the code of the window1:
public partial class NewSave : Window
{
SeqSave sqSv1 = new SeqSave();
public NewSave()
{
InitializeComponent();
List<SeqSave> caracSave = new List<SeqSave>();
if (sqSv1.savedNamesList.Count > 0)
{
for (int i = 0; i < sqSv1.savedNamesList.Count; i++)
{
caracSave.Add(new SeqSave() { SaveTaskName = sqSv1.savedNamesList[i], SourcePath = sqSv1.srcPathList[i], DestinationPath = sqSv1.dstPathList[i], SaveType = sqSv1.saveTypeList[i], Backup = sqSv1.didBackupList[i] });
}
saveListsDisplay.ItemsSource = caracSave;
}
}
private void BusinessSoftware(object sender, RoutedEventArgs e)
{
}
private void AddTask(object sender, RoutedEventArgs e)
{
AddTask aT1 = new AddTask();
aT1.Show();
}
private void saveListsDisplay_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void LaunchSave(object sender, RoutedEventArgs e)
{
//for(int i = 0; i < sqSv1.savedNamesList.Count; i++)
//{
// Console.WriteLine(sqSv1.savedNamesList[i] + "\n"
// + sqSv1.srcPathList[i] + "\n"
// + sqSv1.dstPathList[i] + "\n"
// + sqSv1.saveTypeList[i] + "\n"
// + sqSv1.didBackupList[i]);
//}
sqSv1.launchSave();
}
}
And here's the code of the Window2:
public partial class AddTask : Window
{
List<string> listExtension = new List<string>();
SeqSave sqSv1 = new SeqSave();
public AddTask()
{
InitializeComponent();
}
private void GetSourcePath(object sender, RoutedEventArgs e)
{
FolderBrowserDialog sourcePath = new FolderBrowserDialog();
DialogResult result = sourcePath.ShowDialog();
string strSourcePath = sourcePath.SelectedPath;
sqSv1.srcPathList.Add(strSourcePath);
DirectoryInfo dirInfo = new DirectoryInfo(strSourcePath);
foreach (FileInfo f in dirInfo.GetFiles())
{
if (!listExtension.Contains(f.Extension))
{
listExtension.Add(f.Extension);
}
}
for(int i = 0; i < listExtension.Count; i++)
{
lstB1.Items.Add(listExtension[i]);
}
}
private void GetDestinationPath(object sender, RoutedEventArgs e)
{
FolderBrowserDialog destinationPath = new FolderBrowserDialog();
DialogResult result = destinationPath.ShowDialog();
string strDestinationPath = destinationPath.SelectedPath;
sqSv1.dstPathList.Add(strDestinationPath);
}
private void Encrypt(object sender, RoutedEventArgs e)
{
}
private void Return(object sender, RoutedEventArgs e)
{
}
private void Confirm(object sender, RoutedEventArgs e)
{
sqSv1.savedNamesList.Add(taskNameProject.Text);
if (RadioButton1.IsChecked == true)
{
sqSv1.saveTypeList.Add("1");
}
else if(RadioButton2.IsChecked == true)
{
sqSv1.saveTypeList.Add("2");
}
if (Checkbox1.IsChecked == true)
{
sqSv1.didBackupList.Add(true);
}
else
{
sqSv1.didBackupList.Add(false);
}
MessageBox.Show("Task successfully added.");
this.Visibility = Visibility.Hidden;
}
}
You need to create public properties in your second form. I added public to your code like this. I also added dialog results to both forms.
public partial class AddTask : Window
{
public List<string> ListExtension { get; } = new List<string>();
public SeqSave SqSv1 { get; }= new SeqSave();
public AddTask()
{
InitializeComponent();
}
private void GetSourcePath(object sender, RoutedEventArgs e)
{
FolderBrowserDialog sourcePath = new FolderBrowserDialog();
DialogResult result = sourcePath.ShowDialog();
string strSourcePath = sourcePath.SelectedPath;
SqSv1.srcPathList.Add(strSourcePath);
DirectoryInfo dirInfo = new DirectoryInfo(strSourcePath);
foreach (FileInfo f in dirInfo.GetFiles())
{
if (!ListExtension.Contains(f.Extension))
{
ListExtension.Add(f.Extension);
}
}
for(int i = 0; i < ListExtension.Count; i++)
{
lstB1.Items.Add(ListExtension[i]);
}
}
private void GetDestinationPath(object sender, RoutedEventArgs e)
{
FolderBrowserDialog destinationPath = new FolderBrowserDialog();
DialogResult result = destinationPath.ShowDialog();
string strDestinationPath = destinationPath.SelectedPath;
SqSv1.dstPathList.Add(strDestinationPath);
}
private void Encrypt(object sender, RoutedEventArgs e)
{
}
private void Return(object sender, RoutedEventArgs e)
{
}
private void Confirm(object sender, RoutedEventArgs e)
{
SqSv1.savedNamesList.Add(taskNameProject.Text);
if (RadioButton1.IsChecked == true)
{
SqSv1.saveTypeList.Add("1");
}else if(RadioButton2.IsChecked == true)
{
SqSv1.saveTypeList.Add("2");
}
if (Checkbox1.IsChecked == true)
{
SqSv1.didBackupList.Add(true);
}
else
{
SqSv1.didBackupList.Add(false);
}
MessageBox.Show("Task successfully added.");
this.Close();
DialogResult = DialogResult.OK;
}
}
And then access those in the original form like this:
private void AddTask(object sender, RoutedEventArgs e)
{
AddTask aT1 = new AddTask();
DialogResult results = aT1.ShowDialog();
if(results == DialogResult.OK)
{
List<string> listExt = aT1.ListExtension;
}
}
Related
This is the code that I used for the music player:
public partial class MusicPlayer : Form
{
public MusicPlayer()
{
InitializeComponent();
}
String[] paths, files;
private void BtnSelectSongs_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = true;
if(ofd.ShowDialog()== System.Windows.Forms.DialogResult.OK)
{
paths = ofd.FileNames;
files = ofd.FileNames;
for (int i = 0; i < files.Length; i++)
{
ListBoxSongs.Items.Add(files[i]);
}
}
}
private void ListBoxSongs_SelectedIndexChanged(object sender, EventArgs e)
{
WindowsMusic.URL = paths[ListBoxSongs.SelectedIndex];
}
private void pictureBox1_Click(object sender, EventArgs e)
{
this.Close();
}
}
Try to use List<string>
var songslist = new List<string>();
public void SearchMusic(string music)
{
if (songslist.Contains(music))
string searchresult = songslist.ElementAt(songslist.IndexOf(music));
}
I have a List of Objects. What I want to do:
Build a Dialog Box which shows a Radio Button for each element in the given List and returning the selected element/value by clicking on OK-Button.
Thanks in Advance.
Here is a quick example of creating your own form and getting a value from it.
Form1.cs:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
frmTest frmTest = new frmTest();
DialogResult dr = frmTest.ShowDialog();
if(dr == System.Windows.Forms.DialogResult.OK)
{
string value = frmTest.GetValue();
MessageBox.Show(value);
}
}
}
Form1 View:
public partial class frmTest : Form
{
private string _value { get; set; }
public frmTest()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
private void radioButton_CheckedChanged(object sender, EventArgs e)
{
RadioButton radioButton = (RadioButton)sender;
this._value = radioButton.Text; // Assign the radio button text as value Ex: AAA
}
public string GetValue()
{
return this._value;
}
}
You have to make sure that all radio buttons are using radioButton_CheckedChanged for the CheckedChanged event.
Form2 View:
Output:
build your own form and add a public variable "a string for example" called "Result"
public partial class YourDialog:Form
{
public string Result = "";
public YourDialog()
{// add all the controls you need with the necessary handlers
//add the OK button with an "On Click handler"
}
private void OK_Button_Click(object sender, EventArgs e)
{
//set the Result value according to your controls
this.hide();// will explain in the main form
}
}
// in your main form
private string GetUserResult()
{
YourDialog NewDialog = new YourDialog();
NewDialog.ShowDialog();//that's why you only have to hide it and not close it before getting the result
string Result = NewDialog.Result;
NewDialog.Close();
return Result;
}
OOps! I came back just to see there are already 2 answers! How ever, I want to post my version, which can build controls according to list of strings:
//dialog form
public partial class frmDialogcs : Form
{
public string selectedString;
//keep default constructor or not is fine
public frmDialogcs()
{
InitializeComponent();
}
public frmDialogcs(IList<string> lst)
{
InitializeComponent();
for (int i = 0; i < lst.Count; i++)
{
RadioButton rdb = new RadioButton();
rdb.Text = lst[i];
rdb.Size = new Size(100, 30);
this.Controls.Add(rdb);
rdb.Location = new Point(20, 20 + 35 * i);
rdb.CheckedChanged += (s, ee) =>
{
var r = s as RadioButton;
if (r.Checked)
this.selectedString = r.Text;
};
}
}
private void btnOK_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
}
}
//in main form
private void button1_Click(object sender, EventArgs e)
{
var lst = new List<string>() { "a", "b", "c" };
frmDialogcs dlg = new frmDialogcs(lst);
if (dlg.ShowDialog() == DialogResult.OK)
{
string selected = dlg.selectedString;
MessageBox.Show(selected);
}
}
I have the following C# code in my winform application:
FormPrincipale
private void butFornitore_Click(object sender, EventArgs e)
{
try
{
FormFornitore Dialog = new FormFornitore();
Dialog.ShowDialog();
}
catch(Exception excDial)
{
MessageBox.Show("DIALOG: " + excDial.Message);
}
}
public void getFornitore(string Codice, string Descrizione)
{
this.txtFornitore.Text = Descrizione;
Fornitore = Codice;
}
FormFornitore
private void gridFornitori_DoubleClick(object sender, EventArgs e)
{
try
{
var Codice = gridView2.GetFocusedDataRow()["codconto"].ToString();
var RagSoc = gridView2.GetFocusedDataRow()["dscconto1"].ToString();
FormPrincipale Form = new FormPrincipale();
Form.getFornitore(Codice, RagSoc);
this.Close();
}
catch(Exception excGrid)
{
MessageBox.Show("GRID: " + excGrid.Message);
}
}
The code works (i used breakpoints to check if code was executed) but the Text property of the TextBox doesn't change. I put Modifiers TextBox property on Public, so this is ok too. I'm using Dev Express Grid Control, but i don't think this is the problem. Thank's for help.
To pass the instance of your parent form, you could do something like this:
class FormFornitore: Form
{
protected FormPrincipale parent;
FormFornitore(FormPrincipale parent)
{
this.parent = parent;
}
private void gridFornitori_DoubleClick(object sender, EventArgs e)
{
try
{
var Codice = gridView2.GetFocusedDataRow()["codconto"].ToString();
var RagSoc = gridView2.GetFocusedDataRow()["dscconto1"].ToString();
/// REMOVE THIS FormPrincipale Form = new FormPrincipale();
parent.getFornitore(Codice, RagSoc);
this.Close();
}
catch(Exception excGrid)
{
MessageBox.Show("GRID: " + excGrid.Message);
}
}
}
Then in your "FormPricipale" use it like this
private void butFornitore_Click(object sender, EventArgs e)
{
try
{
FormFornitore Dialog = new FormFornitore(this); // Notice the argument
Dialog.ShowDialog();
}
catch(Exception excDial)
{
MessageBox.Show("DIALOG: " + excDial.Message);
}
}
public void getFornitore(string Codice, string Descrizione)
{
this.txtFornitore.Text = Descrizione;
Fornitore = Codice;
}
So, I got kind of stuck over my head while I tried to program something new.
I'm trying to add objectBeer_pluche or objectBeer_Elektro to my OBJberenlijst on the Beren Main form from the details Form, so I can add both instances of 2 classes to the same list.
I'm not even sure this is possible by the way. So, I would like feedback if what I am trying to do is possible to start with. I already figured VOID is not right but I am really clueless here.
This is my main beren.cs form with an OBJberenlist, that's where I try to add objectBeer_pluche or objectBeer_Elektro into it:
public partial class Beren : Form
{
public interface Berenlijst { }
public List<Berenlijst> OBJberenLijst = new List<Berenlijst>();
public Beren()
{
InitializeComponent();
}
private void Beren_Load(object sender, EventArgs e)
{
}
private void BTNToevoegen_Click(object sender, EventArgs e)
{
this.Hide();
Details Details = new Details();
if (Details.ShowDialog(this) == DialogResult.OK)
{
OBJberenLijst.Add(Details.getdetails());
}
Details.Close();
Details.Dispose();
}
public void LijstLaden()
{
foreach(Beer berenobject in OBJberenLijst)
{
LST_beren.Items.Add(berenobject.Naam);
}
}
}
}
from this form called details.cs
public partial class Details : Form
{
public Details()
{
InitializeComponent();
BTN_toevoegen.DialogResult = DialogResult.OK;
BTN_cancel.DialogResult = DialogResult.Cancel;
}
private void Details_Load(object sender, EventArgs e)
{
RDB_pluche.Checked = true;
BTN_ok.Enabled = false;
}
private void RDB_pluche_CheckedChanged(object sender, EventArgs e)
{
PANEL_pluche.Visible = true;
PANEL_elektro.Visible = false;
}
private void RDB_elektro_CheckedChanged(object sender, EventArgs e)
{
PANEL_pluche.Visible = false;
PANEL_elektro.Visible = true;
}
private void BTN_toevoegen_Click(object sender, EventArgs e)
{
open_foto.Filter = "jpg (*.jpg)|*.jpg|bmp(*.bmp)|*.bmp|png(*.png)|*.png";
if (open_foto.ShowDialog() == System.Windows.Forms.DialogResult.OK && open_foto.FileName.Length > 0)
{
TXT_adres.Text = open_foto.FileName;
PIC_beer.Image = Image.FromFile(open_foto.FileName);
}
}
private void BTN_ok_Click(object sender, EventArgs e)
{
}
public void getdetails()
{
if (RDB_pluche.Enabled == true)
{
Pluche_Beer objectBeer_pluche = new Pluche_Beer(TXTNaam_pluche.Text, open_foto.FileName, "(Wasprogramma: " + TXT_wasprogramma.ToString() + " Graden Celsius");
}
else
{
Elektronische_Beer objectBeer_Elektro = new Elektronische_Beer(TXTNaam_elekro.Text, open_foto.FileName, "aantal Batterijen: " + CMBOBatterijen.ToString());
}
}
private void Details_MouseMove(object sender, MouseEventArgs e)
{
foreach (Control c in this.Controls)
{
if (c is TextBox)
{
TextBox textBox = c as TextBox;
if (textBox.Text != string.Empty)
{
BTN_ok.Enabled = true;
}
}
}
}
}
}
The problem is between this line...
OBJberenLijst.Add(Details.getdetails());
...and this line.
public void getdetails()
List.Add() requires an object to add, but getdetails() returns void. You probably want to change getdetails() to something like the following:
public Berenlijst getdetails()
{
if (RDB_pluche.Enabled == true)
{
return new Pluche_Beer(TXTNaam_pluche.Text, open_foto.FileName, "(Wasprogramma: " + TXT_wasprogramma.ToString() + " Graden Celsius");
}
return new Elektronische_Beer(TXTNaam_elekro.Text, open_foto.FileName, "aantal Batterijen: " + CMBOBatterijen.ToString());
}
Hopefully Pluche_Beer and Elektronisch_Beer inherent from Berenlijst. Otherwise you'll have to revise your logic in a broader way.
I am using c# Windows Form Application and ftpWebRequest, I am doing a directory listing. I have a listbox that will display folders, by using the event DoubleClick in my listbox, the double clicked folder or item in my listbox will show its content. And now my problem is I don't know how to go back to the previous directory by using back button.
Here is my Code File:
namespace myFTPClass
{
public class myFTP
{
public string user;
public string pass;
public delegate void cThread1(string thread1);
public event EventHandler EH;
public List<string> myDIR = new List<string>();
public void getDirectoryList(string getDirectory)
{
try
{
FtpWebRequest fwr = FtpWebRequest.Create(getDirectory) as FtpWebRequest;
fwr.Credentials = new NetworkCredential(user, pass);
fwr.UseBinary = true;
fwr.UsePassive = true;
fwr.KeepAlive = true;
fwr.Method = WebRequestMethods.Ftp.ListDirectory;
StreamReader sr = new StreamReader(fwr.GetResponse().GetResponseStream());
while (!sr.EndOfStream)
{
myDIR.Add(sr.ReadLine());
}
}
catch(Exception we)
{
myDIR.Clear();
string msg = we.Message;
}
}
void myCallBackMethod(IAsyncResult ar)
{
cThread1 myThread = (cThread1)((System.Runtime.Remoting.Messaging.AsyncResult)ar).AsyncDelegate;
myThread.EndInvoke(ar);
if (EH != null) EH(this, null);
}
public void Async_getDirectoryList(string dir)
{
AsyncCallback ac = new AsyncCallback(myCallBackMethod);
cThread1 myThread = new cThread1(getDirectoryList);
myThread.BeginInvoke(dir, ac, null);
}
}
}
And Here is my Form1:
namespace my_ftp_v0._01
{
public partial class Form1 : Form
{
myFTP ftp = new myFTP();
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
btn_connect.Click += new EventHandler(btn_connect_Click);
listBox1.DoubleClick += new EventHandler(listBox1_DoubleClick);
btn_back.Click += new EventHandler(btn_back_Click);
ftp.EH += new EventHandler(ftp_EH);
}
void btn_back_Click(object sender, EventArgs e)
{
}
void listBox1_DoubleClick(object sender, EventArgs e)
{
string forward = "ftp://127.0.0.1/" + listBox1.SelectedItem.ToString();
listBox1.Items.Clear();
ftp.myDIR.Clear();
ftp.Async_getDirectoryList(forward);
}
void Form1_Load(object sender, EventArgs e)
{
txt_dir.Text = "ftp://127.0.0.1/";
txt_pass.PasswordChar = '‡';
}
void ftp_EH(object sender, EventArgs e)
{
if (InvokeRequired)
{
EventHandler eh = new EventHandler(ftp_EH);
this.Invoke(eh, new object[] { sender, e });
return;
}
for (int i = 0; i < ftp.myDIR.Count; i++)
{
listBox1.Items.Add(ftp.myDIR[i]);
}
}
void btn_connect_Click(object sender, EventArgs e)
{
ftp.Async_getDirectoryList(txt_dir.Text);
ftp.user = txt_user.Text;
ftp.pass = txt_pass.Text;
}
}
}
Move your SetDirectoryList to its own method
Add a Stack object to your class to track your requests
When the user double clicks add the request to the stack and then set the directory.
When the user hits the back
button, check if the stack has a request, if it does, pop it off and
call the set directory method.
Something like this...
public partial class Form1 : Form
{
myFTP ftp = new myFTP();
Stack _requestStack = new Stack();//Stack to store requests
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
btn_connect.Click += new EventHandler(btn_connect_Click);
listBox1.DoubleClick += new EventHandler(listBox1_DoubleClick);
btn_back.Click += new EventHandler(btn_back_Click);
ftp.EH += new EventHandler(ftp_EH);
}
void btn_back_Click(object sender, EventArgs e)
{
if(_requestStack.Count > 0)
{
string directoryPath = (string)_requestStack.Pop();
SetDirectoryList(directoryPath);
}
}
void listBox1_DoubleClick(object sender, EventArgs e)
{
string directoryPath = listBox1.SelectedItem.ToString();
_stack.Push(directoryPath);
SetDirectoryList(directoryPath);
}
void SetDirectoryList(string directoryPath)
{
string forward = "ftp://127.0.0.1/" + directoryPath;
listBox1.Items.Clear();
ftp.myDIR.Clear();
ftp.Async_getDirectoryList(forward);
}
void btn_back_Click(object sender, EventArgs e)
{
create.server = create.server.TrimEnd('/');
create.server = create.server.Remove(create.server.LastIndexOf('/')+1);
listBox1.Items.Clear();
ftp.myDIR.Clear();
ftp.Async_getDirectoryList("");
}
I've already done this code to my back button and it works properly.