I've been coding in C# (winforms) for a project for 2 weeks now. My goal is to build a GUI for an FFT-Analysis (frequency-realm).
my Problem:
I keep running into the same problem: i receive 1024 int values (one blocksize) separated by white spaces in one string via serial port and then terminated by \n into a buffer uart_buf. To obtain numeric values, i use uart_buf.split(' ') into a string[] parse_buf and then try to access a single value in ASCII-format like this: parse_buf[i] = val_buf. This i then try to form into a numeric via value = int.Parse(val_buf), without success: System.ArgumentNullException: value cant be NULL.
What I've tried:
value = int.Parse(parse_buf[i]); This returns a format exception
printing parse_buf[i] to a textbox shows an expected value (the received data is correct)
observing the main buffer uart_buf shows valid data like this: "41 30 2 0 0 0 0 0 0 0 3 40 500 69..."
starting from index 1 (or any other) instead of 0 changes nothing
What I don't get:
A single element (ergo a string) of parse_buf contains a value in text-form, e.g. "41". I want to save it to a regular string val_buf, which i should be able to parse to int. Why is every string accessed via parse_buf[i] null?
Code-Fragments:
private void displayData(object o, EventArgs e)
{
parse_buf = uart_buf.Split(' ');
tb_data.Text = parse_buf[0]; //this shows valid data in a tb
for (i = 1; i < parse_buf.Length; i++) //about 1024 loops
{
//problem area:
parse_buf[i] = val_buf;
fft = int.Parse(val_buf);
//ignore this:
f = i * 20;
chart1.Series[0].Points.AddXY(f, fft);
}
}
I usually work in C with embeded systems, so sorry for not seeing the problem instantly. Thanks.
private void DisplayData(object o, EventArgs e)
{
parse_buf = uart_buf.Split(' ');
tb_data.Text = parse_buf[0]; //this shows valid data in a tb
for (i = 0; i < parse_buf.Length; i++) //about 1024 loops
{
//problem area:
int.TryParse(parse_buf[i], out ftt);
//ignore this:
chart1.Series[0].Points.AddXY(i * 20, fft);
}
}
Related
I am creating a program that reads a text file and gets the data then puts it into an array. My problem is that there are instances where a column is intended to be blank but the blank value must still be considered as a value but when my program reads the blank column, it reads the next value and puts it in the array where the value should be 0 or blank. I have tried to count the spaces between each column to make it a condition but the spaces are not reliable since the data varies in length. Any ideas about how I might do this?
Here is what my text data looks like.
Data1 Data2 Data3
1.325 1.57 51.2
2.2 21.85
12.5 25.13
15.85 13.78 1.85
I need my array to look like this
firstRow['1.325','1.57','51.2'];
secondRow['2.2','0','21.85'];
If your file is tab-splitted, use line.Split("\t") to get array of substrings of each line. Then, each substring you can convert into you data type. In your case it must be nullable, e,g, decimal?.
Here's a starting point if you have a list of headers in the order they appear in the data and if your values are always aligned to the headers.
import io, csv, sys
data = '''\
Data 1 Data 2 Data 3
1.325 1.57 51.2
2.2 21.85
12.5 25.13
15.85 13.78 1.85
'''
headers = ['Data 1', 'Data 2', 'Data 3'] # order should match headers
f = io.StringIO(data)
h = f.readline()
indexes = [h.find(s) for s in headers]
rows = []
for line in f:
line = line[:-1] # strip trailing linefeed
d = {}
for key, index in list(zip(headers, indexes))[::-1]: # slice from the right
val = line[index:]
line = line[:index]
d[key] = val.strip()
rows.append(d)
writer = csv.DictWriter(sys.stdout, headers)
writer.writeheader()
writer.writerows(rows)
Since I have ran out of time, what I did was to count the number of spaces and if the spaces exceed by a number (in my case, 10) I'll add a value empty value in my array
string[] lsData = pData.Split(' ');
string[] lsData1 = new string[18];
int newArrayData = 0;
int spaceCounter = 0;
for (int i = 0; i < lsData.Length; i++)
{
if (lsData[i] != "")
{
lsData1[newArrayData] = lsData[i];
newArrayData++;
spaceCounter = 0;
}
else
{
spaceCounter++;
}
if (spaceCounter >= 10)
{
lsData1[newArrayData] = "";
newArrayData++;
spaceCounter = 0;
}
}
I have the following code:
string checkedItemListBoxPName;
string checkedItemListBoxPID;
int selectedProcessIndex;
private void processes_checkedListBox_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (e.NewValue == CheckState.Checked)
{
for (int j = 0; j < processes_checkedListBox.Items.Count; ++j)
{
if (e.Index != j)
{
processes_checkedListBox.SetItemChecked(j, false);
}
}
selectedProcessIndex = processes_checkedListBox.SelectedIndex;
MessageBox.Show(selectedProcessIndex.ToString());
string checkedProcess = processes_checkedListBox.Items[selectedProcessIndex].ToString();
string[] checkedProcessElements = checkedProcess.Split(new string[] { ".exe" }, StringSplitOptions.None);
checkedItemListBoxPName = checkedProcessElements[0];
checkedItemListBoxPID = checkedProcessElements[1].Trim();
MessageBox.Show(checkedProcessElements[0].ToString());
MessageBox.Show(checkedItemListBoxPID.ToString());
}
}
This method is called when I check a checkbox from my checkBoxList. In the beginning I am unchecking all the other previous checked boxes so that I will always have just one checked.
In selectedProcessIndex I store the index of the checked box so that I can access its text a little while after in string checkedProcess = processes_checkedListBox.Items[selectedProcessIndex].ToString();.
Everything works fine except the fact that when I check the very first box (index = 0) or the 33rd box, I receive System.IndexOutOfRangeException: Index was outside the bounds of the array.
I don't know what is going on with those specific positions. Why 0 and 33 can't be handled.
I have 35 checkboxes total, from 0 to 34, as I said.
The data from those positions is just like the other, it is visible, and has nothing special.
Any suggestion is appreciated!
I think you get this error because when you check your elements on position 0 and 33 the method checkedProcess don't return a string containing the chars ".exe". The algorithm tries to split your string. If there isn't found any ".exe" in it .split() will return an array with only one element on position zero. In this case the new splitted array is the old unsplitted string).
checkedProcessElements[1].Trim(); tries to read a value outside the arrays range because its length is only 1.
I have file names that contain numbers that need to be decremented by 1. I need code that satisfies the following pseudocode:
class ReplaceSubstrings
{
string searchFor;
string replaceWith;
Bool filenamecontainnumbers; 'file name contains numbers to be decremented by 1
int filenamenumbers; ' file name size varies from 10 to 500 - I only want to ' target integers 200 - 500
while(filenamecontainsnumbers = 1) ' maybe I should use Bool condition
ReplaceSubstrings app = new ReplaceSubstrings();
If(filenamenumbers > 200){
app.searchFor = filenamenumbers; // A very simple regular expression.
app.replaceWith = decnamenumber();
Console.WriteLine(s);
return 0;
}
void decnamenumber(){
filenamenumbers = filenamenumbers - 1;
};
or something like this!!! Help Please!!!
for "renaming" in c# you can just "move" the file: check out this http://www.dotnetperls.com/file-move
I have written a code that displays 6 DataGridView tables with values from excel that contain exchange rates for euros and us dollars from 6 different banks. The exchange rates are imported from excel file. Now i have to compare each of them and display the min value for euro buy rate (Куповен курс) and max value for sell rate (Продажен/Откупен курс) and min value for dollar buy rate (Куповен курс) and max value for sell rate (Продажен/Откупен курс). I need some help with C# code that will compare those values and display them in a TextBox by clicking the Compare button.
Here is pic from my app:
http://uploadpic.org/v.php?img=CYRmqhbE6F
I tried with this code, but give me error:
private void button7_Click(object sender, EventArgs e)
{
string s = dataGridView1.Rows[1].Cells[1].Value.ToString();
string t = dataGridView2.Rows[0].Cells[6].Value.ToString();
string k = dataGridView3.Rows[0].Cells[1].Value.ToString();
string l = dataGridView4.Rows[0].Cells[4].Value.ToString();
string m = dataGridView5.Rows[0].Cells[2].Value.ToString();
string n = dataGridView6.Rows[0].Cells[3].Value.ToString();
string[] kupoven = new string[] { s,t,k,l,m,n};
int length = kupoven.Length;
int last = length - 1;
int largest = kupoven[];
for (int i = 1; i <= length / 2; i++)
{
if (kupoven[i] > kupoven[last] && kupoven[i] > largest) largest = arr[i];
else if (kupoven[last] > largest) largest = kupoven[last];
last--;
}
return largest;
}
With this i put all euro values in strings(s,t,k,l,m,n), then i put them in array, and then i try to get the max value from the array. I think the problem is with type string.
That code you posted most likely doesn't compile... you should always post code that compiles, unless your question is about code that's not compiling. I would strongly recommend that you try to post sscce compliant questions: http://sscce.org/
With that said, if you want the maximum value I would do something along the lines:
private void button7_Click(object sender, EventArgs e)
{
double s = double.Parse(dataGridView1.Rows[1].Cells[1].Value.ToString());
double t = double.Parse(dataGridView2.Rows[0].Cells[6].Value.ToString());
double k = double.Parse(dataGridView3.Rows[0].Cells[1].Value.ToString());
double l = double.Parse(dataGridView4.Rows[0].Cells[4].Value.ToString());
double m = double.Parse(dataGridView5.Rows[0].Cells[2].Value.ToString());
double n = double.Parse(dataGridView6.Rows[0].Cells[3].Value.ToString());
double[] kupoven = new double[] { s,t,k,l,m,n};
double max = kupoven.Max();
}
Of course, that would only be store the maximum value in the local variable max. To display the max in a text box you would have to write some more code. I also feel like that simply displaying the maximum value may not be sufficient, given that you're comparing the exchange rate between different banks.
Well, I've tried it with ToInt, ToString, and I'm out of options.
I'm trying to substract 2 Label Texts from each other. (Those contains numbers from RSS)
What I have at the moment:
lblOldID.Text = nodeChannel["oldid"].InnerText;
lblNewID.Text = nodeChannel["newid"].InnerText;
So let's say oldid contains "500" and newid "530".
But for some reason, I can't substract (-) them.
What I want:
lblResultID.Text = lblOldID.Text - lblNewID.Text;
Example: Result = 530 - 500
So how is that possible?
You need to convert the text to ints.
//These are the ints we are going to perform the calculation on
Int32 oldID = 0;
Int32 newID = 0;
//TryParse returns a bool if the string was converted to an int successfully
bool first = Int32.TryParse(lblOldID.Text, out oldID);
bool second = Int32.TryParse(lblNewID.Text, out newID);
//Check both were converted successfully and perform the calculation
if(first == true && second == true)
{
lblResultID.Text = (oldID - newID).ToString();
}
else
{
lblResultID.Text = "Could not convert to integers";
}
TryParse prevents an exception being thrown if the data in the labels cannot be converted to integers. Instead, it returns false (or true if the numbers were parsed successfully).
If you want the label text to be, literally, 530 - 500, concatenate the strings like so:
lblResultID.Text = lblOldID.Text + " - " + lblNewID.Text;
If you want the label text to be the result of subtracting the numbers represented in the labels, convert them to integers first:
int old = Int32.Parse(lblOldID.Text);
int new = Int32.Parse(lblNewID.Text);
lblResultID.Text = (old - new).ToString();
(You'll need some error checking in there if there's the possibility that either value might not convert cleanly to an integer)
Perhaps because you really should parse them:
lblResultID.Text = (int.Parse(lblOldID.Text) - int.Parse(lblNewID.Text)).ToString();
Or in string format:
lblResultID.Text = lblOldID.Text + " - "+ lblNewID.Text;