Unable to access element of Array [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Upon tick of my timer i am reading 9 byte of data from my sensor, i am converting the read string to HEX form the data is 01-03-04-0A-D5-15-A9-26-FD
right now the only data concerned with me is 4th & 5th element i am using split command to split my string but still i am unable to access exception pops out Indexoutofrangeexception, when itry to access 4th element by index 3,
private void timer1_Tick(object sender, EventArgs e)
{
// timer1.Enabled = false;
serialPort1.Write(query, 0, query.Length);
incoming = serialPort1.ReadExisting();
ba = Encoding.Default.GetBytes(incoming);
var hexString = BitConverter.ToString(ba);
textBox1.Text = incoming;
textBox2.Text = hexString;
string[] splittedResult = hexString.Split('-');
textBox3.Text = splittedResult[3];
//label1.Text = splittedResult[1];
// textBox3.Text = Convert.ToString(hexString.Length);
timer1.Enabled = true;
}

Maybe hexString is null or it's value is shorter than you think. Try this:
...
string[] splittedResult = hexString.Split('-');
if (splittedResult.Length >=4 ) // check lenght
textBox3.Text = splittedResult[3];
...

Related

How to roll a list of numbers (list of numbers are in a notepad ) randomly in a lable [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I want to retrieve data from notepad and display it randomly on label. The project is about lucky draw system where i need to make the employee id display randomly.
Below are my code:
protected void Button1_Click(object sender, EventArgs e)
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("C:/ Users / Nor Asyraf Mohd No / Documents / TestFile.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
string strRead = sr.ReadLine();
Random random = new Random();
Label1.Text = strRead.ToString();
}
}
}
catch (Exception i)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(i.Message);
}
}
There are a couple of things wrong with your code. First, you should declare your Random variable once rather than inside a loop. Since Random uses the system time as a seed, if it's initialized inside a loop that's running quickly, you will likely get the same "random" number each iteration. I usually just declare it as a class field so it can be used by other methods as well.
Similarly, you can store the file path as a class level variable rather than each time the method is called. And if the file contents aren't changing, you should consider saving them in a List<string> class field one time at startup, rather than reading the file each time. But I'm going to assume that the file contents may change, so I'll leave that code in the method.
Next, you can use the File.ReadAllLines to get all the lines of the file at once, and then you can access a random index in the resulting string array of file lines.
In order to ensure you don't display the same item more than once, you can read the file lines once into a List<string>, and then, after you choose a random item from that list, remove it so it isn't used again.
For example:
private Random random = new Random();
private string testFilePath = #"c:\users\nor asyraf mohd no\documents\testfile.txt";
private List<string> testFileLines;
private void Form1_Load(object sender, EventArgs e)
{
if (!File.Exists(testFilePath))
{
MessageBox.Show($"The file does not exist: {testFilePath}");
}
else
{
try
{
testFileLines = File.ReadAllLines(testFilePath).ToList();
}
catch (Exception ex)
{
MessageBox.Show($"Could not read file {testFilePath}. Exception details: {ex}");
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (testFileLines != null && testFileLines.Count > 0)
{
var randomLine = testFileLines[random.Next(testFileLines.Count)];
Label1.Text = randomLine;
testFileLines.Remove(randomLine);
}
}

c# when pressing a button add totals together [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
When i press "buttonTotal" i need it to add fuel prices together. I have lblDailyPrice, lblTotalLitresEntered and i have 3 buttons "unleaded"; "Diesel"; "Premium"... any help as to how i can achieve this?
private void btnTotal_Click(object sender, EventArgs e)
{
try
{
if(btnUnleaded_Click)
{
}
else if (btnDiesel_Click)
{
}
else if (btnPremium_Click)
{
}
}
catch
{
}
}
I would advise making the "unleaded", "Diesel", "Premium" options RadioButtons instead of Buttons and bind them under a container like Panel. So, when the user presses the "buttonTotal" the program will check which RadioButton is checked and then calculate the corresponding value.
private void btnTotal_Click(object sender, EventArgs e)
{
double totalPrice = 0;
if(unleadedRadioButton.Checked)
{
totalPrice = lblDailyPrice * lblTotalLitresEntered * unleadedValue;
}
else if (dieselRadioButton.Checked)
{
totalPrice = lblDailyPrice * lblTotalLitresEntered * dieselValue;
}
else if (premiumRadioButton.Checked)
{
totalPrice = lblDailyPrice * lblTotalLitresEntered * premiumValue;
}
}
I'm assuming your using Windows Forms. I have linked relevant documentation on how to accomplish this task. With just a tiny bit of reading, it should be easy. Good luck and welcome to StackOverflow!.
Get the prices from the labels.
Convert those strings into a number type with a decimal.
Then just do the math on the resulting variables.
Example:
var total = Convert.ToDecimal(lblDailyPrice.Text) * Convert.ToDecimal(lblTotalLitresEntered.Text);

C# TextBox that allows a maximum of one dot [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
How can I make a TextBox in C# to allow a maximum of one . (dot)?
Thus, abcdef and abc.def would be valid inputs whereas ab.cd.ef wouldn't.
By allow I mean that the user should not be able to enter a dot if there is already one in the text field.
Java has DocumentFilters for that purpose, is there something similar in C#?
I guess this is for validating user inputs. You should create a button and tell the user when he is done, press it so that you can check whether there is only one . in the string.
Assumptions:
Let your text box be called tb. Let your button's Click event handler be BtnOnClick.
Now we can start to write code. First create the handler:
private void BtnOnClick (object sender, EventArgs e) {
}
In the handler, you need to loop through the string and check each character. You can use a foreach for this:
int dotCount = 0;
string s = tb.Text;
if (s.StartsWith(".")) //starts with .
//code to handle invalid input
return;
if (s.EndsWith(".")) //ends with .
//code to handle invalid input
return;
foreach (char c in s) {
if (c == '.') {
dotCount++;
}
if (dotCount >= 2) { //more than two .
//code to handle invalid input
return;
}
}
// if input is valid, this will execute
Alternatively, you can use a query expression. But I think you are unlikely to know what that is.
string s = tb.Text;
if (s.StartsWith(".")) //starts with .
//code to handle invalid input
return;
if (s.EndsWith(".")) //ends with .
//code to handle invalid input
return;
var query = from character in s
where character == '.'
select character;
if (query.Count() > 1) {
//code to handle invalid input
return;
}
// if input is valid, this will execute

please help me to my search button [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
What is the problem to my code? It always results in "No record found!" even if what am I searching is correct.
private void button3_Click(object sender, EventArgs e)
{
string[] lines = System.IO.File.ReadAllLines(#"C:\Users\kulet\Desktop\file.txt");
System.Console.WriteLine("Contents of file.txt = ");
foreach (string line in lines)
{
if (textBox14.Text == line)
{
label28.Text = "File exists!";
}
else
{
label28.Text = "No record found!";
}
Console.WriteLine("\t" + line);
}
You should place a break; after you found a match, since now it will always show the match of the last line:
label28.Text = "File exists!";
break;
The break will bail out of the foreach.

Matching brackets and indentation in RichTextBox using C#? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to make a Code Editing control that can format text somewhat like Visual Studio,till now i have implemented syntax highlighting and autocompletion but i want to format text in nested curly braces.For example:Consider a for loop,
for(int i=0;i<=10;i++)
{
Function_One(); //This should be a tab away from first brace
Function_Two(); //So with this
if(a==b) //So with this
{ //This should be four tabs away from first brace
MessageBox.Show("Some text");//This should be six tabs away from first brace
} //This should be four tabs away from first brace
}
now what i want is that this should look something like this,
for(int i=0;i<=10;i++)
{
Function_One();
Function_Two();
if(a==b)
{
MessageBox.Show("Some text");
}
}
I have already tried Regular Expressions but at some point they fail to match,so i tried to match it with code but code cannot match very deeply nested code or is very hard to implement
,so is there any way to achieve this,and one more thing i am doing all this in Winforms control RichTextBox using C#.
This is by no means a simple feat, I am unaware of any tools or plugins that you would be able to take advantage of, my only recommendation is to research Monodevelop's implementation of this.
See MonoDevelop's github for details.
I think the best way to implement this would be to create some global variables for your form:
private int _nestedBracketCount = 0;
private const string TabString = " ";
private const int TabSpaces = 4;
And then handle all of it in a KeyPressed event handler for the rich text box:
private void richTextBox1_OnKeyPress(object sender, KeyPressEventArgs e) {
var currentLength = richTextBox1.Text.Length;
if (e.KeyChar == '{') {
// need to increment bracket counter
_nestedBracketCount++;
} else if (e.KeyChar == '}') {
// remove last #(TabSpaces) characters from the richtextbox
richTextBox1.Text.Remove(currentLength - TabSpaces);
_nestedBracketCount--;
richTextBox1.AppendText("}");
e.Handled = true;
} else if (e.KeyChar == (char)13) {
// append newline and correct number of tabs.
var formattedSpaces = string.Empty;
for (var i = 0; i < _nestedBracketCount; i++)
formattedSpaces += TabString;
richTextBox1.AppendText("\n" + formattedSpaces);
e.Handled = true;
}
}
I think this should provide you with a halfway decent starting point.

Categories

Resources