Google Suggestish text box (autocomplete) - c#

What would be the best way to develop a text box that remembers the last x number of entries that were put into it. This is a standalone app written with C#.

This is actually fairly easy, especially in terms of showing the "AutoComplete" part of it. In terms of remembering the last x number of entries, you are just going to have to decide on a particular event (or events) that you consider as an entry being completed and write that entry off to a list... an AutoCompleteStringCollection to be precise.
The TextBox class has the 3 following properties that you will need:
AutoCompleteCustomSource
AutoCompleteMode
AutoCompleteSource
Set AutoCompleteMode to SuggestAppend and AutoCompleteSource to CustomSource.
Then at runtime, every time a new entry is made, use the Add() method of AutoCompleteStringCollection to add that entry to the list (and pop off any old ones if you want). You can actually do this operation directly on the AutoCompleteCustomSource property of the TextBox as long as you've already initialized it.
Now, every time you type in the TextBox it will suggest previous entries :)
See this article for a more complete example: http://www.c-sharpcorner.com/UploadFile/mahesh/AutoCompletion02012006113508AM/AutoCompletion.aspx
AutoComplete also has some built in features like FileSystem and URLs (though it only does stuff that was typed into IE...)

#Ethan
I forgot about the fact that you would want to save that so it wasn't a per session only thing :P But yes, you are completely correct.
This is easily done, especially since it's just basic strings, just write out the contents of AutoCompleteCustomSource from the TextBox to a text file, on separate lines.
I had a few minutes, so I wrote up a complete code example...I would've before as I always try to show code, but didn't have time. Anyway, here's the whole thing (minus the designer code).
namespace AutoComplete
{
public partial class Main : Form
{
//so you don't have to address "txtMain.AutoCompleteCustomSource" every time
AutoCompleteStringCollection acsc;
public Main()
{
InitializeComponent();
//Set to use a Custom source
txtMain.AutoCompleteSource = AutoCompleteSource.CustomSource;
//Set to show drop down *and* append current suggestion to end
txtMain.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
//Init string collection.
acsc = new AutoCompleteStringCollection();
//Set txtMain's AutoComplete Source to acsc
txtMain.AutoCompleteCustomSource = acsc;
}
private void txtMain_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Only keep 10 AutoComplete strings
if (acsc.Count < 10)
{
//Add to collection
acsc.Add(txtMain.Text);
}
else
{
//remove oldest
acsc.RemoveAt(0);
//Add to collection
acsc.Add(txtMain.Text);
}
}
}
private void Main_FormClosed(object sender, FormClosedEventArgs e)
{
//open stream to AutoComplete save file
StreamWriter sw = new StreamWriter("AutoComplete.acs");
//Write AutoCompleteStringCollection to stream
foreach (string s in acsc)
sw.WriteLine(s);
//Flush to file
sw.Flush();
//Clean up
sw.Close();
sw.Dispose();
}
private void Main_Load(object sender, EventArgs e)
{
//open stream to AutoComplete save file
StreamReader sr = new StreamReader("AutoComplete.acs");
//initial read
string line = sr.ReadLine();
//loop until end
while (line != null)
{
//add to AutoCompleteStringCollection
acsc.Add(line);
//read again
line = sr.ReadLine();
}
//Clean up
sr.Close();
sr.Dispose();
}
}
}
This code will work exactly as is, you just need to create the GUI with a TextBox named txtMain and hook up the KeyDown, Closed and Load events to the TextBox and Main form.
Also note that, for this example and to make it simple, I just chose to detect the Enter key being pressed as my trigger to save the string to the collection. There is probably more/different events that would be better, depending on your needs.
Also, the model used for populating the collection is not very "smart." It simply deletes the oldest string when the collection gets to the limit of 10. This is likely not ideal, but works for the example. You would probably want some sort of rating system (especially if you really want it to be Google-ish)
A final note, the suggestions will actually show up in the order they are in the collection. If for some reason you want them to show up differently, just sort the list however you like.
Hope that helps!

I store the completion list in the registry.
The code I use is below. It's reusable, in three steps:
replace the namespace and classname in this code with whatever you use.
Call the FillFormFromRegistry() on the Form's Load event, and call SaveFormToRegistry on the Closing event.
compile this into your project.
You need to decorate the assembly with two attributes: [assembly: AssemblyProduct("...")] and [assembly: AssemblyCompany("...")] . (These attributes are normally set automatically in projects created within Visual Studio, so I don't count this as a step.)
Managing state this way is totally automatic and transparent to the user.
You can use the same pattern to store any sort of state for your WPF or WinForms app. Like state of textboxes, checkboxes, dropdowns. Also you can store/restore the size of the window - really handy - the next time the user runs the app, it opens in the same place, and with the same size, as when they closed it. You can store the number of times an app has been run. Lots of possibilities.
namespace Ionic.ExampleCode
{
public partial class NameOfYourForm
{
private void SaveFormToRegistry()
{
if (AppCuKey != null)
{
// the completion list
var converted = _completions.ToList().ConvertAll(x => x.XmlEscapeIexcl());
string completionString = String.Join("¡", converted.ToArray());
AppCuKey.SetValue(_rvn_Completions, completionString);
}
}
private void FillFormFromRegistry()
{
if (!stateLoaded)
{
if (AppCuKey != null)
{
// get the MRU list of .... whatever
_completions = new System.Windows.Forms.AutoCompleteStringCollection();
string c = (string)AppCuKey.GetValue(_rvn_Completions, "");
if (!String.IsNullOrEmpty(c))
{
string[] items = c.Split('¡');
if (items != null && items.Length > 0)
{
//_completions.AddRange(items);
foreach (string item in items)
_completions.Add(item.XmlUnescapeIexcl());
}
}
// Can also store/retrieve items in the registry for
// - textbox contents
// - checkbox state
// - splitter state
// - and so on
//
stateLoaded = true;
}
}
}
private Microsoft.Win32.RegistryKey AppCuKey
{
get
{
if (_appCuKey == null)
{
_appCuKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(AppRegistryPath, true);
if (_appCuKey == null)
_appCuKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(AppRegistryPath);
}
return _appCuKey;
}
set { _appCuKey = null; }
}
private string _appRegistryPath;
private string AppRegistryPath
{
get
{
if (_appRegistryPath == null)
{
// Use a registry path that depends on the assembly attributes,
// that are presumed to be elsewhere. Example:
//
// [assembly: AssemblyCompany("Dino Chiesa")]
// [assembly: AssemblyProduct("XPathVisualizer")]
var a = System.Reflection.Assembly.GetExecutingAssembly();
object[] attr = a.GetCustomAttributes(typeof(System.Reflection.AssemblyProductAttribute), true);
var p = attr[0] as System.Reflection.AssemblyProductAttribute;
attr = a.GetCustomAttributes(typeof(System.Reflection.AssemblyCompanyAttribute), true);
var c = attr[0] as System.Reflection.AssemblyCompanyAttribute;
_appRegistryPath = String.Format("Software\\{0}\\{1}",
p.Product, c.Company);
}
return _appRegistryPath;
}
}
private Microsoft.Win32.RegistryKey _appCuKey;
private string _rvn_Completions = "Completions";
private readonly int _MaxMruListSize = 14;
private System.Windows.Forms.AutoCompleteStringCollection _completions;
private bool stateLoaded;
}
public static class Extensions
{
public static string XmlEscapeIexcl(this String s)
{
while (s.Contains("¡"))
{
s = s.Replace("¡", "¡");
}
return s;
}
public static string XmlUnescapeIexcl(this String s)
{
while (s.Contains("¡"))
{
s = s.Replace("¡", "¡");
}
return s;
}
public static List<String> ToList(this System.Windows.Forms.AutoCompleteStringCollection coll)
{
var list = new List<String>();
foreach (string item in coll)
{
list.Add(item);
}
return list;
}
}
}
Some people shy away from using the Registry for storing state, but I find it's really easy and convenient. If you like, You can very easily build an installer that removes all the registry keys on uninstall.

Related

How do I save user input in ListView?

my project
I was wondering how to save the User input in a ListView and prevent it from disappearing when I go to another Form
if (string.IsNullOrEmpty(txtName.Text) || string.IsNullOrEmpty(txtReview.Text))
return;
ListViewItem item = new ListViewItem(txtName.Text);
item.SubItems.Add(txtReview.Text);
listView1.Items.Add(item);
txtName.Clear();
txtReview.Clear();
As far I got your concern! You have a form in which you are adding a reviews. You are closing it soon after adding review. But you want all previous reviews when you visit that form again.
you cannot use database (it certainly would have been easiest way to do though), but you are allowed to use file system (you said text files, i'm assuming serialization too)
But reading and writing files on every now and then is costly process, I would recommend you keep data in memory cache (insert new reviews, update and delete them if there may such option). While closing an application, you store last updated copy into file and while starting software you read that file to get last updated copy of data.
(this way of storing data on closing software can cause data loss when software crash or stopped abnormally. but as it is class project, i would not worry much about that. however you can always use low priority thread to store data periodically)
For this approach, I would recommend to implement MVVM architecture
At least you should create a class which store all the data statically
(why static? it is an interesting question and i m leaving it on you to find out the answer)
Example code For Model:
public class Model
{
public static Dictionary<string, Review> ReviewData;
//this method should be called at application startup.
public static void SetModel()
{
//Desrialize lastly saved file, I'm just initializing it with new
ReviewData = new Dictionary<string, Review>();
}
public static void AddReview(string movie, string reviewerName, string review)
{
if (!ReviewData.ContainsKey(movie + "-" + reviewerName))
{
ReviewData.Add(movie + "-" + reviewerName, new Review(reviewerName, reviewerName));
}
}
}
public class Review
{
public string reviewerName;
public string review;
public Review(string reviewerName, string review)
{
this.reviewerName = reviewerName;
this.review = review;
}
}
Example Code for Add review form:
private void btnPost_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtName.Text) || string.IsNullOrEmpty(txtReview.Text))
return;
//First we should set Model data
Model.AddReview("moive1", txtName.Text, txtReview.Text);
LoadListView();
}
private void AddReviewForm_Load(object sender, EventArgs e)
{
LoadListView();
}
private void LoadListView()
{
listView1.Clear();
foreach (string reviewKey in Model.ReviewData.Keys)
{
Review review = Model.ReviewData[reviewKey];
ListViewItem item = new ListViewItem(review.reviewerName);
item.SubItems.Add(review.review);
listView1.Items.Add(item);
}
}
And last thing, while closing entire application, store lastly updated copy of Model.ReviewData (Serialize it).

How to add/remove items from a list from a different form?

Say I have a list called listOfFruits in my main form. In a second form I've made I want the user to be able to remove items from that list to a second list called removedFruits. Currently I know I can access these lists in my second form simply passing them as parameters in the form constructor. However c# can't do pointers (correct?) so how can I effect the main form's copy of these lists from my second form? Because currently any changes to those lists in my second form don't effect the main form's original copy of the lists. If I were to remove 5 fruits from the listOfFruits passed to my second form then after finishing my work the main form would still still have a full listOfFruits and an empty removedFruits. Is there a simple fix to this? Maybe a get/set or a way to add/remove items from the original lists from the second form? Maybe the answer is in some sort of accessor stuff?
EDIT: To clarify; I want to add to one list, and remove from another. Not add/remove to the same list. Not sure if this matters entirely but I figured I'd be specific here in case it does.
EDIT2: I think the issue is I'm copying the original list from the first form and not editing it directly. Can someone fix my code so I can access the original list from my second form instead of making a copy of the list?
public partial class ListSelector : Form
{
private string windowName = Form1.typeOfModuleAdded;
public List<IOModule> innerIOList;
IOModule cardAdded = null;
public ListSelector(List<IOModule> cardList)
{
this.Text = windowName;
innerIOList = cardList;
InitializeComponent();
InitializeList();
}
private void InitializeList()
{
if (windowName == "Drive")
{
string[] listDrives = { "ACS880", "test" };
listBox1.Items.AddRange(listDrives);
}
else if (windowName == "IOBlock")
{
if (!innerIOList.Any())
{
MessageBox.Show("No cards loaded! Please import cards from IO List.", "Error Empty Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
}
foreach (IOModule card in innerIOList)
{
cardAdded = card;
listBox1.Items.Add(card.name);
}
}
else if (windowName == "Local Card")
{
string[] listLocals = { "1756-EN2T", "test" };
listBox1.Items.AddRange(listLocals);
}
else if (windowName == "Processor")
{
string[] listProcessors = { "1756-L71S", "test" };
listBox1.Items.AddRange(listProcessors);
}
}
private void addBtn_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItem != null)
{
Form1.SetModule(listBox1.SelectedItem.ToString());
Form1.confirmedAdd = true;
this.Close();
}
else if (cardAdded != null)
{
innerIOList.Remove(cardAdded);
}
else
{
MessageBox.Show("No module selected!");
}
}
and here's how I pass the list to that form from my first form:
ListSelector test = new ListSelector(ioList);
test.ShowDialog();
where ListSelector is the name of my second form, and ioList is the list im passing to it.
EDIT3: added more code
"However c# can't do pointers (correct?) so how can I effect the main form's copy of these lists from my second form?"
No, not correct. Any object reference (for instance, of a List<Fruit>) is still very much a pointer to a place in memory, and if you pass the same List<Fruit> object to both Forms, they share the same List.
I don't know why your changes to your listOfFruits don't chow up in your first Form. I would check the following things:
Are you 100% sure you use the same List<Fruit> object in both Forms. (If you create a new List like this: new List<Fruit>(listOfFruits) it is NOT the same List)
Does the first Form have any way of finding out, that the List has changed? Possible using a Timer with recurring checks, or (my favorite) triggering an event when you change something, and subscribe an EventHandler in the first Form to the event.
I assume that you have created a second list in your second form that is filled with the items of the first form's list. Then changes on the second list aren't reflected in the first list. You have to use the same reference of the list.
public Form2(List<Fruit> listOfFruits)
{
this._listOfFruits = listOfFruits;
}
private List<Fruit> _listOfFruits;
Instead using a public field, try to use property and on creating your new ListSelector pass the list to the property.
public partial class ListSelector : Form
{
private string windowName = Form1.typeOfModuleAdded;
private List<IOModule> innerIOList;
IOModule cardAdded = null;
public List<IOModule> CardList
{
get
{
return innerIOList;
}
set
{
innerIOList = value;
InitializeList();
}
}
public ListSelector()
{
this.Text = windowName;
InitializeComponent();
}
When creating your new ListSelector object
ListSelector ls = new ListSelector();
ls.CardList = your mainform list of IOModule here
ls.ShowDialog();

C1RichTextBox with custom copy/paste behavior

When using C1RichTextBox in Silverlight 5 with IE 10, I am facing two major issues:
During a clipboard paste operation, how can I detect if the content was copied from another C1RichTextBox in my Silverlight application or from an external application? From external applications, only text should be pasted without formatting.
Copy/Pasting large inline images from one C1RichTextBox to another does not work. The <img> elements have the image content stored in their data URL. If the image becomes too large (approx 1MB), the src attribute is dropped when copied to the clipboard.
The solution should:
Not have side-effects on the global clipboard or on the editing behavior of the C1RichTextBox.
Be robust against changes to the C1RichTextBox implementation.
Not have to modify/parse/analyze the HTML document in the clipboard.
It took me a while to figure all this (an a lot more...) out and I am happy to share with anyone who has to deal with these issues.
I am using a derived class to solve the issues
public class C1RichTextBoxExt : C1RichTextBox
{
1. Pasting from external application with text-only
The solution is simple in theory: Get a hold of the HTML after text from within the RichTextBox was copied/cut to the clipboard. When pasting, compare the current HTML in the clipboard with what was last copied. Because the clipboard in ComponentOne is global, the content changes if a Copy/Cut was done in another application and thus the HTML will be different.
To remember the last copied HTML, we use a static member inside C1RichTextBoxExt:
private static string _clipboardHtml;
The bad news is: The C1RichTextBox.ClipboardCopy() etc. methods are not virtual. The good news is: The keyboard shortcuts for Copy/Cut/Paste which call these methods can be disabled, e.g. in the constructor:
RemoveShortcut(ModifierKeys.Control, Key.C);
RemoveShortcut(ModifierKeys.Control, Key.Insert);
RemoveShortcut(ModifierKeys.Control, Key.V);
RemoveShortcut(ModifierKeys.Shift , Key.Insert);
RemoveShortcut(ModifierKeys.Control, Key.X);
RemoveShortcut(ModifierKeys.Shift , Key.Delete);
Now that the methods C1RichTextBox.ClipboardCopy() etc. are no longer called we can wire up our own version by overriding OnKeyDown:
protected override void OnKeyDown(KeyEventArgs e)
{
if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.C)) { ClipboardCopy(); }
else if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.Insert)) { ClipboardCopy(); }
else if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.V)) { ClipboardPaste(); }
else if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.X)) { ClipboardCut(); }
else if ((Keyboard.Modifiers == ModifierKeys.Shift) && (e.Key == Key.Insert)) { ClipboardPaste(); }
else if ((Keyboard.Modifiers == ModifierKeys.Shift) && (e.Key == Key.Delete)) { ClipboardCut(); }
else
{
// default behaviour
base.OnKeyDown(e);
return;
}
e.Handled = true; // base class should not fire KeyDown event
}
To not accidentally call the base class methods, I am overwriting them (see below, using new modifier). The ClipboardCopy() method just calls the base class and afterwards stores the clipboard HTML. A small pitfall here was to use Dispatcher.BeginInvoke() since the C1RichTextBox.ClipboardCopy() stores the selected text in the clipboard inside a Dispatcher.BeginInvoke() invocation. So the content will only be available after the dispatcher had a chance to run the action provided by C1RichTextBox.
new public void ClipboardCopy()
{
base.ClipboardCopy();
Dispatcher.BeginInvoke(() =>
{
_clipboardHtml = C1.Silverlight.Clipboard.GetHtmlData();
});
}
The ClipboardCut method is very similar:
new public void ClipboardCut()
{
base.ClipboardCut();
Dispatcher.BeginInvoke(() =>
{
_clipboardHtml = C1.Silverlight.Clipboard.GetHtmlData();
});
}
The ClipboardPaste method can now detect if pasting external data. Pasting text only is no so straightforward. I came up with the idea to replace the current clipboard content with the text-only representation of the clipboard. After pasting is done, the clipboard should be restored so the content can be pasted again in other applications. This also has to be done within a Dispatcher.BeginInvoke() since the base class method C1RichTextBox.ClipboardPaste() performs the paste operation in a delayed action as well.
new public void ClipboardPaste()
{
// If the text in the global clipboard matches the text stored in _clipboardText it is
// assumed that the HTML in the C1 clipboard is still valid
// (no other Copy was made by the user).
string current = C1.Silverlight.Clipboard.GetHtmlData();
if(current == _clipboardHtml)
{
// text is the same -> Let base class paste HTML
base.ClipboardPaste();
}
else
{
// let base class paste text only
string text = C1.Silverlight.Clipboard.GetTextData();
C1.Silverlight.Clipboard.SetData(text);
base.ClipboardPaste();
Dispatcher.BeginInvoke(() =>
{
// restore clipboard
C1.Silverlight.Clipboard.SetData(current);
});
}
}
2. Copy/Pasting large inline images
The idea here is similar: Remember the images when copied, put them back in during paste.
So first we need to store where which image is in the document:
private static List<C1TextElement> _clipboardImages;
private static int _imageCounter;
(The use of _imageCounter will be explained later...)
Then, before Copy/Cut is executed, we search for all images:
new public void ClipboardCopy()
{
_clipboardImages = FindImages(Selection);
base.ClipboardCopy();
// ... as posted above
}
and similar:
new public void ClipboardCut()
{
_clipboardImages = FindImages(Selection);
base.ClipboardCut();
// ... as posted above
}
The methods to find the images are:
private List<BitmapImage> FindImages(C1TextRange selection = null)
{
var result = new List<BitmapImage>();
if (selection == null)
{
// Document Contains all elements at the document level.
foreach (C1TextElement elem in Document)
{
FindImagesRecursive(elem, result);
}
}
else
{
// Selection contains all (selected) elements -> no need to search recursively
foreach (C1TextElement elem in selection.ContainedElements)
{
if (elem is C1InlineUIContainer)
{
FindImage(elem as C1InlineUIContainer, result);
}
}
}
return result;
}
private void FindImagesRecursive(C1TextElement elem, List<BitmapImage> list)
{
if (elem is C1Paragraph)
{
var para = (C1Paragraph)elem;
foreach (C1Inline inl in para.Inlines)
{
FindImagesRecursive(inl, list);
}
}
else if (elem is C1Span)
{
var span = (C1Span)elem;
foreach (C1Inline child in span.Inlines)
{
FindImagesRecursive(child, list);
}
}
else if (elem is C1InlineUIContainer)
{
FindImage(elem as C1InlineUIContainer, list);
}
}
private void FindImage(C1InlineUIContainer container, List<BitmapImage> list)
{
if (container.Content is BitmapImage)
{
list.Add(container.Content as BitmapImage);
}
}
I won't go into details about the above methods, they are pretty straightforward if you analyze the structure of C1RichTextBox.Document.
Now, how do we restore the images? The best I found is to use the ConvertingHtmlNode event of the C1RichTextBox.HtmlFilter. This event is fired every time a HTML node is converted into a C1TextElement. We subscribe to it in the constructor:
HtmlFilter.ConvertingHtmlNode += new EventHandler<ConvertingHtmlNodeEventArgs>(HtmlFilter_ConvertingHtmlNode);
and implement it like this:
void HtmlFilter_ConvertingHtmlNode(object sender, ConvertingHtmlNodeEventArgs e)
{
if (e.HtmlNode is C1HtmlElement)
{
var elem = e.HtmlNode as C1HtmlElement;
if (elem.Name.ToLower() == "img" && _clipboardImages != null && _clipboardImages.Count > _imageCounter)
{
if (!elem.Attributes.ContainsKey("src")) // key comparison is not case sensitive
{
e.Parent.Children.Add(_clipboardImages[_imageCounter].Clone());
e.Handled = true;
}
_imageCounter++;
}
}
}
So for each HTML element node with the name "img" we check if the "src" attribute is missing. If so, we add the next stored image instead and tell the event source that the event is now handled (for this HTML node) by setting e.Handled = true;
Which image is the "next" image is determined by the _imageCounter field which is incremented for each visited "img" element.
The _imageCounter field must be reset when ClipboardPaste() is invoked, so we do:
new public void ClipboardPaste()
{
_imageCounter = 0;
string current = C1.Silverlight.Clipboard.GetHtmlData();
// ... as posted above
}
Conclusion
If you copy/paste (no pun intended...) all code blocks posted above together, you should end up with a solution which has no side-effects (at least none known to the author as of today), is robust against changes and does almost no HTML processing.

save and load Listbox Items locally and pass them to other pages

I am currently working on Windows Store App in c#.
Now,
I am having a list box 'Listbox1' which gets its items on a button click event from a text box 'tasks', and have selected Items delete property on other button click event.
private void add_Click(object sender, RoutedEventArgs e)
{
string t;
t = tasks.Text;
if (t != "")
{
Listbox1.Items.Add(t);
}
else
{
var a = new MessageDialog("Please Enter the Task First");
a.Commands.Add(new UICommand("Ok"));
a.ShowAsync();
}
tasks.Text = "";
}
private void del_Click(object sender, RoutedEventArgs e)
{
for (int p = 0; p < Listbox1.SelectedItems.Count; p++)
{
Listbox1.Items.Remove(Listbox1.SelectedItems[p].ToString());
p--;
}
}
Now I want to save this list into local application storage, after user complete the changes (on a button click event perhaps).
And also to send all Listbox Items to another page(s).
I am not much a coder, I design things.
Please guide me by sample or reference.
Thank you in advance :)
If you have already stored the data to local storage, you could just read it in the OnNavigatedTo override of the other page. Otherwise, use the navigation parameter: http://social.msdn.microsoft.com/Forums/windowsapps/en-US/8cb42356-82bc-4d77-9bbc-ae186990cfd5/passing-parameters-during-navigation-in-windows-8
Edit: I am not sure whether you also need some information about local storage. This is easy: Windows.Storage.ApplicationData.Current.LocalSettings has a property called Values, which is a Dictionary you can write your settings to. Have a look at http://msdn.microsoft.com/en-us/library/windows/apps/hh700361.aspx
Edit: Try something like this code to store your list.
// Try to get the old stuff from local storage.
object oldData = null;
ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
bool isFound = settings.Values.TryGetValue("List", out oldData);
// Save a list to local storage. (You cannot store the list directly, because it is not
// serialisable, so we use the detours via an array.)
List<string> newData = new List<string>(new string[] { "test", "blah", "blubb" });
settings.Values["List"] = newData.ToArray();
// Test whether the saved list contains the expected data.
Debug.Assert(!isFound || Enumerable.SequenceEqual((string[]) oldData, newData));
Note, this is only demo code for testing - it does not make real sense...
Edit: One advice: Do not persist the list in your click handlers as this will become extremely slow as the list grows. I would load and save the list in the Navigation handlers, i.e. add something like
protected override void OnNavigatedTo(NavigationEventArgs e) {
base.OnNavigatedTo(e);
if (this.ListBox1.ItemsSource == null) {
object list;
if (ApplicationData.Current.LocalSettings.Values.TryGetValue("List", out list)) {
this.ListBox1.ItemsSource = new List<string>((string[]) list);
} else {
this.ListBox1.ItemsSource = new List<string>();
}
}
}
protected override void OnNavigatedFrom(NavigationEventArgs e) {
if (this.ListBox1.ItemsSource != null) {
ApplicationData.Current.LocalSettings.Values["List"] = this.ListBox1.ItemsSource.ToArray();
}
base.OnNavigatedFrom(e);
}
Here is very nice simple example on SQLite DataBase Use in winRT app Development. Look at it and you will know how you can store your Data on the Local Machine. I learned Basic code from this example.
http://blogs.msdn.com/b/robertgreen/archive/2012/11/13/using-sqlite-in-windows-store-apps.aspx
Now, for ease of navigation let me suggest you a flow for this portion of your app.
take one ObservableCollection<> of string and store values of
that textBox into this ObservationCollection with onClick() and then
refer that ObservableCollection<String> to the ItemsList of the
listBox.
now at the time you need to send your Data to the next page, make one parameterised constructor of next page and pass that ObservableCollection<String> as it's parameter.
Now you can access those Data in your constructor and can use as however you want.
Hope this will help..

Issues with ListView & File Output

I have so many issues with my project, i really don't know where to begin. First off, i get an error "an object reference is required for non-static field, method or property". It underlines retPath (the line: DriveRecursion_results.DriveRecursion(retPath);). I have no idea how to fix this.
THe other thing i'm still stumped on is how to populate a listview on my Windows Form. What i want is a list of files that need to be renamed (versus a list of all files in my list.)
Can anybody help? I have been struggling miserably with this for several hours now.
Here is my code:
Form1.cs:
namespace FileMigration
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FolderSelect("Please select:");
}
public string FolderSelect(string txtPrompt)
{
//Value to be returned
string result = string.Empty;
//Now, we want to use the path information to population our folder selection initial location
string initialCheckoutPathDir = (#"C:\");
System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(initialCheckoutPathDir);
FolderBrowserDialog FolderSelect = new FolderBrowserDialog();
FolderSelect.SelectedPath = info.FullName;
FolderSelect.Description = txtPrompt;
FolderSelect.ShowNewFolderButton = true;
if (FolderSelect.ShowDialog() == DialogResult.OK)
{
string retPath = FolderSelect.SelectedPath;
if (retPath == null)
{
retPath = "";
}
DriveRecursion_Results ds = new DriveRecursion_Results();
ds(retPath);
result = retPath;
//Close this form.
}
return result;
}
}
}
Here is DriveRecursion_Results.cs:
namespace FileMigration
{
public partial class DriveRecursion_Results : Form
{
public DriveRecursion_Results()
{
InitializeComponent();
}
private void fileOutput_SelectedIndexChanged(object sender, EventArgs e)
{
}
public void DriveRecursion(string retPath)
{
// string[] files = Directory.GetFiles(retPath, "*.*", SearchOption.AllDirectories);
string pattern = " *[\\~#%&*{}/<>?|\"-]+ *";
string replacement = "";
Regex regEx = new Regex(pattern);
string[] fileDrive = Directory.GetFiles(retPath, "*.*", SearchOption.AllDirectories);
List<string> filePath = new List<string>();
foreach (string fileNames in fileDrive)
{
if (regEx.IsMatch(fileNames))
{
filePath.Add(fileNames);
//I tried adding my listview (fileOptions) here but I cannot for some reason
}
}
}
}
}
ANY help would really be appreciated :( Does anybody have any ideas on how to change my code so it actually works?
Issue 1: your function is static. If it stops being such, this will work. This is because a static function does not have this hidden 'this' argument - the reference to object it acts upon. So, it can only access static data members, not regular ones.
You can't add the items to your listview from that level because the listview is non-static and the method DriveRecursion is static. I would start by changing the DriveRecursion method to be non-static or return a list of file paths.
You are not able to add items to your list view because you are trying to add them from a static method.
Since it is static there is no ListView because there isn't actually a Form to add things to. You will need to make DriveRecursion() not static in order to add things to the ListView.
Additionally, when you make DriveRecursion() not static, you will need a way to let Form1 know which DriveRecursion_Results class to populate.
Another approach you could take is having Form1 return retPath to DriveRecursion_Results.
Edit
Removed irrelevant parts of my original answer
I have copied your code exactly how you posted it. And then made the following changes to FolderSelect() in Form1.cs When I run this code. I can get the second window to pop up, but not the other window to close, because that will cause the application to quit.
Please make sure you have ds.Show() and do at some point call ds.DriveRecursion(retPath)
Modified FolderSelect(string) in Form1.cs:
private void FolderSelect( string txtPrompt )
{
//Value to be returned
string result = string.Empty;
//Now, we want to use the path information to population our folder selection initial location
string initialCheckoutPathDir = ( "C:\\" );
System.IO.DirectoryInfo info = new System.IO.DirectoryInfo( initialCheckoutPathDir );
FolderBrowserDialog FolderSelect = new FolderBrowserDialog();
FolderSelect.SelectedPath = info.FullName;
FolderSelect.Description = txtPrompt;
FolderSelect.ShowNewFolderButton = true;
if( FolderSelect.ShowDialog() == DialogResult.OK )
{
string retPath = FolderSelect.SelectedPath;
if( retPath == null )
{
retPath = "";
}
DriveRecursion_Results ds = new DriveRecursion_Results();
ds.DriveRecursion( retPath );
ds.Show();
result = retPath;
//Close this form.
}
return;
}

Categories

Resources