Alternating colour in listview items - c#

What i am trying to do here is loop a bunch of .csv files split the data, and then put the data in a listview, this is all working fine:
private void BtnRun_Click(object sender, EventArgs e)
{
try {
RunExtraction();
listViewMain.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
} catch (Exception ex) {
Helpers.DebugLogging("[" + DateTime.Now + "]-[" + ex.ToString() + "]");
}
}
private void ProcessCsvFile(string CsvLocation, string CsvFile) {
try {
string[] lines = File.ReadAllLines(#"backlinks\data.txt");
string[] hosts_list = new string[lines.Length];
for (int i = 0; i < lines.Length; i++)
{
hosts_list[i] = (lines[i].Split('|')[0]);
}
using (var reader = new StreamReader(CsvLocation))
{
while(reader.Peek() != -1) {
string line = reader.ReadLine();
List<string> lineValues = line.Split(',').ToList();
if (!lineValues[0].StartsWith("Time")) {
ListViewItem lv = new ListViewItem(lineValues[0].Replace(#"""", " "));
lv.SubItems.Add(lineValues[1].Replace(#"""", " "));
lv.SubItems.Add(lineValues[2]);
listViewMain.Items.Add(lv);
}
}
countToolStrip.Text = listViewMain.Items.Count.ToString() + " extracted ...";
}
} catch (Exception ex) {
Helpers.DebugLogging("[" + DateTime.Now + "]-[" + ex.ToString() + "]");
}
}
What i don't know how to do is alternate the colour between say green and pink for example, like this in the listview:
csv data = green
csv data = pink
csv data = green
csv data = pink
etc
In the listview, i don't need every row alternate, but every csv file block of information imported, they are different sizes in length, I cannot think of a way to do it, any help would be appreciated.

Since you haven't shared some parts of your code, I assume RunExtraction is calling ProcessCsvFile in a loop over csv files. Just add a new argument color to ProcessCsvFile. In RunExtraction, alternate it before calling ProcessCsvFile. Pseudocode below:
RunExtraction()
{
var colors = new List<Color>() { Colors.Green, Colors.Pink }; // add more if you want
var colorIndex = 0;
var csvLocation = "<some-path>";
foreach (var csvFile in csvFiles) {
var color = colors[colorIndex % colors.Count]; // allows you use more than two colors to alternate
ProcessCsvFile(csvLocation, color); // CsvFile is not used, so it is removed
colorIndex++;
}
}

You may just use a simple counter inside the loop and check if it's even/odd
var counter = 1;
while (/* ... */)
{
// ...
if (counter%2 == 0) lv.ForeColor = Color.Green;
// ...
counter++;
}

You can loop through GridView using DataGridViewRow and check if the row is even then Green else Pink for odd rows. Just like this:
foreach (DataGridViewRow row in GridView1.Rows)
if (row.Index % 2==0 )
{
row.DefaultCellStyle.BackColor = Color.Green;
}
else{
row.DefaultCellStyle.BackColor = Color.Pink;
}

Related

How to get selected chart area data in C#

I plotted a graph by using .csv file.Now user enable to select the chart area and clicking export button then selected data want to write another .csv file.
In here I want to approach this methods.User want to get chart1.ChartAreas[0].CursorX.SelectionStart,chart1.ChartAreas[0].CursorX.SelectionEndthen want to read .csv file and deleting others raw that in not selected area.
Note:the user want to select multiple chart area also.Please give me a clarification about this.This is winform application and I use MsChart.
my code as follows;
private void btnExport_Click(object sender, EventArgs e)
{
List<Graph> ObservingData = new List<Graph>(); // List to store all available Graph objects from the CSV
int index = 0;
using (StreamWriter sw = new StreamWriter(#"D:\CSVFile\NEWFile\Export\NewFile.csv"))
{
// Loops through each lines in the CSV
foreach (string line in System.IO.File.ReadAllLines(pathToCsv))
{
// here line stands for each line in the csv file
string[] CsvLine = line.Split(',');
// creating an object of type Graph based on the each csv line
// and adding them to the List<Graph>
Graph Instance1 = new Graph();
if (index == 0)
{
sw.WriteLine(line);
}
else
{
//Add the code here..
// if (((chart1.ChartAreas[0].CursorX.SelectionStart))<= && ( <= (chart1.ChartAreas[0].CursorX.SelectionEnd)))
{
sw.WriteLine(line);
}
}
index++;
}
sw.Close();
}
MessageBox.Show("Data are copied to the new .CSV file");
}
Following code for my multiple selection for chart area.
SizeF curRange = SizeF.Empty;
List<SizeF> ranges = new List<SizeF>();
List<int> selectedIndices = new List<int>();
private void chart1_SelectionRangeChanged(object sender, CursorEventArgs e)
{
ranges.Add(curRange);
selectedIndices.Union(collectDataPoints(chart1.Series[0],curRange.Width, curRange.Height)).Distinct();
StripLine sl = new StripLine();
sl.BackColor = Color.FromArgb(255, Color.LightSeaGreen);
sl.IntervalOffset = Math.Min(curRange.Width, curRange.Height);
sl.StripWidth = Math.Abs(curRange.Height - curRange.Width);
chart1.ChartAreas[0].AxisX.StripLines.Add(sl);
}
List<int> collectDataPoints(Series s, double min, double max)
{
List<int> hits = new List<int>();
for (int i = 0; i < s.Points.Count; i++)
if (s.Points[i].XValue >= min && s.Points[i].XValue <= max) hits.Add(i);
return hits;
}
private void chart1_SelectionRangeChanging(object sender, CursorEventArgs e)
{
curRange = new SizeF((float)e.NewSelectionStart, (float)e.NewSelectionEnd);
}
Following code is plotted graph;
private void Output_Load(object sender, EventArgs e)
{
List<Graph> ObservingData = new List<Graph>(); // List to store all available Graph objects from the CSV
// Loops through each lines in the CSV
foreach (string line in System.IO.File.ReadAllLines(pathToCsv).Skip(1)) // .Skip(1) is for skipping header
{
// here line stands for each line in the csv file
string[] InCsvLine = line.Split(',');
// creating an object of type Graph based on the each csv line
Graph Inst1 = new Graph();
Inst1.Date = DateTime.ParseExact(InCsvLine[0], dateFormatString, CultureInfo.InvariantCulture);
Inst1.AvE = double.Parse(InCsvLine[15]);
Inst1.AvI = double.Parse(InCsvLine[16]);
chart1.Series["Speed"].YAxisType = AxisType.Primary;
chart1.Series["Velocity"].YAxisType = AxisType.Secondary;
chart1.Series["Speed"].Points.AddXY(Inst1.Date.TimeOfDay.ToString(), Inst1.AvE);
chart1.Series["Speed"].ChartType = SeriesChartType.FastLine;
chart1.Series["Velocity"].Points.AddXY(Inst1.Date.TimeOfDay.ToString(), Inst1.AvI);
chart1.Series["Velocity"].ChartType = SeriesChartType.FastLine;
ChartArea CA = chart1.ChartAreas[0];
CA.AxisX.ScaleView.Zoomable = false;
CA.AxisY.ScaleView.Zoomable = false;
CA.CursorX.AutoScroll = true;
CA.CursorX.IsUserSelectionEnabled = true;
}
}
This is out put of graph
Here is an example you may want to study.
It assumes that the x-values are added as DateTimes; set the XValueType!
eachSeries.XValueType = ChartValueType.DateTime;
It also assumes that you have a class level List of sereis to be exported:
var series2Export = new List<Series>() { chart.Series[0], chart.Series[1]};
It assumes further that the points in the series are added in parallel, so that you want to export the same range together, e.g. to first 20 or points from index 33-66..
Now you can for example code the SelectionRangeChanged event (or, of course a Save Button click):
private void chart_SelectionRangeChanged(object sender, CursorEventArgs e)
{
ChartArea ca = chart.ChartAreas[0];
var d0 = (int) ca.CursorX.SelectionStart;
var d1 = (int) ca.CursorX.SelectionEnd;
var spoints = series2Export[0].Points
.Where(x => x.XValue >= d0 && x.XValue <= d1).ToList();
string del1 = ";";
string del2 = "\t";
string fmt1 = "yyyy.MM.dd";
string fmt2 = "#0.0";
SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = suggestedFilePath;
sfd.Title = (d1 - d0) + " points selected. Save data to..";
if (sfd.ShowDialog() == DialogResult.OK)
{
StringBuilder sb = new StringBuilder();
foreach (var dp0 in spoints)
{
int pi = chart.Series[0].Points.IndexOf(dp0);
string st = "";
foreach (var s in series2Export)
{
DataPoint dp = s.Points[pi];
st += (DateTime.FromOADate(dp.XValue)).ToString(fmt1) +
del1 + dp.YValues[0].ToString(fmt2) + del2;
}
sb.AppendLine(st);
}
File.WriteAllText(sfd.FileName, sb.ToString());
}
}
}
Note that I have used strings for both the delimiters and the formts of the data. You can adapt them as needed..
The above code is exporting the data from all participating series in the format: x-value1, yvalue1..; this means it assumes that..
the datapoints contain all the information you want to export and
you want to export the x-values for each point.
If you want to export just the csv line as you had read it in, the simplest way is to store that line with each DataPoint, of, say the 1st series. The natural spot to store them in are the Tags.
Here are two functions to create a list of data points from a line and to restore that line from a series:
List<DataPoint> PointsFromCsvLine(string line)
{
var parts = line.Split(',').ToList(); // use your separator
DateTime dt = Convert.ToDateTime(parts[0]); // add checks!
double d1 = Convert.ToDouble(parts[1]); // use..
double d2 = Convert.ToDouble(parts[4]); // ..your..
double d3 = Convert.ToDouble(parts[9]); // ..numbers!
var points = new List<DataPoint>();
points.Add(new DataPoint( dt.ToOADate(), d1));
points.Add(new DataPoint( dt.ToOADate(), d2));
points.Add(new DataPoint( dt.ToOADate(), d3));
points[0].Tag = line;
return points;
}
string CsvLineFromPoint(Series series0, int index )
{
DataPoint dp = series0.Points[index]; // check index
string s = dp.Tag.ToString();
return s;
}

How we count how many multiple selection in chart area?

I want to count the multiple selections in chart area.As an example user can marked multiple selection as this picture,Multiple selected chart.So how I count how many multiple selection in this chart.This is MSchart in windowsform by using C#.
my multiple selection code as follows;
SizeF rangeOfCurve = SizeF.Empty;
List<SizeF> ranges = new List<SizeF>();
List<int> selectedIndices = new List<int>();
private void chart1_SelectionRangeChanged(object sender, CursorEventArgs e)
{
ranges.Add(rangeOfCurve);
selectedIndices.Union(collectDataPoints(chart1.Series[0],rangeOfCurve.Width, rangeOfCurve.Height)).Distinct();
StripLine sl = new StripLine();
sl.BackColor = Color.FromArgb(255, Color.LightSeaGreen);
sl.IntervalOffset = Math.Min(rangeOfCurve.Width, rangeOfCurve.Height);
sl.StripWidth = Math.Abs(rangeOfCurve.Height - rangeOfCurve.Width);
chart1.ChartAreas[0].AxisX.StripLines.Add(sl);
}
List<int> collectDataPoints(Series s, double min, double max)
{
List<int> hits = new List<int>();
for (int i = 0; i < s.Points.Count; i++)
if (s.Points[i].XValue >= min && s.Points[i].XValue <= max) hits.Add(i);
return hits;
}
private void chart1_SelectionRangeChanging(object sender, CursorEventArgs e)
{
rangeOfCurve = new SizeF((float)e.NewSelectionStart, (float)e.NewSelectionEnd);
}
This is my code for export those selected data to new .csv file.In here I added button click event then selected area data to export another .csv file.but I want to say I can add multiple selection in chart area but data is exported only last selected part only.how can I got all multiple selection data.this is code for getting one selected area data to another .csv file.
private void btnExport_Click(object sender, EventArgs e)
{
List<Graph> ObservingData = new List<Graph>(); // List to store all available Graph objects from the CSV
int index = 0;
using (StreamWriter sw = new StreamWriter(#"D:\CSVFile\NEWFile\Export\NewFile.csv"))
{
// Loops through each lines in the CSV
foreach (string line in System.IO.File.ReadAllLines(pathToCsv))
{
// here line stands for each line in the csv file
string[] CsvLine = line.Split(',');
// creating an object of type Graph based on the each csv line
// and adding them to the List<Graph>
Graph Instance1 = new Graph();
if (index == 0)
{
sw.WriteLine(line);
}
else
{
//Add the code here..**
if (((chart1.ChartAreas[0].CursorX.SelectionStart))<=index && ( index<= (chart1.ChartAreas[0].CursorX.SelectionEnd)))
{
sw.WriteLine(line);
}
}
index++;
}
sw.Close();
}
MessageBox.Show("Data are copied to the new .CSV file");
}
If you can give any help to solve this.I am so much thankful to you.
Assuming you have added StripLines to mark selections, here is an example of how you can collect the DataPoints from these StripLines:
Let's create a List<> of point list:
selectionPoints = new List<List<DataPoint>>();
Now we can collect the DataPoints like this:
List<List<DataPoint>> GetSelectedPoints(ChartArea ca, Series S)
{
selectionPoints = new List<List<DataPoint>>();
foreach (var sl in ca.AxisX.StripLines)
{
List<DataPoint> points = new List<DataPoint>();
points = S.Points.Select(x => x)
.Where(x => x.XValue >= sl.IntervalOffset
&& x.XValue <= (sl.IntervalOffset + sl.StripWidth)).ToList();
selectionPoints.Add(points);
}
return selectionPoints;
}
And now we can do things with the DataPoints like color them..:
foreach (var pointList in selectionPoints)
{
foreach (var dp in pointList) dp.Color = Color.Red;
}
.. or export them:
string filePath = "D:\\demo.csv";
StringBuilder sb = new StringBuilder();
foreach (var pointList in selectionPoints)
{
foreach (var dp in pointList)
sb.Append(dp.XValue + "," + dp.YValues[0] + ";"); // pick your format!
}
File.WriteAllText(filePath, sb.ToString());

How can I paint selected rows in a DataGridView based on the values in two of the cells?

I am populating a DataGridView with a semicolon-delimited text file like so:
private void ExistingAppntmntRecs_Load(object sender, EventArgs e)
{
DataTable dt = SeparatedValsFileToDataTable(APPOINTMENTS_FILE_NAME, ";");
dataGridViewExistingAppntmntRecs.DataSource = dt;
}
// from http://stackoverflow.com/questions/39434405/read-csv-to-datatable-and-fill-a-datagridview (Frank)
public static DataTable SeparatedValsFileToDataTable(string filename, string separatorChar)
{
var table = new DataTable("Filecsv");
using (var sr = new StreamReader(filename, Encoding.Default))
{
string line;
var i = 0;
while (sr.Peek() >= 0)
{
try
{
line = sr.ReadLine();
if (string.IsNullOrEmpty(line)) continue;
var values = line.Split(new[] { separatorChar }, StringSplitOptions.None);
var row = table.NewRow();
for (var colNum = 0; colNum < values.Length; colNum++)
{
var value = values[colNum];
if (i == 0)
{
table.Columns.Add(value, typeof(String));
}
else
{ row[table.Columns[colNum]] = value; }
}
if (i != 0) table.Rows.Add(row);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
i++;
}
}
return table;
}
What I want to do now is to color the rows which have an EndDate value within two months of the current date yellow, within one month orange, and those with a date in the past (meaning they have lapsed) red.
There is a PostPaint event which may work, but I don't know how to examine cell contents within the row in that event handler:
private void dataGridViewExistingAppntmntRecs_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
// What now?
}
Here is the contents of the file that is read (bogus/test data, with a header row prepended):
person;phone;email;org;addr1;addr2;city;st8;zip;visitNum;success;adSizeLoc;meetingLoc;meetingDate;meetingTime;adBeginMonth;adBeginYear;adEndMonth;adEndYear;Notes
B.B. King;2221113333;bbking#blues.com;Virtuosos;1234 Wayback Lane;;Chicago;IL;98765;1;false;Full Page Inside Front Cover;Same as Org Address;4/5/2017 2:03:12 PM;9:00 am;May;2017;May;2018;Lucille was her name
Linda Ronstadt;55577889999;rhondalinstadt#eaglet.com;Eagles Singer;La Canada;;Los Angeles;CA;99988;1;false;Full page Inside Back Cover;Same as Org Address;4/5/2017 2:05:23 PM;9:00 am;May;2017;May;2018;She had some good stuff
If the adEndMonth + adEndYear date equates to 2 months or less away, the entire row should be yellow; if 1 month or less away, orange; if today or in the past, paint it red. Finally, if one of the Rolling Stones is running the app, paint it black.
Here is some pseudocode for the PostPaint event, with "TODO:" where I don't know what to do:
private void dataGridViewExistingAppntmntRecs_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
DateTime twoMonthsLimit = DateTime.Now.AddMonths(2);
DateTime oneMonthLimit = DateTime.Now.AddMonths(1);
int endYear = // TODO: assign adEndYear value
int endMonth = // TODO: assign adEndMonth value
DateTime endDate = new DateTime(endYear, endMonth, 1);
if (twoMonthsLimit > endDate) // TODO: paint row yellow
if (oneMonthLimit > endDate) // TODO: paint row orange
if (endDate < DateTime.Now) // TODO: paint row red
}
If the goal is too simply, highlight the rows that fall within certain dates, then changing the rows background color may be an easier option. Repainting the rows may be unnecessary. My solution simply changes the rows background color depending on the dates in the “endMonth” and “endYear” columns.
The cell formatting is an option however, it will fire often and placing this “Coloring” checks every time a cell is changed or displayed is unnecessary. If the rows have already been “Colored”, then the only things to look for is when new rows are added or the values in the “endMonth” or “endYear” columns are changed.
Below is code that simply loops through the DataGridView and sets each row color based on the criteria you described. The logic to get a rows color is fairly straightforward (minus the paint it black). If the date is greater than two months forward from today’s date then leave the background color white. If the date is greater than 1 month but less than 2 months then color the row yellow… etc.
I used a similar approach to read the text file and create the DataTable. Hope this helps.
DataTable dt;
string filePath = #"D:\Test\Artist.txt";
char delimiter = ';';
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
dt = GetTableFromFile(filePath, delimiter);
dataGridViewExistingAppntmntRecs.DataSource = dt;
UpdateDataGridColors();
}
private DataTable GetTableFromFile(string filePath, char delimiter) {
List<string[]> allArtists = GetArtistList(filePath, delimiter);
DataTable dt = GetTableColumns(allArtists[0]);
int totalCols = dt.Columns.Count;
DataRow dr;
for (int i = 1; i < allArtists.Count; i++) {
string[] curArtist = allArtists[i];
dr = dt.NewRow();
for (int j = 0; j < totalCols; j++) {
dr[j] = curArtist[j].ToString();
}
dt.Rows.Add(dr);
}
return dt;
}
private List<string[]> GetArtistList(string inFilePath, char inDelimiter) {
string pathToFile = inFilePath;
char delimiter = inDelimiter;
List<string[]> listStringArrays = File.ReadAllLines(pathToFile).Select(x => x.Split(delimiter)).ToList();
return listStringArrays;
}
private DataTable GetTableColumns(string[] allHeaders) {
DataTable dt = new DataTable();
foreach (string curHeader in allHeaders) {
dt.Columns.Add(curHeader, typeof(string));
}
return dt;
}
private Color GetColorForRow(DataRowView dr) {
// paint it black ;-)
if (dr[0].ToString().Equals("Rolling Stones")) {
return Color.Black;
}
DateTime rowDate;
DateTime dateNow = DateTime.Now;
DateTime twoMonthsLimit = dateNow.AddMonths(2);
DateTime oneMonthLimit = dateNow.AddMonths(1);
if (dr != null) {
string rowStringMonth = dr[17].ToString();
string rowStringYear = dr[18].ToString();
string rowStringDate = "1/" + rowStringMonth + "/" + rowStringYear;
if (DateTime.TryParse(rowStringDate, out rowDate)) {
if (rowDate > twoMonthsLimit)
return Color.White;
if (rowDate > oneMonthLimit)
return Color.Yellow;
if (rowDate > dateNow)
return Color.Orange;
if (rowDate.Month == dateNow.Month && rowDate.Year == dateNow.Year)
return Color.Orange;
// this row date is less than todays month date
return Color.Red;
} // else date time parse unsuccessful - ignoring
}
// date is null
return Color.White;
}
private void UpdateDataGridColors() {
Color rowColor;
DataRowView dr;
foreach (DataGridViewRow dgvr in dataGridViewExistingAppntmntRecs.Rows) {
dr = dgvr.DataBoundItem as DataRowView;
if (dr != null) {
rowColor = GetColorForRow(dr);
dgvr.DefaultCellStyle.BackColor = rowColor;
if (rowColor == Color.Black)
dgvr.DefaultCellStyle.ForeColor = Color.White;
}
}
}
private void dataGridViewExistingAppntmntRecs_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
if (e.ColumnIndex == 17 || e.ColumnIndex == 18) {
//MessageBox.Show("End Date Changed");
UpdateDataGridColors();
}
}
private void dataGridViewExistingAppntmntRecs_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) {
UpdateDataGridColors();
}

Add item in listview

I want to add item into the listview, the problem I'm facing is that when I add an item that I type in on the text box. It is able to insert the value in the listview column that I want. But when it update, all the data that it loaded from the textfile is missing. Only the value that I type in is left.
Before add data:
http://www.hostpic.org/images/1508121529460086.png
After insert the data:
http://www.hostpic.org/images/1508121531010086.png
private void button2_Click(object sender, EventArgs e)
{
//add button
string s;
listView1.Items.Clear();
listView1.BeginUpdate();
for (int i = 0; i < comboBox1.Items.Count; i++)
{
if ((comboBox1.SelectedIndex + 1) + "" == proDetail[i].id)
{
//proDetail[i].estimation = double.Parse(textBox3.Text);
proDetail[i].estimation = textBox3.Text;
s = textBox4.Text;
proDetail[i].pre = s.Split(',');
}
}
for (int j = 0; j < comboBox1.Items.Count; j++)
{
if (proDetail[j].pre != null)
{
project = listView1.Items.Add(proDetail[j].id);
project.SubItems.Add(proDetail[j].activity);
if (proDetail[j].pre.Length <= 1)
{
foreach (string words in proDetail[j].pre)
{
preValue = words;
}
}
else
{
preValue = string.Empty;
foreach (string words in proDetail[j].pre)
{
preValue += words + ",";
}
}
project.SubItems.Add(proDetail[j].estimation.ToString());
project.SubItems.Add(preValue);
}
else
{
project = listView1.Items.Add(proDetail[j].id);
project.SubItems.Add(proDetail[j].activity);
}
listView1.EndUpdate();
listView1.Refresh();
}
}
I forgot to include the
project.SubItems.Add(proDetail[j].estimation);
in the else statement.
Thanks for the help.
This is the culprit:
listView1.Items.Clear();
That has removed all existing items from the control.

c# Add Specific columns from a TEXT file to DataGridView

Hello Everyone,
As shown in the above image I want to add the decimal numbers column wise from a text file to datagrid control.
Following is my code snippet
List<string> str = new List<string>();
String st = "";
int k = 0;
string[] s ;
//Path to write contents to text file
string filename = #"E:\Vivek\contentcopy\clientlist.txt";
Form.CheckForIllegalCrossThreadCalls = false;
OpenFileDialog ofd = new OpenFileDialog();
ofd.FileName = "";
ofd.ShowDialog();
st = ofd.FileName;
if (string.IsNullOrEmpty(ofd.FileName))
return;
string Name = "", No1 = "",No2="";
string[] lines = File.ReadAllLines(st).Where(sw => !string.IsNullOrWhiteSpace(sw)).ToArray();
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].Contains("VENTURA SECURITIES LIMITED (NSE F&O)")) continue;
if (lines[i].Contains("ALL EXCHANGES DERIVATIVES CLIENTWISE STATEMENT AS ON 16-05-2012")) continue;
if (lines[i].Contains("-------------------------------------------------------")) continue;
s = lines[i].Split(' ');
if (s[0] == "PARTY" || s[0] == "") continue;
int z;
Name = "";
for (z = 1; z < s.Length; z++)
{
if (s[z] == "") continue;
if (s[z].Contains('.'))
{
No1+=s[z]+" ";
No2 = No1 + " ";
}
else
{
Name += s[z];
str.Add(s[0]+" "+Name);
}
}
dataGridView1.Rows.Add();
dataGridView1.Rows[k].Cells[0].Value = s[0];
dataGridView1.Rows[k].Cells[1].Value = Name;
dataGridView1.Rows[k].Cells[2].Value = No1;
dataGridView1.Rows[k].Cells[3].Value = No2;
k++;
}
File.WriteAllLines(filename, str);
dataGridView1.ReadOnly = true;
}
The line No1=s[z] directly takes the last column values ie 46,123.19 and so on.I want to fetch each column from the text file and store it in a string variable and then assign it to the datagrid view
I hope my doubt is clear.If not please let me know
Here is the simplest Solution:
Add a DataGrid View to Form and add a Button:
private void button1_Click(object sender, EventArgs e)
{
ReadAndFileter();
}
private void ReadAndFileter()
{
try
{
using(System.IO.StreamReader reader = new System.IO.StreamReader("file.txt"))
{
string line;
string []array;
int rowcount= 0;
decimal number;
string[] separators = { "\t", " " };
int columnCount = 0;
while ((line = reader.ReadLine()) != null)
{
array = line.Split(separators, StringSplitOptions.RemoveEmptyEntries);
dataGridView1.Rows.Add();
foreach (string str in array)
{
if (Decimal.TryParse(str,out number))
{
dataGridView1.Rows[rowcount].Cells[columnCount++].Value = number;
}
}
rowcount++;
columnCount = 0;
}
}
}
catch (Exception ex)
{
}
}
The File Contents are:
Abc 20.122 69.33 0.00 693.25 0.00
def 36.20 96.20 1.15 69.56 8.96
And the final output:
Lets say, you have for lines in your test file, then u need to do following things:
Use StreamReader.ReadLine(), to read one line at time.
Spilt the line using split(' ') and store it in a array
Remove all the empty ones from the array
Now at index 2,3,4,5,6 of the resulting array will have the string equivalent of the decimal numbers.
Repeat this for each StreamReader.ReadLine()
Hope this will help.
Your problem is that you are overwriting No1 every time you read a string, which explains why you only get the last value. What you could do is either;
Append the string:
No1 += s[z] + " ";
Which will put all the values behind eachother, seperated by a whitespace.
Or, you could make a List<String> and add each value to the list, meaning you have them stored seperated:
List<String> values = new List<String>();
foreach(...)
{
if (s[z] == "") continue;
if (s[z].Contains('.'))
{
values.Add(s[z])
}
else
{
Name += s[z];
str.Add(s[0] + " " + Name);
}
}
You can thereafter loop through the list and add each value to a row. Considering your code piece;
int i = 2;
foreach(string value in values)
{
dataGridView1.Rows[k].Cells[i].Value = value;
i++;
}
This should work.
Hope this helps.
Here is edited code: but for future I must suggest to give a try at least..
private void ReadAndFileter1()
{
try
{
using (System.IO.StreamReader reader = new System.IO.StreamReader("file.txt"))
{
string line;
string[] array;
int rowcount = 0;
decimal number;
string[] separators = { "\t", " " };
int columnCount = 1;
string[] lines = File.ReadAllLines("file.txt");
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].Contains("VENTURA SECURITIES LIMITED (NSE F&O)")) continue;
if (lines[i].Contains("ALL EXCHANGES DERIVATIVES CLIENTWISE STATEMENT AS ON 16-05-2012")) continue;
if (lines[i].Contains("-------------------------------------------------------")) continue;
array = lines[i].Split(separators, StringSplitOptions.RemoveEmptyEntries);
if (array[0] == "PARTY" || array[0] == "") continue;
dataGridView1.Rows.Add();
foreach (string str in array)
{
if (Decimal.TryParse(str, out number))
{
dataGridView1.Rows[rowcount].Cells[columnCount++].Value = number;
}
}
dataGridView1.Rows[rowcount].Cells[0].Value = array[0];
rowcount++;
columnCount = 1;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Here it is:
static void Main(string[] args)
{
Decimal result;
string[] splitchar = new string[]{" "};
using(StreamReader reader = new StreamReader(#"C:\Users\Dell\Desktop\input.txt"))
{
while(!reader.EndOfStream)
{
string[] splittedArray = reader.ReadLine().Split(splitchar, StringSplitOptions.RemoveEmptyEntries).Where(x => Decimal.TryParse(x, out result)).ToArray();
// put your code here to get insert the values in datagrid
}
}
}

Categories

Resources