I'm trying to simply select one string line out a long list strings that are held on a server and seperated with a pipe character. This string is grabbed by a php script and the string line is a list of all the media and folders I have on my server.
In my code I'm getting this information and returning it with the following code:
using (var client = new WebClient())
{
result = client.DownloadString("http://server.foo.com/images/getDirectoryList.php");
}
textBox1.Text = string.Join(Environment.NewLine, result.Split('|'));
And it looks like this:
But when I try to simply click on one of them, my cursor simply just goes to where I've clicked. Like this, I tried to select md-harrier.jpg and my cursor just ends up at the end of jpg:
What I'm really wanting is pictured below. I click on Koala.jpg and the whole thing is highlighted and I have the ability to store the name of what it is I've just clicked on. TO achieve that screen shot I had to click next to Koala.jpg and then drag my mouse along.
Is there anyway I can achieve what I want to achieve?
The key thing to note about this is that I will have no idea how many files will be on the server, nor what they will be called. My php script is grabbing this information and displaying it in my winform text box using the code I have wrote above.
as Simon said you need a ListBox, a ListBox fits here because it allows you to select a line, and you can register to the event of SelectedIndexChanged and store the name that was selected.
to initiate the values do
using (var client = new WebClient())
{
result = client.DownloadString("http://bender.holovis.com/images/getDirectoryList.php");
}
listBox1.Items.AddRange(result.Split('|'));
listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged);
and on the selectedItemChanged:
string currVal;
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
currVal = (string)listBox1.SelectedItem;
}
As you said you have no reason to use TextBox,then by using ListBox you can achieve that in this way;
using (var client = new WebClient())
{
result = client.DownloadString("http://bender.holovis.com/images/getDirectoryList.php");
}
string[] names=result.Split('|');
foreach(string name in names)
{
if(name!="|"&&name!=" ")
{
listbox.Items.Add(name);
}
}
Additionally,if you would like to store selected item in a variable subscribe to ListBox's SelectionChangedEvent and store the selection index in a variable in this way;
int selection=;
private void ListBox1_SelectionIndexChanged(object sender,EventArgs e)
{
selection=ListBox1.SelectedIndex;
}
Related
I'm creating an application to scan barcode tickets. When you start the app a list of available shows has to be shown on the screen. To get all the available shows I'm using a webservice which returns me a List<Event>. How do I create a list of buttons with each button representing a show/event from inside the xaml.cs? When clicking the button a new page will be shown where the user can scan the tickets from that show. I'm pretty new to Xamarin.Forms and I quite don't understand how to use the paging/content views. I already searched a lot but the closest to what I need was this: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/get-started-with-xaml?tabs=vswin
Unfortunatly it only shows how to add a certain amount of controls. And not a dynamicly generated amount.
Many thanks in advance!
In xaml insert a stacklayout where you want your buttons to appear. Remember you can also play whith its Orientation and Spacing properties. So:
<StackLayout x:Name="MyButtons"/>
Then in code-behind generate your dinamic buttons list. Put the code in constructor AFTER InitializeComponent(); or somewhere else:
var myList = new List<*Event or something*>(); //your list here
MyButtons.Children.Clear(); //just in case so you can call this code several times np..
foreach (var item in myList)
{
var btn = new Button()
{
Text = item.*your property*, //Whatever prop you wonna put as title;
StyleId = item.*your ID property* //use a property from event as id to be passed to handler
};
btn.Clicked += OnDynamicBtnClicked;
MyButtons.Children.Add(btn);
}
Add a handler:
private void OnDynamicBtnClicked(object sender, EventArgs e)
{
var myBtn = sender as Button;
// who called me?
var myId = myBtn.StyleId; //this was set during dynamic creation
//do you stuff upon is
switch (myId)
{
case "1": //or other value you might have set as id
//todo
break;
default:
//todo
break;
}
}
I'm new to C# and trying to understand how things work. So I created a two forms. First one has a textbox and the second one has a combobox with a button that sends offer help to that computer. From the text box I add computer names. once I click the OK button it loads all my computer names to the combobox.
string[] computerlist = txtComputers.Text.Split(new[]{'\n'}, StringSplitOptions.RemoveEmptyEntries);
frmHome _frmhome = new frmHome();
_frmhome.cbComputerList.Items.AddRange(computerlist);
_frmhome.ShowDialog();
_frmhome.Dispose();
When I select a computer from the dropbox and click Offer_help button, offer remote window comes up saying its trying to connect to the user but then fails.
private void Offerhelp_Click(object sender, EventArgs e)
{
CompName = cbComputerList.SelectedItem.ToString();
var _offerhelp = new ProcessStartInfo();
_offerhelp.FileName = "msra.exe";
_offerhelp.Arguments = String.Format("/offerRA" + " " + CompName);
Process.Start(_offerhelp);
}
I tried running in debug mode and I see that "CompName" variable is
"/offerRA Lab1\r"
if I remove the "\r" it actually works.
Can anyone tell me why this is happening? Also, Is there a way I can create a new class for the selected item and make it a global variable so I can use it say if I create 4-5 forms and use that computer name in all forms?
Thanks in advance.
Your line
string[] computerlist = txtComputers.Text.Split(new[]{'\n'}, StringSplitOptions.RemoveEmptyEntries);
Is the issue. \n is the newline operator, and \r is carriage return. Depending on OS / Program, you can use \r\n to determine a 'NewLine'.
Use
string[] computerlist = txtComputers.Text.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
Environment.NewLine will return the proper character.
EDIT: In terms of your comment, add a static property to your form:
class MyForm
{
public static string SelectedComputer { get; set;}
}
you can then reference this anywhere by
MyForm.SelectedComputer
Set this variable on your cbComputerList.SelectedIndexChanged event. Just check to make sure the value is greater than 0 then set it.
When programming a Windows Forms application I found myself having to create a variable amount of text fields according to the number of inputs.
I decided to name these name1, name2, name3, ..., nameN.
Now I want to be able to save the user's input to a text file. To do this I need to get the text from the text boxes into separate variables to be able to write this to the text file.
This would result in a for loop like this:
for(i=0; i < totalnames; i++)
{
string varname= "name" + i;
}
But this way I cannot get the value from the text boxes. How can I get the separate values from the text boxes to write them to the text file?
Thank you,
When you create the form controls, keep references to them in a list:
// probably at the class level...
List<TextBox> myTextBoxes = new List<TextBox>();
// then when you create them...
myTextBoxes.Add(name1);
// etc.
Then later, when you need to reference them, use the list:
foreach (var textBox in myTextBoxes)
{
// get the value from the text box and use it in your output
}
You can create a List of string List and add your name in it. Then use StreamWriter to add the name in your file:
List<string> myListOfNames = new List<string>();
int totalnames = 10;
for (int i = 0; i < totalnames; i++)
{
myListOfNames.Add("name" + i);
}
using (StreamWriter writer = new StreamWriter("C:\\MyTextFile.txt", true))
{
foreach (string name in myListOfNames)
{
writer.WriteLine(name);
}
}
Here is my two pennies worth, because the OP originally said Windows Form Application - I would have a Save button, which when fired, the code behind will grab all the Textboxes and save to the file. You can add your own filtering for textboxes yourself if you want.
Firstly here is the code behind for the button event:
private void saveToFile_Click(object sender, EventArgs e)
{
using (StreamWriter writer = new StreamWriter("C:\\k\\saveToFile.txt", true))
{
if (this.Controls.Count > 0)
{
var textBoxes = this.Controls.OfType<TextBox>();
foreach (TextBox textbox in textBoxes)
{
writer.WriteLine(textbox.Name + "=" + textbox.Text);
}
}
}
}
A simple forn to prove the point, each TextBox has a name of name1 etc.
Also here is an example output of the file:
Improvements
Filtering on the Textboxes - you may only want to do this for some textboxes for a particular name.
Loading the file. I have added the textbox name to the file, so theorically you could load the data back into the textboxes.
I've been working on the past couple of days on a ListView based Music player using NAudio in C#. It's now time for me to start working on the forward/previous functions but I've come to a bit of a bump in the road. I need to select whatever the next item in the listView I have is. However, it is not selected by the user but instead is marked as now playing by a checkmark next to it with the default ListView checkboxes.
Here's what it looks like:
I've got a public string that's accessible by anything; it has the filename of the currently playing track in it. Whenever I click to play a track, I've got a foreach loop that loops through all of the items in this listView (I've got a second listview in another tab that has all the music I click to play from) and if the filename subitem and currentlyPlaying string match, then it checks it. If not, it unchecks.
I've got an event handler in my mainclass for when the playback stops on the track. What's going to go in there will be the logic for the next track. I've got a general idea of what to do but I'm not sure how to go about doing it
Get the index of the item with the check mark next to it
Get the item after it
Retrieve its fileName subitem
Play it
So what would be the way to go about doing this? I'm still a bit confused with listViews and such.
Update: Also, how possible is it to disable the user checking the check box, I've got it down for when it's a double click but what about when the user checks the checkbox themselves?
Update 2: Here's the eventhandler with some scratch code I was working on
public void waveOutDevice_PlaybackStopped(object sender, StoppedEventArgs e)
{
string fileName;
foreach (ListViewItem lvi in playListView.Items)
{
fileName = lvi.SubItems[1].Text;
if(lvi.Checked == true)
{
int finIndex;
lvi.Checked = false;
finIndex = lvi.Index;
//finIndex + 1;
}
}
}
I think you are just about there. all you need to do is something like this:
public void waveOutDevice_PlaybackStopped(object sender, StoppedEventArgs e)
{
string fileName;
foreach (ListViewItem lvi in playListView.Items)
{
fileName = lvi.SubItems[1].Text;
if(lvi.Checked == true)
{
int finIndex;
lvi.Checked = false;
finIndex = lvi.Index;
finIndex++;
if(finIndex < playListView.Count())
{
var nextGuy = playListView.Items[finIndex];
nextGuy.Checked = true;
//Play the file and what not.
}
}
}
}
Recently I've been quite enjoying C# and I'm just testing with it but there seems to be one part I don't get.
Basically I want it so that when I click the SAVE button must save all the items in the listbox to a text file. At the moment all it comes up with in the file is System.Windows.Forms.ListBox+ObjectCollection.
Here's what I've got so far. With the SaveFile.WriteLine(listBox1.Items); part I've tried putting many different methods in and I can't seem to figure it out. Also take in mind that in the end product of my program I would like it to read back to that to that text file and output what's in the text file to the listbox, if this isn't possible then my bad, I am new to C# after all ;)
private void btn_Save_Click(object sender, EventArgs e)
{
const string sPath = "save.txt";
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
SaveFile.WriteLine(listBox1.Items);
SaveFile.ToString();
SaveFile.Close();
MessageBox.Show("Programs saved!");
}
From your code
SaveFile.WriteLine(listBox1.Items);
your program actually does this:
SaveFile.WriteLine(listBox1.Items.ToString());
The .ToString() method of the Items collection returns the type name of the collection (System.Windows.Forms.ListBox+ObjectCollection) as this is the default .ToString() behavior if the method is not overridden.
In order to save the data in a meaningful way, you need to loop trough each item and write it the way you need. Here is an example code, I am assuming your items have the appropriate .ToString() implementation:
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
foreach(var item in listBox1.Items)
{
SaveFile.WriteLine(item.ToString());
}
Items is a collection, you should iterate through all your items to save them
private void btn_Save_Click(object sender, EventArgs e)
{
const string sPath = "save.txt";
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
foreach (var item in listBox1.Items)
{
SaveFile.WriteLine(item);
}
SaveFile.Close();
MessageBox.Show("Programs saved!");
}
There is one line solution to the problem.
System.IO.File.WriteAllLines(path, Listbox.Items.Cast<string>().ToArray());
put your file path+name and Listbox name in above code.
Example:
in Example below path and name of the file is D:\sku3.txt and list box name is lb
System.IO.File.WriteAllLines(#"D:\sku3.txt", lb.Items.Cast<string>().ToArray());