I am creating a GUI that outputs raw serial data onto a textbox, and I want the user to be able to choose certain columns from that data to print onto a label next to the text box every time the data updates. I can do this when there is only one column chosen, however, when I try to add multiple columns, I get the error "Cannot Explicitly Convert string[] to string". How can I take multiple columns of data, put them into one string, then print the string to the label?
Here is what I have done so far:
string[] data_disp = new string[10];
string[] blahArray = line.Split(new char[] { ',' });
int count1 = txt_PRINT_COLUMN_2.Text.Split(',').Length - 1;
string[] countarr = txt_PRINT_COLUMN_2.Text.Split(new char[] { ',' });
for (int i = 0; i <= count1;)
{
int column_data = Convert.ToInt32(countarr[i]);
double inst2 = Convert.ToDouble(blahArray[column_data]);
data_disp[i] = Convert.ToString(inst2);
i++;
}
lbl_SHOW_COLUMN_2.Text = String.Join(",",data_disp);
"line" is the incoming data, txt_PRINT_COLUMN_2 is the textbox where the user enters the desired columns, and lbl_SHOW_COLUMN_2 is the label where the data should print.
EDIT: I used string.join which takes care of the string error, however, the string data_disp is still null. How do I fill it in with the values?
EDIT2: I added i++ to the for loop and made the condition for i <= count1. This worked for the first iteration, however, when the data updated, I got the error: "Input string was not in the correct format" on the line inst2. How do I fix this?
Related
This is more a question of whether this is possible.
I have an input box, 6 items go into the input box, this is an example string that forms the array:
Monday, Tuesday, April, February, Tomorrow, 42
These words can change, but their order is important. They are separated by a tab.
I want the 1st, 3rd, and the 6th word from this array. I would like to place them into an object - and if at all possible, but other items from other sources into that object in a particular order - so that I can then refer back to that object so that I do not have to write out long sections of code each time I need to output these 3 items.
My current code is unwieldy and I am looking for a better solution.
For reference my current code:
string phrase = value.Text;
string[] words = phrase.Split('\t');
string Word1 = words[1];
string Word2 = words[3];
string Word3 = words[6];
this.Output.Text = Word1 + '\t';
this.Output.Text += TextBox1.Text + '\t';
this.Output.Text += Word2 + '\t';
this.Output.Text += TextBox2.Text + '\t';
this.Output.Text += Word3;
This code works, but I am starting to work with larger arrays, requiring larger outputs and I am finding that I need to refer back to the same output multiple times.
Imagine the above code running to Word12, from an array of 30 adding the information from 6 text boxes, and having to have that output created 15 times in different places in the program. Also, you can see that the length of the code stops making sense.
If I could create an object containing all of that information, I could create it once, and then refer back to it as often as I needed.
Any insight or direction on how to proceed gratefully received.
Based on my understanding you are looking for below solution. If I missed something then please let me know.
Firstly you can store value.Text into a list of string by splitting by '\t'.
Create an array to store indexes for which you want to pick words.
Based on stored indexes you can pick words and store in a final wordslist.
Create an array to store dynamic textboxes text.
Loop on these stored textboxes text array and insert at alternate position in final wordlist.
At last join wordlist separated by '\t' and show as output.
Below is the code:
string finalOutput = string.Empty;
List<string> wordsList = new List<string>();
string phrase = value.Text;// "Monday\tTuesday\tApril\tFebruary\tTomorrow\t42";
string[] words = phrase.Split('\t');
List<int> wordsIndexes = new List<int> { 1, 3, 6 }; //this is based on ur requirment
List<string> textBoxesText = new List<string>() { TextBox1.Text, TextBox2.Text };
wordsIndexes.ForEach(i => wordsList.Add(words[i-1]));
int insertAtIndex = 1;
for (int i = 0; i < textBoxesText.Count; i++)
{
if (wordsList.Count >= insertAtIndex)
{
wordsList.Insert(insertAtIndex, textBoxesText[i]);
insertAtIndex += 2;
}
}
finalOutput = string.Join('\t', wordsList);
Not sure if I understand correctly, but I think that you could use a list and add the words there, using a list of indexes like so:
string phrase = value.Text;
string[] words = phrase.Split('\t');
List<int> indexes = new List<int> { 1, 3, 6 }; //you can add more indexes here...
List<string> wordsList = new List<string>();
indexes.Foreach(i => wordsList.add(words[i]));
With this implementation, you have all the words you need in the list and you can easily add more just adding or removing any index you want. And you can refer the list whenever you need to.
I have a CSV file, I am trying to replace 1st column details with 2nd column values using String.Replace in C#,This is working fine. But next when I try replacing 2nd column with 6th column values, it is affecting the 1st column values also..?
string[] lines = File.ReadAllLines(file);
for(int i=1;i<lines.Length;i++)
{
if (lines[i].Split(',')[1].Contains('.'))
{
lines[i] = lines[i].Replace(lines[i].Split(',')[0], lines[i].Split(',')[1]);
lines[i] = lines[i].Replace(lines[i].Split(',')[1], lines[i].Split(',')[6]);
}
}
File.WriteAllLines(file,lines);
There is a miss understanding of what lines[i].Replace does. If you click on it and press F12 or F1 you will see that it's actually String.Replace(String, String).
From the documentation: "Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string."
In your code you want to move values from column 2 to column 1 etc. Not remplace the all occurence of the value of column 1.
for (int i = 1; i < lines.Length; i++)
{
// your if here.
var columns = lines[i].Split(',');
columns[0] = columns[1];
columns[1] = columns[5];
lines[i] = string.Join(",", columns);
}
In the following Live demo, I removed the if and emulate fileRead and Write with simple string [] and string.
I have a DataGridView with TextBox colums. One of the columns display record counts which are formatted as ###,###,000. The column itself isn't set to format the text, but the data is formatted when the data source is populated. The data source is a List by the way. The DataGridView merely displays everything as it gets it.
Now, I need to parse the numeric text value into a variable, which is fine by doing
int.Parse(data_grid_view_row.Cells["col_Record_Count"].Value.ToString())
but, if I have numbers reaching thousands, it displays as 1 000, because of the formatting. The formatting generates a space rather than a comma as this is how the environment has been configured. When I try to parse that value, I get an exception because of the space in the numeric value.
I have tried formatting the string value
int.Parse(String.Format("{0:000000000}", data_grid_view_row.Cells["col_Record_Count"].Value.ToString()))
and
int.Parse(String.Format("{0:########0}", data_grid_view_row.Cells["col_Record_Count"].Value.ToString()))
and all sorts of variants, but it keeps returning the space in the value, which then won't parse. I have tried replacing the space, but it is persistent. Also, the space shows ASCII keycode 63 which is supposed to be a question mark, not so? Even when I try to replace using the keycode... nothing!
Any ideas as to why this is happening and how to fix it?
The complete code block I have is
foreach (DataGridViewRow data_grid_view_row in dgv_Migration_Files.Rows)
{
if ((bool)data_grid_view_row.Cells["col_Select"].Value == true)
{
//-------------------------------------------------------------------------
// this is only to test and see what value I get for the space character, will be removed later
string test_str = data_grid_view_row.Cells["col_Record_Count"].Value.ToString().Replace(" ", string.Empty);
test_str = test_str.Replace(" ", "");
for (int k = 0; k < test_str.Length; k++)
{
string newstr = test_str.Substring(k, 1);
var kycode = ASCIIEncoding.ASCII.GetBytes(newstr);
}
//-------------------------------------------------------------------------
migrate.Add(new Migrate()
{
File_Folder = data_grid_view_row.Cells["col_File_Folder"].Value.ToString()
,
File_Name = data_grid_view_row.Cells["col_File_Name"].Value.ToString()
,
Record_Count = int.Parse(String.Format("{0:000000000}", data_grid_view_row.Cells["col_Record_Count"].Value.ToString()))
});
}
}
Use simple Solution:-
If space is available Remove it and then simply Parse into INT.
str.Replace(" ", String.Empty)
string data = data_grid_view_row.Cells["col_Record_Count"].Value.ToString().Replace(" ", String.Empty);
int.Parse(data);
Make it easier:-
int.Parse(data_grid_view_row.Cells["col_Record_Count"].Value.ToString().replace(" ", String.Empty));
And if you want to remove space and comma both while parsing using this Regular Expression
int.Parse(data_grid_view_row.Cells["col_Record_Count"].Value.ToString().replace(/[, ]+/g, " ").trim());
Check This Small Example First you will get Clear Idea:-
string data = "1 0000";
string result = data.Replace(" ", string.Empty);
Since the replace method didn't remove spaces as I expected to, I resorted to the below solution. This will also remove any other numeric separators irrespective of what the numeric separator has been set up as in the OS.
//get the numeric decimal seperator key code
string dummy_numeric = (1000).ToString(Helper.application_number_display_format);
char replace_char = (char)0;
foreach (char current_char in dummy_numeric)
{
if (!System.Char.IsDigit(current_char))
{
replace_char = current_char;
break;
}
}
//get all the files that are selected for migration
List<Migrate> migrate = new List<Migrate>();
foreach (DataGridViewRow data_grid_view_row in dgv_Migration_Files.Rows)
{
if ((bool)data_grid_view_row.Cells["col_Select"].Value == true)
{
migrate.Add(new Migrate()
{
File_Folder = data_grid_view_row.Cells["col_File_Folder"].Value.ToString()
,
File_Name = data_grid_view_row.Cells["col_File_Name"].Value.ToString()
,
Record_Count = int.Parse(data_grid_view_row.Cells["col_Record_Count"].Value.ToString().Replace(replace_char.ToString(), ""))
});
}
}
I've been working on a school assignment for a while and I have noticed I need a little help finishing it up. Specifically, I need help converting/importing a FlatFile.txt into my normalized DataBase in .
My flatfile has many rows, and in each row there are many attributes separated by a ' | '.
How can I add each line and take every element in the line to its unique corresponding attributes in my DataBase (assuming I already have my connection with my Database established)?
I know I might need to use something like:
hint*: comm.Parameters.AddWithValue("#FirstName", firstname);
How can make the first element of .txt file equal to firstname?
I hope this made sense.
Here is what I have so far:
string [] lines = File.ReadAllLines(pathString);
string[][] myRecords = new string[lines.Count() + 1][];
int k = 1;
foreach (var line in lines)
{
var values = line.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 1; i < values.Length; i++)
{
if (myRecords[k] == null)
{
myRecords[k] = new string[values.Length + 1];
}
myRecords[k][i] = values[i];
Console.WriteLine(myRecords[k][i]);
}
k++;
You should be able to add each item from a line to a corresponding name in the database, by using it's position in the line; something like:
comm.Parameters.AddWithValue("#FirstName", values[i]);
(Note: The exact syntax needed here will depend on what you use for this, but I'm assuming you'll be able to figure that part out).
...However, for something like that to work, you'll want to change the code parsing the line and remove StringSplitOptions.RemoveEmptyEntrie, since that will affect the resulting number of data-parts from each line.
An example:
var line = "one|two|||five|six";
// Will produce: {one, two, five, six}
var nonEmptyValues = line.Split(new char[] { '|' },
StringSplitOptions.RemoveEmptyEntries);
// Will produce {one, two, null, null, five, six}
var allValues = line.Split(new char[] { '|' });
The latter will allow your resulting array (values in your code) to always contain the correct number of "columns", which should make mapping from positions to DB column names easier.
I'm running three counters, one to return the total amount of chars, one to return the number of '|' chars in my .txt file (total). And one to read how many separate lines are in my text file. I'm assuming my counters are wrong, I'm not sure. In my text file there are some extra '|' chars, but that is a bug I need to fix later...
The Message Boxes show
"Lines = 8"
"Entries = 8"
"Total Chars = 0"
Not sure if it helps but the .txt file is compiled using a streamwriter, and I have a datagridview saved to a string to create the output. Everything seems okay with those functions.
Here is a copy of the text file I'm reading
Matthew|Walker|MXW320|114282353|True|True|True
Audrey|Walker|AXW420|114282354|True|True|True
John|Doe|JXD020|111222333|True|True|False
||||||
And here is the code.
private void btnLoadList_Click(object sender, EventArgs e)
{
var loadDialog = new OpenFileDialog
{
InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments),
Filter = "Text (*.txt)|*.txt",
FilterIndex = 1
};
if (loadDialog.ShowDialog() != DialogResult.OK) return;
using (new StreamReader(loadDialog.FileName))
{
var lines = File.ReadAllLines(loadDialog.FileName);//Array of all the lines in the text file
foreach (var assocStringer in lines)//For each assocStringer in lines (Runs 1 cycle for each line in the text file loaded)
{
var entries = assocStringer.Split('|'); // split the line into pieces (e.g. an array of "Matthew", "Walker", etc.)
var obj = (Associate) _bindingSource.AddNew();
if (obj == null) continue;
obj.FirstName = entries[0];
obj.LastName = entries[1];
obj.AssocId = entries[2];
obj.AssocRfid = entries[3];
obj.CanDoDiverts = entries[4];
obj.CanDoMhe = entries[5];
obj.CanDoLoading = entries[6];
}
}
}
Hope you guys find the bug(s) here. Sorry if the formatting is sloppy I'm self-taught, no classes. Any extra advice is welcomed, be as honest and harsh as need be, no feelings will be hurt.
In summary
Why is this program not reading the correct values from the text file I'm using?
Not totally sure I get exactly what you're trying to do, so correct me if I'm off, but if you're just trying to get the line count, pipe (|) count and character count for the file the following should get you that.
var lines = File.ReadAllLines(load_dialog.FileName);
int lineCount = lines.Count();
int totalChars = 0;
int totalPipes = 0; // number of "|" chars
foreach (var s in lines)
{
var entries = s.Split('|'); // split the line into pieces (e.g. an array of "Matthew", "Walker", etc.)
totalChars += s.Length; // add the number of chars on this line to the total
totalPipes = totalPipes + entries.Count() - 1; // there is always one more entry than pipes
}
All the Split() is doing is breaking the full line into an array of the individual fields in the string. Since you only seem to care about the number of pipes and not the fields, I'm not doing much with it other than determining the number of pipes by taking the number of fields and subtracting one (since you don't have a trailing pipe on each line).