Create ListBox items from text file with 2 variables - c#

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);
}

Related

Read Multiple Textfile upon Button Click and Display Content

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.

Saving textbox text into XML file

I have an ASP.NET WebForm with 1 button and 4 textboxes.
Every time the page loads, the following code to read data from an XML file and display in the textboxes is executed:
private void PutWhatWasBefore()
{
var xml = XDocument.Load(#"C:\Settings.xml");
From_display.Text = xml.Element("Settings").Element("Remember").Attribute("fromdisplay").Value.ToString();
From_Smtp.Text = xml.Element("Settings").Element("Remember").Attribute("fromsmtp").Value.ToString();
subject.Text = xml.Element("Settings").Element("Remember").Attribute("subject").Value.ToString();
}
This code works well, it puts everything in the textboxes. BUT, and this is a big but, when i click the button, the following code to write to the XML file does not work:
string tem = Template1.Text;
string from = From_Smtp.Text;
string dis = From_display.Text;
string sub = subject.Text;
var x = new XDocument(
new XElement("Settings",
new XElement("Remember",
new XAttribute("fromsmtp", from),
new XAttribute("subject", sub),
new XAttribute("fromdisplay", dis),
new XAttribute("template", tem)
)
)
);
x.Save(#"C:\Settings.xml");
No matter how I change the data in the text boxes, every time I click on the button the data reverts back to what it was before.
I was thinking its a post back and that's why this is happening, but even if i disable the post back with OnClientClick = return false; it still does not work.
Any ideas?
EDIT(12:06):
I don't think I have said where the problem was and I want to be more into the point.
When I click the button the following function is executed first:
private void SaveNames()
{
try
{
string tem = Template1.Text;
string from = From_Smtp.Text;
string dis = From_display.Text;
string sub = subject.Text;
var x = new XDocument(
new XElement("Settings",
new XElement("Remember",
new XAttribute("fromsmtp", "He2"),
new XAttribute("subject", sub),
new XAttribute("fromdisplay", dis),
new XAttribute("template", tem)
)
)
);
x.Save(#"C:\Program Files (x86)\ActivePath\MailSenderWeb\Settings.xml");
}
catch (Exception ex)
{
AnswerAndError.Text = ex.Message;
}
}
That's the functions that doesn't work. It just doesn't save new data into the XML file.
This should solve your issue:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PutWhatWasBefore();
}
}
This will ensure the code runs only when the page is initially visited.

how ot make background agent to check for new feeds

I want to make the background agent in my Windows Phone app check for new feeds in the background, i use webclient to download them and i display them in an listbox i use an webbrowser control to display the selected feed to the page it comes from via url i got from the syndicationitem, now i want to save lets say the title or the publishdate to isolated storage and that the background agent checks every 30 min. for feeds and checks if some new feed are available with comparing the the last feed Title or the last publishdate saved already and the newsest on the page, then if a newer feed is there it should send an toast notification with the title of the feed and open my app.
i have nothing done to save the feeds before, i dont know how to do this and i dont know how to use background agents and do thid what i wrote above. I use Microsofts example of an rss reader as background for my app logic. downloading, displaying all that like the sample here - http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh487167(v=vs.105).aspx
here is some code:
i use this to download the feeds
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new System.Uri("http://wpnovosti.com/feeds/posts/default?alt=rss"));
this i use to show them on my listbox and there is some logic of the live tiles too:
public void UpdateFeedList(string feedXML)
{
StringReader stringReader = new StringReader(feedXML);
XmlReader xmlReader = XmlReader.Create(stringReader);
SyndicationFeed feed = SyndicationFeed.Load(xmlReader);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// Bind the list of SyndicationItems to our ListBox.
feedListBox.ItemsSource = feed.Items;
SystemTray.SetProgressIndicator(this, null);
//Live Tiles
ShellTile appTile = ShellTile.ActiveTiles.First();
if (appTile != null)
{
FlipTileData TileData = new FlipTileData()
{
Title = "",
BackTitle = "WP Novosti",
BackContent = feed.Items.First().Title.Text,
WideBackContent = feed.Items.First().Title.Text,
Count = 0,
};
appTile.Update(TileData);
}
else
{
}
});
this i use if an item is selected on the listbox:
public void feedListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox listBox = sender as ListBox;
if (listBox != null && listBox.SelectedItem != null)
{
// Get the SyndicationItem that was tapped.
SyndicationItem sItem = (SyndicationItem)listBox.SelectedItem;
// Set up the page navigation only if a link actually exists in the feed item.
if (sItem.Links.Count > 0)
{
Uri uri = sItem.Links.FirstOrDefault().Uri;
NavigationService.Navigate(new Uri("/Pregled.xaml?url=" + uri, UriKind.Relative));
UpdateFeedList(State["feed"] as string);
}
}
}
the rest is just displaying this passed url on another page via webbrowser control. how can i make this really work now like i want described on top?!

Dynamically adding LinkLabels to a TableLayoutPanel

I've been having a problem with the following code:
namespace Viewer
{
public partial class Form1 : Form
{
int count = 0;
LinkLabel[] linkLabel = new LinkLabel[200];
string filename;
string extension;
string filepath;
private void btnLoad_Click(object sender, EventArgs e)
{
// Creates a Directory for the Movies Folder
DirectoryInfo myDirectory = new DirectoryInfo(#"C:\Users\User\Movies");
// Creates a list of "File info" objects
List<FileInfo> ls = new List<FileInfo>();
// Adds filetypes to the list
ls.AddRange(myDirectory.GetFiles("*.mp4"));
ls.AddRange(myDirectory.GetFiles("*.avi"));
// Orders the list by Name
List<FileInfo> orderedList = ls.OrderBy(x => x.Name).ToList();
// Loop through file list to act on each item
foreach (FileInfo filFile in orderedList)
{
// Creates a new link label
linkLabel[count] = new LinkLabel();
// Alters name info for display and file calling
filepath = filFile.FullName;
extension = filFile.Extension;
filename = filFile.Name.Remove(filFile.Name.Length - extension.Length);
// Write to the textbox for functional display
textBox1.AppendText(filename + "\r\n");
// Alters link label settings
linkLabel[count].Text = filename;
linkLabel[count].Links.Add(0, linkLabel[count].Text.ToString().Length, filepath);
linkLabel[count].LinkClicked += new LinkLabelLinkClickedEventHandler(LinkedLabelClicked);
// Adds link label to table display
tblDisplay.Controls.Add(linkLabel[count]);
// Indexes count up for arrays
count = count + 1;
}
}
private void LinkedLabelClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start(filepath);
}
}
}
My goal is to generate a table of links to all of the media files that I add at launch, and have the links open the files in their respective players.
As of right now, it generates all of the links properly, but whenever I click on any of them, it launches the last item in the list.
For example, if the list contains "300", "Gladiator", and "Top Gun", no matter which link I click, it opens "Top Gun".
I assume that this has to do with it calling the variable "filepath" in the click event, which is left in it's final state. However, I'm not exactly clear on how to create a static link value or action on each individual link, as all of the answers I've researched are in regards to single linklabel situations, not dynamic set-ups.
Any help/advice would be appreciated!
Try as below:
In foreach loop add one line more like:
linkLabel[count].Tag = filepath;
then in click event get this path as blow,
private void LinkedLabelClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string filepath = ((LinkLabel)sender).Tag.tostring();
System.Diagnostics.Process.Start(filepath);
}

Want to show the results of a page in another page?

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.

Categories

Resources