Ordering a comboBox by the int value - c#

having a lot of problems ordering my combobox by value any help is greatly appreacitated
private void Form1_Load(object sender, EventArgs e)
{
//text to hold the conbo box, text is grabed from the AS2W14data.csv file from c:\temp\...
String variable;
variable = "";
//filll in the combo box , create a reader
System.IO.StreamReader sr = System.IO.File.OpenText(#"c:\temp\AS2W14data.csv");
//use a while loop to read the entire file line by line, using the current line to populate the comboBox
while (!sr.EndOfStream)
{
variable = sr.ReadLine();
string[] currentLineIndex = variable.Split(',');
//customer ID is indexed at the string array postion 1
//Customer name is indexed at the string array position 0
cboCustomer.Items.Add(currentLineIndex[1].Trim() + " " + currentLineIndex[0].Trim());
}
//close the file to prevent errors...
sr.Close();
}
this is my code so far and i cant seem to find a way to order it.. help

I would suggest ordering them before adding them to the combo. Also here's a little shortcut for reading a text file. First, you want to read lines by streaming them (ReadLines() returns IEnumerable<string>) into a projection (Select()) where you create an anonymous object with two properties - Id and Name. At the end, you order a collection of these anonymous objects by the Id.
var lines = File.ReadLines(#"c:\temp\AS2W14data.csv")
.Select(l => new
{
Id = int.Parse(l.Split(',')[1].Trim()),
Name = l.Split(',')[0].Trim()
}).OrderBy(i => i.Id);
foreach (var l in lines)
cboCustomer.Items.Add(l.Id + " " + l.Name);

try this code hope it will work alternatively you can use Sorted Property of ComboBox
private void Form1_Load(object sender, EventArgs e)
{
//text to hold the conbo box, text is grabed from the AS2W14data.csv file from c:\temp\...
String variable;
variable = "";
ArrayList Indexs = new ArrayList();
//filll in the combo box , create a reader
System.IO.StreamReader sr = System.IO.File.OpenText(#"c:\temp\AS2W14data.csv");
//use a while loop to read the entire file line by line, using the current line to populate the comboBox
while (!sr.EndOfStream)
{
variable = sr.ReadLine();
string[] currentLineIndex = variable.Split(',');
//customer ID is indexed at the string array postion 1
//Customer name is indexed at the string array position 0
Indexs.Add(new AddIndexValues(currentLineIndex[1].Trim() + " " + currentLineIndex[0].Trim());
}
//close the file to prevent errors...
cboCustomer.DataSource = DataBaseBuilds.Indexs;
sr.Close();
}
public class AddIndexValues
{
private int i_index;
public AddIndexValues(int Index)
{
i_index = Index;
}
public int Index
{
get { return i_index; }
}
}

Related

C#: Populate Combobox with single column in CSV

I have a csv file with multiple columns, "PROJECT NAME", "PROJECT BUILD". I am trying to populate comobobox with Project Name column only.
Project name column might have multiple repeated names but repeated names should only appear once in combobox as an option to select. For example: in column 1, under "Project Name", Toyota is listed 4 times and Honda is listed 8 Times. Combobox will have 2 things, Toyota and Honda.
Here is my code so far:
// Wehn Form Loads___________________________________________________________________________________________________
public void OnLoad(object sender, RoutedEventArgs e)
{
StreamReader sr = new StreamReader(path);
string column = sr.ReadToEnd();
string[] eachColumn = column.Split(',');
foreach (string s in eachColumn)
{
Project_Name_Combobox.Items.Add(s);
}
}
The current code gets me the entire csv content (row and column) separated by "," listed under combo box. :(. Any help is apricated.
You have to separate out the rows and columns from csv and store whatever you need separately like below.
public void OnLoad(object sender, RoutedEventArgs e)
{
StreamReader sr = new StreamReader(path);
List<string> ProjectNames = new List<string>();
int lineNumber = 1;
while (!sr.EndOfStream)
{
var EachRow = sr.ReadLine();
var Columns= EachRow.Split(',');
if(lineNumber != 1){
ProjectNames.Add(Columns[0]);
}
lineNumber++;
}
ProjectNames = ProjectNames.Distinct().ToList();
foreach(var projectName in ProjectNames){
Project_Name_Combobox.Items.Add(projectName);
}
}

write a comma delimited list to a data grid view

I'm trying to get a csv file into a data table but there are some things in the csv file that I am trying to omit from being entered into the data table, so I wrote it to a list first.
The csv files that i will using the software for have different sections in it for which I then split the whole list into the separate lists for those sections.
After all that was achieved, i needed to skip some lines in each list and wrote the final form i was happy with to lists respective to previous set of lists.
Now I hit a wall, I need to write each of the lists to a respective data grid.
public partial class Form1 : Form
{
String filePath = "";
//list set 1 = list box
List<String> lines = new List<String>();
List<String> accountList = new List<String>();
List<String> statementList = new List<String>();
List<String> summaryList = new List<String>();
List<String> transactionList = new List<String>();
//list set 2 = dgv
List<String> accountList2 = new List<String>();
List<String> statementList2 = new List<String>();
List<String> summaryList2 = new List<String>();
List<String> transactionList2 = new List<String>();
public Form1()
{
InitializeComponent();
}
private void btn_find_Click(object sender, EventArgs e)
{
try
{
using (OpenFileDialog fileDialog = new OpenFileDialog()
{ Filter = "CSV|* .csv", ValidateNames = true, Multiselect = false })
if (fileDialog.ShowDialog() == DialogResult.OK)
{
String fileName = fileDialog.FileName;
filePath = fileName;
}
try
{
if (File.Exists(filePath))
{
lines = File.ReadAllLines(filePath).ToList();
foreach (String line in lines)
{
String addLine = line.Replace("'", "");
String addLine2 = addLine.Replace("\"", "");
String str = line.Substring(0, 1);
int num = int.Parse(str);
if (addLine2.Length > 1)
{
String addLine3 = addLine2.Substring(2);
switch (num)
{
case 2:
accountList.Add(addLine3);
break;
case 3:
statementList.Add(addLine3);
break;
case 4:
summaryList.Add(addLine3);
break;
case 5:
transactionList.Add(addLine3);
break;
}
}
}
}
else
{
MessageBox.Show("Invalid file chosen, choose an appropriate CSV file and try again.");
}
transactionLB.DataSource = transactionList;
//var liness = transactionList;
//foreach (string line in liness.Skip(2))
// transactionList2.Add(line);
//Console.WriteLine(transactionList2);
//var source = new BindingSource();
//source.DataSource = transactionList2;
//trans_dgv.DataSource = source;
accountLB.DataSource = accountList;
summaryLB.DataSource = summaryList;
statementLB.DataSource = statementList;
}
catch (Exception)
{
MessageBox.Show("Cannot load CSV file, Ensure that a valid CSV file is selected and try again.");
}
}
catch (Exception)
{
MessageBox.Show("Cannot open File Explorer, Something is wrong :(");
}
}
}
EDIT 1:
the table has the following columns for the transaction lists (each of the lists have different columns) :
'Number' , 'Date' , 'Description1' , 'Description2' , 'Description3' , 'Amount' , 'Balance' , 'Accrued Charges'
an example of data in the lines of the transaction list:
9, 02 Sep, Petrol Card Purchase, Shell Kempton Park, 968143*7188 30 Aug, -714.45, -10661.88, 5.5
some liness do contain null values.
If I understand correctly, it seems like you're wanting to get the value of the strings in your string list to appear in your DataGridViews. This can be a little tricky because the DataGridView needs to know which property to display and strings only have the Length property (which probably isn't what you're looking for). There are a lot of ways to go about getting the data you want into the DataGridView. For example you could use DataTables and choose which column you want displayed in the DataGridView. If you want to stick with using string lists, I think you could get this to work by modifying your DataSource line to look something like this:
transactionLB.DataSource = transactionList.Select(x => new { Value = x} ).ToList();
I hope this helps! Let me know if I've misunderstood your question. Thanks!

How to reference List<Data>

I am new to C# and I have taken a small task on. The StackOverflow entry for reading a text file and saving to a list is a great start for me. I need to read a text file and send the data to an SQL database.
How to Read This Text File and store in a list using C#
The Data in List<Data> list = new List<Data>(); just keeps staying in red.
How can I stop this please?
I am a PLC engineer and I'm trying to collate data that cannot be handled by PLC. I am just trying to read the file so that I can then show the data in a Grid, with a view to populating the SQL database later.
The text file is held on a remote Linux machine. The collator is a WIndows 10 panel. The SQL can reside on teh Windows panel or remotely.
static void Main(string[] args)
{
List<Data> list = new List<Data>();
var dd = File.ReadAllLines(#"C:\Users\XXXX\Desktop\test.txt")
.Skip(1)
.Where(s => s.Length > 1).ToList();
foreach (var item in dd)
{
var columns = item.Split('\t').Where(c => c.Trim() != string.Empty).ToList();
if (columns != null && columns.Count > 0)
{
int id;
if (int.TryParse(columns[0], out id))
{
list.Add(new Data()
{
id = Convert.ToInt32(columns[0]),
Name = columns[1],
Description = columns[2],
Quantity = Convert.ToInt32(columns[3]),
Rate = Convert.ToDouble(columns[4]),
Discount = Convert.ToInt32(columns[5]),
Amount = int.Parse(columns[6])
});
}
else
{
list.Last().Description += columns[0];
}
}
}
Console.ReadLine();
}
I just keep receiving red squiggly lines on <Data. within Visual Studio
I got the code to work and I read the DAT/text file straight into a DatagridView. I am now writing the Grid to SQL.
Many thanks, sorry for latency as I've been away on-site.
String sLine = "";
try
{
//Pass the file you selected with the OpenFileDialog control to
//the StreamReader Constructor.
System.IO.StreamReader FileStream = new System.IO.StreamReader(openFileDialog1.FileName);
//You must set the value to false when you are programatically adding rows to
//a DataGridView. If you need to allow the user to add rows, you
//can set the value back to true after you have populated the DataGridView
dataGridView1.AllowUserToAddRows = false;
// Clear the DataGridView prior to reading a new text file
dataGridView1.Rows.Clear();
dataGridView1.Columns.Clear();
//Read the first line of the text file
sLine = FileStream.ReadLine();
//The Split Command splits a string into an array, based on the delimiter you pass.
//I chose to use a semi-colon for the text delimiter.
//Any character can be used as a delimeter in the split command.
//string[] s = sLine.Split(';');
string[] s = sLine.Split('\t');
//In this example, I placed the field names in the first row.
//The for loop below is used to create the columns and use the text values in
//the first row for the column headings.
for (int i = 0; i <= s.Count() - 1; i++)
{
DataGridViewColumn colHold = new DataGridViewTextBoxColumn();
colHold.Name = "col" + System.Convert.ToString(i);
colHold.HeaderText = s[i].ToString();
dataGridView1.Columns.Add(colHold);
}
//Read the next line in the text file in order to pass it to the
//while loop below
sLine = FileStream.ReadLine();
//The while loop reads each line of text.
while (sLine != null)
{
//Adds a new row to the DataGridView for each line of text.
dataGridView1.Rows.Add();
//This for loop loops through the array in order to retrieve each
//line of text.
for (int i = 0; i <= s.Count() - 1; i++)
{
//Splits each line in the text file into a string array
//s = sLine.Split(';');
s = sLine.Split('\t');
//Sets the value of the cell to the value of the text retreived from the text file.
dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[i].Value = s[i].ToString();
}
sLine = FileStream.ReadLine();
}
//Close the selected text file.
FileStream.Close();
}
catch (Exception err)
{
//Display any errors in a Message Box.
System.Windows.Forms.MessageBox.Show("Error "+ err.Message, "Program Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

Listarray overflow

I have a problem reading data from a CSV file. As in the following example I try to read in the list information from two different columns. With the query "EndOfStream" or with a count variable larger than about 6000 I get the error: "The index was out of range". However, with a count variable of 4000, the code works exactly as it should. I do not understand my mistake.
List<string> gpsGGA = new List<string>();
List<string> gpsRMC = new List<string>();
public Form1()
{
InitializeComponent();
}
private void btn_file_Click(object sender, EventArgs e)
{
string path;
OpenFileDialog file = new OpenFileDialog();
if (file.ShowDialog() == DialogResult.OK)
{
try {
path = file.FileName;
StreamReader data = new StreamReader(path);
data.ReadLine(); //Header verwerfen
gpsGGA.Clear();
gpsRMC.Clear();
for(int i=0; i<8000; i++)//while (!data.EndOfStream)
{
string[] substring = data.ReadLine().Split(';');
gpsGGA.Add(substring[11]);
gpsRMC.Add(substring[12]);
}
data.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Not sure why this is commented out:
for(int i=0; i<8000; i++)//while (!data.EndOfStream)
The while loop that is commented out intended to only read data while exists.
I added a using statement to ensure the file gets closed. I added an IsNullOrEmpty check in case there's a blank line at the end of the file, so you don't get an error with that.
using (StreamReader data = new StreamReader(path))
{
data.ReadLine(); //Header verwerfen
gpsGGA.Clear();
gpsRMC.Clear();
int counter = 0;
while (!data.EndOfStream)
{
string line = data.ReadLine();
if (! String.IsNullOrEmpty(line))
{
string[] substring = line.Split(';');
if ( substring.Length < 13 )
throw new ApplicationException("Malformated Data At Line " + counter.ToString());
gpsGGA.Add(substring[11]);
gpsRMC.Add(substring[12]);
}
counter += 1;
}
}
Your codes makes it hard to guess wheter the error is coming from reading the file or the file content itself.
You can use File.ReadAllLines which takes the file path and returns its lines as an array, regardless of the number of lines that you specify in the foor loop, which by the way can cause errors if the number of lines is is not equal to 8000.
if (file.ShowDialog() == DialogResult.OK)
{
try
{
gpsGGA.Clear();
gpsRMC.Clear();
string[] lines= File.ReadAllLines(file.FileName);
foreach(String line in lines)
{
string[] substring = line.Split(';');
gpsGGA.Add(substring[11]);
gpsRMC.Add(substring[12]);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The index was out of range is probably caused by some lines which have invalid data
For example this is line 6000 : sdd;dfdf;dfdf;00;dfdf;555
When you try to get element at index 11 or 12, it doesn't exist because this line has only 6 elements

How to read a text file's data vertically or column wise

How can we read a text file column by column.
Check my new code: I can read the data row-wise using text.split (' ')
But how can be the file read as column wise? Lets assume that a file contains number of rows and columns but I was able to read the data/value horizontally. The code you see that below that's what I could execute!
SEE THE CODE BELOW:-
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string text = "";
text = textBox1.Text;
string[] arr = text.Split(' ');
textBox2.Text = arr[5];
textBox3.Text = arr[8];
}
private void button3_Click(object sender, EventArgs e)
{
string file_name = "c:\\Excel\\count.txt";
string txtline = "";
System.IO.StreamReader objreader;
objreader = new System.IO.StreamReader(file_name);
do
{
txtline = txtline + objreader.ReadLine() + "\r\n";
txtline = txtline + objreader.ReadToEnd() + "";
this.textBox1.Text = "subzihut";
}
while (objreader.Peek() != -1);
textBox1.Text = txtline;
objreader.Close();
}
private void button2_Click(object sender, EventArgs e)
{
textBox4.Text = textBox2.Text + " " + textBox3.Text;
}
}
}
A textfile contains a sequence of characters, delimited by newline characters and probably other characters which are used as delimiters (usually a comma or a semiciolon).
When you read a file you simply read this stream of characters. There are helper functions which read such a file line-by-line (using the newline character as a delimiter).
In plain .Net there are no methods which read column-by-column.
So you should:
read the file line by line
split each line into fields/columns using string.Split() at the separator character(s)
access only the columns of interest
You can simply read the file line by line, splitt the lines and do whatever you want.
var lines = File.ReadLines(#"c:\yourfile.txt");
foreach(var line in lines)
{
var values = line.Split(' ');
}
public string getColumnString(int columnNumber){
string[] lines = System.IO.ReadAllLines(#"C:\inputfile.txt");
string stringTobeDisplayed = string.Empty;
foreach(string line in lines) {
if(columnNumber == -1){ //when column number is sent as -1 then read full line
stringTobeDisplayed += line +"\n"
}
else{ //else read only the column required
string [] words = line.Split();
stringTobeDisplayed += word[columnNumber] +"\n"
}
}
return stringTobeDisplayed;
}
Maybe this will help you:
public static void ReadFile(string path)
{
List<string> Col1 = new List<string>();
List<string> Col2 = new List<string>();
List<string> Col3 = new List<string>();
using (StreamReader sr = new StreamReader(path))
{
while (sr.EndOfStream)
{
string header = sr.ReadLine();
var values = header.Split(' ');
Col1.Add(values[0]);
Col2.Add(values[1]);
Col3.Add(values[2]);
}
}
}
It's true that sometimes you just don't know where to start. Here are some pointers.
You'll have to read the whole file in, probably using something like a StreamReader.
You can parse the first row into column names. Use StreamReader.ReadLine() to get the first line and then do some simple string parsing on it.
You'll want to create some kind of class/object to store and access your data.
Once you have column names, continue to parse the following lines into the proper arrays.
Some here's a rough idea
using(StreamReader sr = new StreamReadeR("C:\\my\\file\\location\\text.csv"))
{
string header = sr.ReadLine();
List<string> HeaderColumns = new List<string>(header.split(" ", StringSplitOptions.RemoveEmptyEntires));
myModelClass.Header = HeaderColumns;
etc...
You might also consider making some kind of dictionary to access columns by header name and index.

Categories