I want to clear listbox everytime when addImages button is clicked which adds new items to it but I am facing problem in clearing it. Following is my code:
private void addImages_Click(object sender, RoutedEventArgs e)
{
FileInfo Images;
string[] filenames = null;
System.Windows.Forms.FolderBrowserDialog folderDlg = new System.Windows.Forms.FolderBrowserDialog();
folderDlg.ShowNewFolderButton = true;
System.Windows.Forms.DialogResult result = folderDlg.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
filenames = System.IO.Directory.GetFiles(folderDlg.SelectedPath);
foreach (string image in filenames)
{
Images = new FileInfo(image);
if(Images.Extension.ToLower() == ".png" || Images.Extension.ToLower() == ".jpg" || Images.Extension.ToLower() == ".gif" || Images.Extension.ToLower() == ".jpeg" || Images.Extension.ToLower() == ".bmp" || Images.Extension.ToLower() == ".tif")
{
ImageList.Items.Add(new LoadImages(new BitmapImage(new Uri(image))));
}
}
}
}
I have tried ImageList.items.clear(), BindingOperations.ClearAllBindings(ImageList) but these removed items first time only when button is clicked next time onwards they don't clear the list. I want list to be cleared everytime when button is clicked.
This code below should work properly. the only thing that might be problematic
private void addImages_Click(object sender, RoutedEventArgs e)
{
ImageList.Items.Clear();
RefreshList();
FileInfo Images;
string[] filenames = null;
System.Windows.Forms.FolderBrowserDialog folderDlg = new System.Windows.Forms.FolderBrowserDialog();
folderDlg.ShowNewFolderButton = true;
System.Windows.Forms.DialogResult result = folderDlg.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
filenames = System.IO.Directory.GetFiles(folderDlg.SelectedPath);
foreach (string image in filenames)
{
Images = new FileInfo(image);
if(new string[]{".png", ".jpg", ".gif", ".jpeg", ".bmp", ".tif"}.Contains(Images.Extension.ToLower()))
{
ImageList.Items.Add(new LoadImages(new BitmapImage(new Uri(image))));
}
}
}
RefreshList();
}
private void RefreshList()
{
// Force visual refresh of control
ImageList.Refresh();
}
*note i cleaned up the extension validation
Edit : I just noticed you talk about Bindings. well you problem is easy then. you cannot clear a list binded to a control. the control will keep original source. You can only UPDATE a binding source otherwise you need to manually update the binding.
Binding on collection is a like a climbing.
Control is the person
Ropes are the DataSource(collection)
Mountain is your model
If in your model you clear (cut) the source (all ropes)
the Control (person) still hold the source (ropes)
If you want the control (person) to have a new source (rope)
You need to add a new one so he can jump on it an remove old ones.
ListBox.Items.Clear should clear the list, if you need that to happen every time the button is clicked then you need it in your event handler i.e.
private void addImages_Click(object sender, RoutedEventArgs e)
{
listBox.Items.Clear();
// do stuff
}
Try this ..
ImageList.Images.Clear();
listBox.Items.Clear();
Related
I''m devoloping a multi tabbed notepad application. How do I perform a save all function on all the tabs on the application without opening a SaveFileDialog after I save the tabs. The method shown below works but it opens a SaveFileDialog for all the tabs.
string strfilename;
RichTextBox rtb = null;
private void saveAllToolStripMenuItem_Click(object sender, EventArgs e)
{
TabControl.TabPageCollection pages = tabControl1.TabPages;
foreach (TabPage page in pages)
{
if (rtb != null)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
rtb.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
}
}
}
I tried it like this as well but only last saved tab gets saved
private void saveAllToolStripMenuItem_Click(object sender, EventArgs e)
{
TabControl.TabPageCollection pages = tabControl1.TabPages;
foreach (TabPage page in pages)
{
rtb = page.Controls[0] as RichTextBox;
if (rtb != null)
{
rtb.SaveFile(strfilename, RichTextBoxStreamType.PlainText);
}
}
}
This is my individual save function
public void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog sv = new SaveFileDialog();
sv.Filter = "Text Document(*.txt)|*.txt|All Files(*.*)|*.*";
if (sv.ShowDialog() == DialogResult.OK)
GetRichTextBox().SaveFile(sv.FileName, RichTextBoxStreamType.PlainText);
this.Text = sv.FileName;
strfilename = sv.FileName;
autosave(sv.FileName);
}
Though this is old,
You can save the file name for the tab with it's Name,
e.g.
Tabpage tb = new TabPage();
RichTextBox rtb = new RichTextBox();
tb.Name = Path.GetFullPath(ofd.FileName); // <--- 'ofd' is the OpenFileDialog
tb.Controls.Add(rtb);
tb.Text = Path.GetFileName(ofd.FileName); // <--- This sets the tab's text to the file's name, rather than the full path.
tabControl1.TabPages.Add(tb);
You can put that snippet of code into the part where you actually open a file.
So, when the user (Or you) presses the Save All button, this snippet of code should be used:
foreach (TabPage tb in tabControl1.TabPages)
{
if (File.Exists(tb.Name))
{
File.WriteAllText(tb.Name, ((RichTextBox)tb.Controls[0]).Text); // <--- You can optionally save the RTF!
}
else if (!File.Exists(tb.Name))
{
saveFileDialog(sender, e);
}
}
saveFileDialog(sender, e) is the Link to your 'Save As' dialog, so that the user may save the individual files that either were deleted and don't exist anymore, or files that never existed all together. (Like if the user presses 'New', and it creates a new tab with a RichTextBox in it, the name would not exist as a file.)
For your 'New Tab' button,
TabPage tb = new TabPage();
RichTextBox rtb = new RichTextBox();
tb.Name = "New.Txt";
tb.Text = "New.Txt";
tb.Controls.Add(rtb);
tabControl1.TabPages.Add(tb);
Optionally, you can create an integer to watch how many 'New.Txt' are created, and instead of it displaying 'New.Txt', it would display 'New*5.Txt' if there were already four tabs before it. (I won't go too far into that.)
If you have any questions, feel free to ask.
I have over 100 checkboxes in my program and I want to save the state of these programatically without creating settings property manualy in visual studio. The checkboxes are bind to a user control including a nummericUpDownBox.
This is how I save it:
//Save Button Click
private void button2_Click(object sender, EventArgs e)
{
Settings.Default.Reset();
foreach (Control c in panel1.Controls)
{
Settings.Default.Properties.Remove(c.Name);
Settings.Default.Properties.Remove(c.Name + "value");
if ((c is checkNum) && Settings.Default.Properties[c.Name] == null)
{
SettingsProperty property = new SettingsProperty(c.Name);
property.DefaultValue = false;
property.IsReadOnly = false;
property.PropertyType = typeof(bool);
property.Provider = Settings.Default.Providers["LocalFileSettingsProvider"];
property.Attributes.Add(typeof(UserScopedSettingAttribute), new UserScopedSettingAttribute());
Settings.Default.Properties.Add(property);
Settings.Default[c.Name] = ((checkNum)c).Checked;
SettingsProperty property2 = new SettingsProperty(c.Name + "value");
property2.DefaultValue = 2;
property2.IsReadOnly = false;
property2.PropertyType = typeof(int);
property2.Provider = Settings.Default.Providers["LocalFileSettingsProvider"];
property2.Attributes.Add(typeof(UserScopedSettingAttribute), new UserScopedSettingAttribute());
Settings.Default.Properties.Add(property2);
Settings.Default[c.Name + "value"] = Convert.ToInt32(((checkNum)c).Value);
}
}
Settings.Default.Save();
}
Now, it is saved, and if I change the Settings again, I can restore the Settings.
But if I close the application It doesnt work. It doesnt save the new Setting when Application is closed an restart.
So how can I save the settings permanently? So that I can load it after restart the application. What do I have to do?
This is how I load the Settings:
//Load Button Click
private void button4_Click(object sender, EventArgs e)
{
foreach (Control c in panel1.Controls)
{
if ((c is checkNum) && Settings.Default.Properties[c.Name] != null)
{
((checkNum)c).Checked = (bool)Settings.Default[c.Name];
((checkNum)c).Value = (int)Settings.Default[c.Name + "value"];
}
}
}
If I got the problem correct, save the Settings into an external file like xml or a simple txt. After starting the Programm, the saved Settings will be read by your program (you must code a restorefunction) and all saved settings are active.
the easiest way is to handle this with a Streamreader.
I'm creating an app which I can select items on combobox to display an image on the screen.
I have 196 png files in /assets/flags/. when I select an item on combobox, the image does not display. There are no errors or exceptions. What am i doing wrong?
private void okBtn_Click(object sender, RoutedEventArgs e)
{
if (myComboBox.SelectedItem.ToString() == "Afghanistan")
{
imageBox.Source =
new BitmapImage(new Uri("ms-appx:///Assets/flags/af.png", UriKind.Absolute));
}
else if (myComboBox.SelectedItem.ToString() == "Danmark")
{
imageBox.Source =
new BitmapImage(new Uri("ms-appx:///Assets/flags/dk.png", UriKind.Absolute));
}
else
{
}
}
You wrote the code inside any Button Click event "okBtn",
Try putting "IF" block inside combobox's default event which is Selection Changed.
Private Sub myComboBox_SelectionChanged(sender As Object, e As Args)
End Sub
well i have solved the problem. the combobox selection must equal to the values and not equal to the strings
if (myComboBox.SelectedIndex == 0)
{
imageBox.Source = new BitmapImage(new Uri("ms-appx:///Assets/flags/af.png", UriKind.Absolute));
}
else if (myComboBox.SelectedIndex == 1)
{
imageBox.Source = new BitmapImage(new Uri("ms-appx:///Assets/flags/dk.png", UriKind.Absolute));
}
This is similar to older posts on this site but I keep getting an error message. I want to create a button in C # WPF that opens a dialogbox and saves a text file to be read at a later date. This code works for windows 32, but crashes on windows 64. How can I change this code to get it to work on both systems? I am a beginner at programming.
Microsoft.Win32.SaveFileDialog saveFile = new Microsoft.Win32.SaveFileDialog(); //throws error message here
private void savebutton_Click(object sender, RoutedEventArgs e)
{
saveFile.FileName = Class1.stringjobnum;
saveFile.Filter = "CCurtain (*.cur)|*.cur";
saveFile.FilterIndex = 2;
saveFile.InitialDirectory = "T:\\Tank Baffle Curtain Calculator\\SavedTanks";
saveFile.OverwritePrompt = true;
bool? result = saveFile.ShowDialog();
if (result.HasValue && result.Value)
{
clsSaveFile.s_FilePath = saveFile.FileName;
int iDotLoc = clsSaveFile.s_FilePath.LastIndexOf('.');
string strExtTest = clsSaveFile.s_FilePath.Substring(iDotLoc);
if (strExtTest != ".cur")
clsSaveFile.s_FilePath += ".cur";
FileInfo sourceFile = new FileInfo(clsSaveFile.s_FilePath);
clsSaveFile.saveFile();
}
}
You're setting an invalid FilterIndex, that might have something to do with it.
There is no 2nd filter in the filter string as written:
"CCurtain (*.cur)|*.cur"
Try setting the FilterIndex to 1 or adding another filter to the string.
You should try adding a catch around the statement to get a better idea as to what is going on.
try
{
code here
}
catch (Exception ex)
{
ex.message contains the info
}
Also, check for null:
bool? result = saveFile.ShowDialog();
if (result != null && (result.HasValue && result.Value))
{
// code
}
I would create the dialogbox IN the event. And you don't have two different filters.
private void savebutton_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.SaveFileDialog saveFile = new Microsoft.Win32.SaveFileDialog();
saveFile.FileName = Class1.stringjobnum;
saveFile.Filter = "CCurtain|*.cur";;
saveFile.FilterIndex = 1;
saveFile.InitialDirectory = "T:\\Tank Baffle Curtain Calculator\\SavedTanks";
saveFile.OverwritePrompt = true;
// Show open file dialog box
Nullable<bool> result = saveFile.ShowDialog();
// Process open file dialog box results
if (result == true)
{
string filename = saveFile.FileName;
// are you sure you need to check the extension.
// if so extension is a a fileinfo property
}
I'd like to have a user select a folder with the FolderBrowserDialog and have the files loaded into the ListView.
My intention is to make a little playlist of sorts so I have to modify a couple of properties of the ListView control I'm assuming. What properties should I set on the control?
How can I achive this?
Surely you just need to do the following:
FolderBrowserDialog folderPicker = new FolderBrowserDialog();
if (folderPicker.ShowDialog() == DialogResult.OK)
{
ListView1.Items.Clear();
string[] files = Directory.GetFiles(folderPicker.SelectedPath);
foreach (string file in files)
{
string fileName = Path.GetFileNameWithoutExtension(file);
ListViewItem item = new ListViewItem(fileName);
item.Tag = file;
ListView1.Items.Add(item);
}
}
Then to get the file out again, do the following on a button press or another event:
if (ListView1.SelectedItems.Count > 0)
{
ListViewItem selected = ListView1.SelectedItems[0];
string selectedFilePath = selected.Tag.ToString();
PlayYourFile(selectedFilePath);
}
else
{
// Show a message
}
For best viewing, set your ListView to Details Mode:
ListView1.View = View.Details;
A basic function could look like this:
public void DisplayFolder ( string folderPath )
{
string[ ] files = System.IO.Directory.GetFiles( folderPath );
for ( int x = 0 ; x < files.Length ; x++ )
{
lvFiles.Items.Add( files[x]);
}
}
List item
private void buttonOK_Click_1(object sender, EventArgs e)
{
DirectoryInfo FileNm = new DirectoryInfo(Application.StartupPath);
var filename = FileNm.GetFiles("CONFIG_*.csv");
//Filename CONFIG_123.csv,CONFIG_abc.csv,etc
foreach(FileInfo f in filename)
listViewFileNames.Items.Add(f.ToString());
}