I've created a windows phone 7 application using Isolated Storage. In this application i've used a button named as btnRead, a textblock named as txtRead and a text box named as txtWrite. If i write something to the textbox(txtWrite) and clicked on the button(btnRead). Then the textblock(txtRead) shows or saves whatever i write on textbox(All these are created in a single MainPage.xaml). Now I have created another page1.xaml and created a textblock named as txtShow. But I want the textblock(txtShow) to show all the things that i write on textbox which is in MainPage.xaml. I have also uploaded my project- https://skydrive.live.com/redir.aspx?cid=ea5aaefa4ad2307a&resid=EA5AAEFA4AD2307A!133&parid=EA5AAEFA4AD2307A!109
Below is MainPage.xaml.cs source that i have used -:
private void button1_Click(object sender, RoutedEventArgs e)
{
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
myStore.CreateDirectory("Bookmark");
using (var isoFileStream = new IsolatedStorageFileStream("Bookmark\\myFile.txt", FileMode.OpenOrCreate, myStore))
{
//Write the data
using (var isoFileWriter = new StreamWriter(isoFileStream))
{
isoFileWriter.WriteLine(txtWrite.Text);
}
}
try
{
// Specify the file path and options.
using (var isoFileStream = new IsolatedStorageFileStream("Bookmark\\myFile.txt", FileMode.Open, myStore))
{
// Read the data.
using (var isoFileReader = new StreamReader(isoFileStream))
{
txtRead.Text = isoFileReader.ReadLine();
}
}
}
catch
{
// Handle the case when the user attempts to click the Read button first.
txtRead.Text = "Need to create directory and the file first.";
}
}
If you are displaying the text from the TextBox in a TextBlock in the same page, it would be easier to do that through binding
<TextBox x:Name="txtWrite"/>
<TextBlock Text="{Binding Text, ElementName=txtWrite}"/>
To put this information into the next page you could put it into the NavigationContext to pass to the next page
// Navigate to Page1 FROM MainPage
// This can be done in a button click event
NavigationService.Navigate(new Uri("/Page1.xaml?text=" + txtWrite.Text, UriKind.Relative));
// Override OnNavigatedTo in Page1.xaml.cs
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
string text;
NavigationContext.QueryString.TryGetValue("text", out text);
txtRead.Text = text;
}
If you like using IsoStorage, you could do the read like you are doing above in the OnNavigatedTo method.
Related
I initially have a Fileupload tool to upload a textfile, manipulate its content and display into a Listbox or Textbox. The limitation however is Fileupload only supports single uploading, at least to the version of .Net Framework I am using.
What I intend to do is just use a button control and remove the Fileupload. Upon Button click I need to read the textfiles inside a designated folder path and display first the contents inside a multiple lined textbox. (not just the file name) This is my intially written codes, and it is not working.
protected void btnGetFiles_Click(object sender, EventArgs e)
{
string content = string.Empty;
DirectoryInfo dinfo = new DirectoryInfo(#"C:\samplePath");
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
//ListBox1.Items.Add(file.Name);
content += content;
}
txtContent.Text = content;
}
Since your's is web based application you can't access physical paths like c:\\.. you should use Server.MapPath anyway(As per the comment, you don't need to get the file with Server.MapPath). Then for getting the content you can try something like the following:
protected void btnGetFiles_Click(object sender, EventArgs e)
{
try
{
StringBuilder content = new StringBuilder();
if (Directory.Exists(#"C:\samplePath"))
{
// Execute this if the directory exists
foreach (string file in Directory.GetFiles(#"C:\samplePath","*.txt"))
{
// Iterates through the files of type txt in the directories
content.Append(File.ReadAllText(file)); // gives you the conent
}
txtContent.Text = content.ToString();
}
}
catch
{
txtContent.Text = "Something went wrong";
}
}
you wrote content += content;, that is the problem. change it to content += file.Name;, it will work.
So, I would like any help to populate a ListBox that is going to show a website name and if it's clicked go to a specific url.
This is what's inside of the text file:
#first website
http://firstwebsite.com
#second website
http://secondwebsite.com
#third website
http://thirdwebsite.com
I can read the file and populate the listbox with the name, but cannot put the url working.
FileOpenPicker picker = new FileOpenPicker();
picker.ViewMode = PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
picker.FileTypeFilter.Add(".txt");
StorageFile file = await picker.PickSingleFileAsync();
if (file != null) {
var stream = await file.OpenAsync(FileAccessMode.Read);
using (StreamReader reader = new StreamReader(stream.AsStream()))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (line.StartsWith("#") {
listbox.items.Add(line);
}
Any help is great.
Thanks
If you want it in the "Click" event, I mean when you click on the Item, below code works.
private void listBox1_Click(object sender, EventArgs e)
{
string str = ((ListBox)(sender)).Text;
Process.Start(str);
}
Handle NULL conditions and exceptions.
Add System.Diagnostics namespace for "Process".
I've created a very simple console to test this.
Here is what I came up with
var _listBox1 = new ListBox();
//just adding a url for example
_listBox1.Items.Add("http://www.google.com");
//here I am just setting the selected value
_listBox1.SetSelected(0, true);
var selectedUrl = _listBox1.SelectedItem.ToString();
//this will start off the default web browser
Process.Start(selectedUrl);
So the Process.Start() can be put in any event handlers for that listbox. I.E SelectedIndexChanged event
private void _listBox1_SelectedIndexChanged(object pSender, EventArgs pArgs)
{
var selectedUrl = _listBox1.SelectedItem.ToString();
Process.Start(selectedUrl);
}
I am in the process of making a multi tab browser and have run into some problems. I would like it so when the user has added a new tab using a button, that every site they then choose to navigate to will update to the tab url. So if the user changes tab or opens a new one, it the last website will be saved if they return to the previous tab.
Here is the code while creating a new tab & When a tab is selected from the created ones
private void addNewTab(string url)
{
TabEntry urlObj = new TabEntry();
urlObj.URL = url;
urlObj.timestamp = DateTime.Now.ToString("HH:mm");
if (url.Contains("/"))
{
urlObj.Name = url.Remove(url.IndexOf('/'));
}
else
{
urlObj.Name = url.Remove(url.IndexOf('.'));
}
tabs.Insert(0, urlObj);
listBoxTabPage.ItemsSource = null;
listBoxTabPage.ItemsSource = tabs;
Browser.Navigate(new Uri("http://www.google.com", UriKind.Absolute));
//selectedTab = listBoxTabPage.SelectedValue as TabEntry;
}
private void ListBoxTabPage_SelectionChanged(object sender, GestureEventArgs e)
{
selectedTab = listBoxTabPage.SelectedValue as TabEntry;
Browser.Navigate(new Uri("http://www." + selectedTab.URL, UriKind.Absolute));
PivotItems.SelectedItem = BrowserPage;
}
Here is the code where it should update the selected tabs url, in the Browser_Navigated methord
void Browser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
_deactivatedURL = e.Uri;
_progressIndicator.IsVisible = false;
string url = Convert.ToString(e.Uri);
//selectedTab.URL = url;
addHistoryRecord(url);
}
Where it is commented out I think is the problem. I believe the code does not know which one is the selectedTab. To fix this error should I create a methord which updates the url of the tab, each time the browser navigates. And how would the program know which tab is currently in use.
If you need any more details please comment and I will be happy to explain in further detail.
You just set listBoxTabPage.ItemsSource = null before you set tabs as ItemsSource. It may clears your listBoxTabPage.SelectedValue.
I think you can just set listBoxTabPage.SelectedValue = urlObj in addNewTab().
Then you begin navigate to a new uri in ListBoxTabPage_SelectionChanged, but it seems to be wrong that you just append a prefix string http://www. to an full url. It may triggers NavigateFailed event if you navigate to a non-exist website.
Browser.Navigate(new Uri("http://www." + selectedTab.URL, UriKind.Absolute));
What's more, ListBoxTabPage_SelectionChanged may triggers twice because the old value is cleared and the new value is set.
I want to iterate through all the files in a folder and dynamically create images controls for each JPEG file found. Once complete I want a form filled with dynamically created image controls (think of just about any photo viewing software such as Picasa that has a thumbnail view).
I want to be able to reorder these dynamically created images controls on the form by implementing some sort of drag drop event handler. I will not know how many images I will encounter and therefore cannot hardcode event handlers for each image control that might or might not exist. So I am looking for a way to dynamically add event handlers to dynamically created controls.
The method used in the code below is almost what I am looking for. The problem with the method below is that if I don't know the name of the control I could not hard code the event handler.
public partial class RoutedEventAddRemoveHandler {
void MakeButton(object sender, RoutedEventArgs e)
{
Button b2 = new Button();
b2.Content = "New Button";
// Associate event handler to the button. You can remove the event
// handler using "-=" syntax rather than "+=".
b2.Click += new RoutedEventHandler(Onb2Click);
root.Children.Insert(root.Children.Count, b2);
DockPanel.SetDock(b2, Dock.Top);
text1.Text = "Now click the second button...";
b1.IsEnabled = false;
}
void Onb2Click(object sender, RoutedEventArgs e)
{
text1.Text = "New Button (b2) Was Clicked!!";
}
}
Note I am looking for a solution in c# code not XAML. That is a solution using code like this to add controls:
// What I want
Fields.Add(new Field() { Name = "Username", Length = 100, Required = true });
not like this:
// What I do not want
<TextBox Width="100" Canvas.Left="50" Canvas.Top="20" />
Thanks
I would not do so much in codebehind. Only to get the files.
I would get an ObservableCollection where the string is the FullName of the file.
Then I would present it in a ListBox or ListView having the ItemSource bound to the collection and defining å good ItemTemplate for the control.
In the template, you can use a Converter to create å Source for the Image in the template.
Adding a small sample just to save you the pain of image loading in WPF code-behind.
void OnButtonClick(object sender, RoutedEventArgs routedEventArgs)
{
var files = Directory.GetFiles(#"C:\img");
foreach (var file in files)
{
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(file);
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
var img = new Image { Source = bitmap };
img.MouseDown += OnImageMouseDown;
//Add img to your container
}
}
void OnImageMouseDown(object sender, MouseButtonEventArgs e)
{
var img = sender as Image;
//Operate
}
I am making an application where i am opening wpf pages in tab control. But i am able to open same page again and again in tabcontrol. I want that if once page is opened it can't be opened again and it should get focused on tabcontrol if i try to open it again. i did following code but not working. I am using a custom closableTabItem Usercontrol.
private void Set_Fee_Click(object sender, RoutedEventArgs e)
{
// Adding page to frame and then adding that frame to tab item and then adding tab item to main tab.
FeeStructure feePage = new FeeStructure();
_closableTab = new ClosableTabItem();
_formFrame = new Frame();
_formFrame.Content = feePage;
_closableTab.Content = _formFrame;
_closableTab.Header = "Set Fee Structure";
if (!mainTab.Items.Contains(_closableTab))
{
mainTab.Items.Add(_closableTab);
_closableTab.Focus();
}
else
{
_closableTab.Focus();
}
}
private void Database_RecoveryBackup_Click(object sender, RoutedEventArgs e)
{
// Adding page to frame and then adding that frame to tab item and then adding tab item to main tab.
DbRecoveryBackup dbRecBack = new DbRecoveryBackup();
_closableTab = new ClosableTabItem();
_formFrame = new Frame();
_formFrame.Content = dbRecBack;
_closableTab.Content = _formFrame;
_closableTab.Header = "Data Base";
if (!mainTab.Items.Contains(_closableTab))
{
mainTab.Items.Add(_closableTab);
_closableTab.Focus();
}
else
{
_closableTab.Focus();
}
}
It'll never happen, what you want because you're creating a new instance of ClosableTabItem everytime, hence it is unique everytime, so .Items.Contains will never work in this case because it matches items using object.Equals.
Now, Since you said in question that you only want one instance of ClosableTabItem, then
using Linq, you can check if in the items there exist any item of type ClosableTabItem,
...
// Here we're checking the array 'Items',
// if it contains any item whose type is 'ClosableTabItem'
if (!mainTab.Items.Any(item => item is ClosableTabItem)))
...