Combox selecteditem adding extra letter - c#

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.

Related

How to remove/delete Button text on when check button is clicked?

I am making this sum creator where user will have to type an answer using custom keyboard. and on check button click if answer is correct then new question is loaded.
My problem is after answering first question answer button reset to blank but when user types next answer, only one last alphabet is deleted (for example 5 from 15). and when i type 14 it shows 114 (1 from previously typed answer).
I need help to reset answer button text to blank.
I am using buttons because later i want to add more questions at the same time so user will have multiple answers to click and type.
Can anyone please help me on this? Also tell me if this is the right method to achieve what i want.
I am calling backspace function to delete previous answer and also setting text to blank.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Keyboard : MonoBehaviour
{
string word = null;
int wordIndex = -1;
string alpha = null;
string alpha2 = null;
public Text userAnswer1 = null;
public Text valueA, valueB;
public Text scoreCount;
private int a, b, answer1, score;
char[] nameChar = new char[5];
private void Start()
{
SumCreator();
}
public void nameFunc (string alphabet)
{
wordIndex++;
char[] keepchar = alphabet.ToCharArray();
nameChar[wordIndex] = keepchar[0];
alpha = nameChar[wordIndex].ToString();
word = word + alpha;
userAnswer1.text = word;
}
public void BackspaceFunction()
{
if (wordIndex >= 0)
{
wordIndex--;
alpha2 = null;
for (int i = 0; i < wordIndex + 1; i++)
{
alpha2 = alpha2 + nameChar[i].ToString();
}
word = alpha2;
userAnswer1.text = word;
}
}
public void SumCreator ()
{
a = Random.Range(0,15);
b = Random.Range(0,15);
answer1 = a + b;
valueA.text = a.ToString();
valueB.text = b.ToString();
scoreCount.text = "score " + score.ToString();
}
public void CheckAnswer()
{
Text buttonText = userAnswer1.GetComponentInChildren<Text>();
if (answer1 == int.Parse(userAnswer1.text))
{
score++;
// userAnswer1.text = string.Empty;
buttonText.text = string.Empty;
}
SumCreator();
}
}
I've edited my answer and removed the now irrelevant parts.
Once the button "Check" is clicked, first of all erase the text in the result textbox, then do the whole other logic.
To erase the text you can use next piece of code:
Text buttonText = buttonName.GetComponentInChildren<Text>();
buttonText.text = string.Empty;
You probably want to have this "buttonText" property as a global and get it once, at the start of the program instead of getting it every time the button is clicked. It won't do much difference in a small scale program, but it's a right way of thinking.
After checking your code a bit more, I can summarize your problem:
The whole logic of your program is flawed, there're many unnecessary complicated things which make it fail in several places. It is understandable, everybody goes through this stage, nothing to be ashamed or worried about. Either way it's my subjective opinion, which may be wrong.
Back to your code, all you have to do is update your result text, say "txtResult", once anything happens.
Once you click a number, do "txtResult += numberClicked".
Once you click backspace, remove last char of txtResult. Here is a question with many answers on how to do it, it's really simple.
Once you click "Check", in case it's the right number, set txtResult to empty.
Also, every time you update txtResult, you're supposed to update the UI too of course. Let's say you do it every time, it would be one line to update txtResult, and one line to update UI for each of the above 3 cases. So in total 6 lines. A check for an empty string while in "Backspace" function adds another line. My math could be wrong, but either way, it's quite short and simple approach, nothing too complicated.
You just lack relevant knowledge, otherwise you wouldn't be doing that nightmare in your Backspace function.
Regarding the "nameFunc" function, the whole 6 lines could be replaced with "txtResult += alphabet", isn't it? I'm not sure what you get in alphabet parameter, but either way, string is an array of chars, so you can also do "txtResult += alphabet[0]" instead of what you have there.
So, in total, you got it all right, the logic was right, you figured the main aspects. But you over complicated the whole thing. I believe you'll be fine after reading all this text, and wish you the best.
If you want to clear your Text object when you have succesfully entered your answer, you should not call your "BackSpace" function.
Just replace your code to this:
if (answer1 == int.Parse(userAnswer1.text))
{
score++;
userAnswer1.text = string.Empty;
This will clear the text element.
You could also look into using InputFields in Unity, which are designed for entering input and automatically support backspace and other keyboard functions.
If you do, make sure that you set the InputField's ContentType to either Integer Number or Decimal Number

Why does the listing order of my com ports in a comboBox always change? C#

I have the problem that my comports always change their order in the list.
I have a ComboBox where you can select one of 8 com ports (usb scales) and connect to the selected one. After that, I am saving the the selected index of the ComboBox and load it when the form loads next time. But when it is loading it is always listing the ports in an other order, so that the wrong port is selected when SelectedIndex is loaded in to the ComboBox. How can I solve this?
saving the actual port selected in ComboBox :
File.WriteAllText("portsave1", textBox18.Text + "+" + comboBox2.SelectedIndex.ToString());
on form Load:
//Load Com Port List into comboBoxes
string[] portNames = SerialPort.GetPortNames(); //<-- Reads all available comPorts
foreach (var portName in portNames)
{
comboBox2.Items.Add(portName); //<-- Adds Ports to combobox
comboBox3.Items.Add(portName);
comboBox5.Items.Add(portName);
comboBox7.Items.Add(portName);
comboBox9.Items.Add(portName);
comboBox12.Items.Add(portName);
comboBox14.Items.Add(portName);
comboBox16.Items.Add(portName);
}
if (File.Exists("startstate1"))
{
checkBox8.Checked = bool.Parse(File.ReadAllText(#"startstate1"));
if (checkBox8.Checked)
{
//Loading the scale name and com ports Scale1 / TAB 1
if (File.Exists("portsave1"))
{
StreamReader sr2 = new StreamReader("portsave1");
string portload = sr2.ReadToEnd();
String[] portstrings1 = portload.Split(new string[] { "+" }, StringSplitOptions.None);
if (portstrings1[0] != string.Empty)
{
textBox18.Text = portstrings1[0];
tabPage1.Text = portstrings1[0];
button13.Text = portstrings1[0];
}
int comport = Convert.ToInt32(portstrings1[1]);
try
{
comboBox2.SelectedIndex = comport;
}
catch (Exception)
{
MessageBox.Show("Ein gespeicherter Port ist nicht mehr vorhanden", "Information",
MessageBoxButtons.OK, MessageBoxIcon.Information);
comboBox2.ResetText();
}
sr2.Close();
}
//connect to the scale on the port loaded into comboBox
button1_Click(null, null);
}
}
I hope someone can help me. Thank you.
Don't select your data using an index stored from a previous session.
You need to change how you are setting the selecting data in your combobox since index is unreliable between sessions. Instead you should look for a match for the text you desire and have that selected.
Instead of:
int comport = Convert.ToInt32(portstrings1[1]);
comboBox2.SelectedIndex = comport;
use this:
string comport = portstrings1[1];
comboBox2.SelectedIndex = comboBox2.FindStringExact(comport);
From MSDN on the method FindStringExact.
Finds the first item in the combo box that matches the specified
string.
In order for this to work you will need to modify how you are saving the selected data. Save the selected text value of the combobox instead of the index.
File.WriteAllText("portsave1", textBox18.Text + "+" + comboBox2.Text);
Bonus Note:
You should really consider using more verbose naming conventions for your controls which you are accessing via code. combobox2 doesn't mean much. A name like comboboxUSBScalePort makes your code more readable and will make future maintenance a lot easier.
Remember, the point of code is to be human readable.
OK, Thank you at all, I solved the problem. All your Code is correct and there are many way's, like comboBox.Text, comboBox.Item to save that.... My problem was that, I saved it twice, once after connecting to the scale and once when the Form is closing... And when Form was closing it wrote the selected index into the file so that is why it couldn't work. I didn't noticed that and was wondering why its not working. Thank you!

How do I set a textbox's text to a line in a file contained in a string?

Here's the code:
public Form1()
{
string[] reader = File.ReadAllLines(#"F:\Bioshock2SP.ini");
foreach (string lines in reader)
{
if (lines.Contains("VoVolume="))
{
lines.Substring(lines.Length -2);
TextBox.Text = lines; //Exception
}
}
InitializeComponent();
}
I'm trying to find a line in a file and make only the actual setting part of the file show in the textbox. For example I want to find the line containing "VoVolume=55", but I only want, "55" to show in the textbox or even just, "1.534".
I keep getting an exception when I launch the program.
Any ideas?
Exception Details:
NullReferenceException was unhandled.
An unhandled exception of type 'System.NullReferenceException'
occurred in EditingTextFromFile.exe
Additional information: Object reference not set to an instance of an
object.
Ok. First, you can't use the textBox if it hasn't been initialized. You need to make sure InitializeComponent is run first. This is what is causing your exception. Second, that Substring is not doing anything as you're not using the output value.
Here is your code slightly altered to correct those two issues :
public Form1()
{
InitializeComponent();
string[] reader = File.ReadAllLines(#"F:\Bioshock2SP.ini");
foreach (string lines in reader)
{
if (lines.Contains("VoVolume="))
{
lines = lines.Substring(lines.Length - 2);
TextBox.Text = lines.Split(new string[] { "=" }, StringSplitOptions.None).Last();
}
}
}
And TextBox is a terrible name for a TextBox instance.
Edit : I've used the code from Mike's answer.
TextBox is a class, not an instance.
If you drag and drop a TextBox into form, you can find the Name property, like: textBox1
Then you can try following code:
textBox1.Text = lines.Split(new string[] { "=" }, StringSplitOptions.None).Last();
See link sample:
Reading/writing an INI file
I think my code run ok
var MyIni = new IniFile(#"F:\Bioshock2SP.ini");
TextBox.text = MyIni.Read("VoVolume");

Select one string line in a list

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

TextBlock refuses ~70% of the time to make a hyperlink

Really really odd problem, in short, I'm doing a foreach over every word in a textblock, if that word starts with for example "#" I want to make a username hyperlink out of it. However in about 70% of the cases it replaces the text fine, but it just doesn't become a hyperlink.
Partial code:
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
var kaas = Tweet.Split(' ');
foreach (string a in kaas)
{
if (a.StartsWith("#"))
{
Hyperlink uname = new Hyperlink();
uname.NavigateUri = new Uri("http://twitter.com/" + "xarinatan");
uname.RequestNavigate += new RequestNavigateEventHandler(Hyperlink_RequestNavigateEvent);
uname.Inlines.Add("ASDAS");
TweetBlock.Inlines.Add(uname);
//TweetBlock.Inlines.Add(Username(a));
TweetBlock.Inlines.Add(" ");
}
}
}
Above code turns all instances that start with "#" into "ASDAS" but fails most of the time to properly convert it to a hyperlink, HOWEVER it DOES convert it SOMETIMES.
It's completely beyond me how it only works sometimes, instead of all the time or not at all.
All suggestions are welcome!
edit: To clarify, it -always- replaces the text with 'ASDAS', but in 70% of the cases it doesn't become a hyperlink.
My friend found the answer. Somehow inlines being added as string causes sporadic behavior, they have to be added as a 'Run'.
Fix can be found here: https://github.com/zahndy/o3o/commit/68b50f8c0ea106bcc709d3f69658b28da9c8a9d4#diff-3
Thanks all for the suggestions!

Categories

Resources