|
In your UI, you have an event handler for the dropdown list, so we'll start from that perspective.
public void DropDownSelectChanged(object sender, EventArgs args)
{
var ddl = sender as DropDown;
Calculate(ddl.SelectedItem);
}
The Calculate method will then call the appropriate Action to react to the state of the application.
public Action MoreApplesAction {get; set;}
public Action FewerApplesAction {get; set;}
public void Caclulate(Fruit selectedFruit)
{
var Apple = 5
var Orange = 1
var MoreApples = Apple > Orange;
var FewerApples = Apple < Orange;
switch(selectedFruit)
{
case Apple:
if(MoreApplies) MoreApplesAction?.Invoke();
break;
case Orange:
if(FewerApples) FewerApplesAction?.Invoke();
break;
}
}
The Sharp Ninja
|
|
|
|
|
Dear Folks,
Im a newbie to this forum and appreciate i could get a guidance for my above subject.
I have a csv file ABC.Txt file with contents as indicated below
Name, Age, TelNum, Emailid
Chris, 42, 5555, chris.walker@gmail.com
Rob, 35, 6666, rob.randell@gmail.com
from my C# Script, i want to vlookup by name and get info like age, TelNum or EmailId.
e.g for Chris, if I query for Emailid , i must get his emailid chris.walker@gmail.com.
Appreciate if Could i get a typical code example for this
Cheers!!
Venkat
|
|
|
|
|
Try this: A Fast CSV Reader[^]
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Assuming you are someone who really wants to learn C#, consider this pattern:
1 define a Class for 'Person:
public class Person
{
public Person(string name, int age, int telNum, string emailId)
{
Name = name;
Age = age;
TelNum = telNum;
EmailId = emailId;
}
public string Name { get; set; }
public int Age { get; set; }
public int TelNum { get; set; }
public string EmailId { get; set; }
}
public static class PersonFactory
{
static char[] delimiter = new []{','};
public static Person MakePerson(string line)
{
try
{
var data = line.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
var name = data[0];
var age = Int32.Parse(data[1]);
var tel = Int32.Parse(data[2]);
var eml = data[3];
return new Person(name, age, tel, eml);
}
catch (Exception ex)
{
throw new InvalidDataException(ex.Message);
}
}
public static List<Person> PersonsFromFile(string filepath)
{
var lines = File.ReadAllLines(filepath).Skip(1);
return lines.Select(line => MakePerson(line.Trim())).ToList();
}
} Sample usage:
var persons = PersonFactory.PersonsFromFile(@"C:\Users\###\##\##?.txt");
int chrisage = persons.First(p => p.Name == "Chris").Age;
«Where is the Life we have lost in living? Where is the wisdom we have lost in knowledge? Where is the knowledge we have lost in information?» T. S. Elliot
modified 1-Sep-19 22:04pm.
|
|
|
|
|
Text File in Notepad++
1. Name
2. Institute
3. .......................................................................
4. x : y
5. ......................................................................
6. 9 7
7. .......................................................................
8. Mass(M) : Weight(W) : Time(T) : Velocity(V) : Acceleration(A) : Distance(D)
9. .......................................................................
10. 4.0 5.0 3.56 4.78 5.098 2
11. 5.0 6.0 4.67 5.87 6.387 3
12. 3.0 4.0 6.49 3.95 5.209 4
13. 4.0 7.0 2.01 6.98 2.039 9
14. 9.0 2.0 5.02 2.94 7.209 2
15. 8.0 2.0 4.02 7.30 8.202 6
16. 5.0 9.0 7.03 3.06 2.049 3
17. 0.5 0.4 0.34 0.34 0.534 9
18. 0.7 0.2 0.53 0.74 0.293 3
19. ........................................................................
20.
21.
Code in C#
using System;
using System.IO;
using System.Globalization;
namespace main
{
public class project
{
public int x, y;
public matrix MandW, Time, VandA, Distance;
public string cmt, file, dash;
public project()
{
string filename= "C://user//abc.txt";
Read(filename);
}
public void Read(String pfile)
{
file=pfile;
CultureInfo _ci = CultureInfo.InvariantCulture;
using (StreamReader _sr = new StreamReader(pfile))
{
string[] values;
cmt = _sr.ReadLine();
cmt = _sr.ReadLine();
dash = _sr.ReadLine();
cmt = _sr.ReadLine();
dash = _sr.ReadLine();
values = IO.split_string(_sr.ReadLine());
x = Convert.ToInt32(values[0]);
y = Convert.ToInt32(values[1]);
dash = _sr.ReadLine();
cmt = _sr.ReadLine();
dash = _sr.ReadLine();
MandW = new matrix(x,2);
for (int i= 0, i<x, i++)
{
values = IO.split_string(_sr.ReadLine());
for (int j = 0; j < 2; j++)
{
MandW[i,j] = Convert.ToDouble(values[j], _ci);
}
}
Time = new matrix(y,1);
VandA = new matrix(y,2);
Distance = new matrix(y,1);
}
}
}
}
I am having trouble constructing these matrices..
Thank you in advance.
modified 29-Aug-19 3:31am.
|
|
|
|
|
Member 14571520 wrote: I am having trouble constructing these matrices..
What trouble?
What does it do that you didn't expect, or not do that you did?
Any error messages?
What have you tried to fix it?
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Your main problem seems to be that you do no checks on the data you are reading. You should check the content of each line to ensure it contains the elements you expect. You should also check the result of your calls to IO.split_string ; and why are you not using string.split() ? And do not use Convert to convert strings to numbers, use the TryParse() method for each type; that way you will not be caught out by bad data. And finally, if you look at your data the lines containing the mass and weight values have a line number at the beginning which will confuse the converter: 10. 4.0 5.0 3.56 4.78 5.098 2 .
|
|
|
|
|
I haven't heard about IO.split_string() method and i can't find it in MSDN documentation...
Can you share direct link into it?
|
|
|
|
|
If the file content has always got the same structure, you can to grab data into specific class. For example:
public class MyData
{
private System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-US");
public string Name {get; set;}
public string Institute {get; set;}
public int X {get; set;}
public int Y {get; set;}
public string[] Headers {get; set;}
public double[][] DataMatrix {get; set;}
public MyData(string sFileName)
{
if(!File.Exists(sFileName))
throw new FileNotFoundException($"File '{Path.GetFileName(sFileName)}' does not exist!");
string[] lines = File.ReadAllLines(sFileName);
Name = lines[0];
Institute = lines[1];
X = Convert.ToInt32(lines[5].Split(' ')[0]);
Y = Convert.ToInt32(lines[5].Split(' ')[1]);
Headers = lines[7].Split(new string[]{" : "}, StringSplitOptions.RemoveEmptyEntries);
DataMatrix = lines.Skip(9)
.TakeWhile(l=>l.Length>0 && !l.StartsWith("."))
.Select(l=>l.Split(' ').Select(d=>Double.Parse(d, ci)).ToArray())
.ToArray();
}
}
Then usage will be very easy:
string filename= "C://user//abc.txt";
MyData md = new MyData(filename);
Console.WriteLine(md.Name);
Console.WriteLine(md.Institute);
Console.WriteLine("X = {0}, Y = {1}", md.X, md.Y);
double[] allMasses = md.DataMatrix.Select(m=>m[0]).ToArray();
foreach(double d in allMasses)
Console.WriteLine(d);
Good luck!
|
|
|
|
|
imho, the solution you really want requires you ... or someone else ... writing the code to serialize the data into XML where it can then be deserialized into an instance of a a Class, or added, by binding, to some grid UI.
If that's not possible, I am afraid you are stuck with the tedious task of implementing a line-by-line parser with error-checking per line, as Richard suggested.
«Where is the Life we have lost in living? Where is the wisdom we have lost in knowledge? Where is the knowledge we have lost in information?» T. S. Elliot
|
|
|
|
|
It may be common practice. Is your filename slightly slanted?
|
|
|
|
|
Member 14571520 wrote: MandW = new matrix(x,2);
Unless matrix is an actual class name, I think you wanted something like
MandW = new double[x,2];
Class names should by UpperCamelCase.
Also I'm not sure if you should call Read() in a constructor... let external code decide when does it want to do this
|
|
|
|
|
I would like to know if a toll exist to "inject" code in existing class. I'm thinking about a system working with attribute. These attributes are not used at compile or runtime but just to specify part of code I want to inject during coding.
For example attribute [LogThis]
[LogThis]
private void ConsoleTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
consoleTextBox.ScrollToEnd();
}
Then I run a tool that will add log to all [LogThis] methods
[LogThis]
private void ConsoleTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
log.Trace("starting ConsoleTextBox_TextChanged");
consoleTextBox.ScrollToEnd();
}
Does somthin similar exists?
|
|
|
|
|
|
The term you're looking for is "Aspect-Oriented Programming[^]", or "AOP".
There are a variety of tools which can do this, both free and commercial. There are also some articles here on CodeProject on the topic. For example: Aspect Oriented Programming in C# with RealProxy[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
While you have the information you need to explore AOP tools: very full-featured commercial, like PostSharp [^] ; open-source, like Fody [^]; and, others mentioned on this thread ...
I wonder if there are other, simpler, techniques ... not based on Attributes and behind-the-scenes modification of Assemblies/IL code ... that could meet your needs ? These could include: use of #define compiler directives; run-time attaching/detaching EventHandlers.
If you want to see examples of these methods, just ask.
fyi: I use PostSharp, and it is an amazing tool-set.
«Where is the Life we have lost in living? Where is the wisdom we have lost in knowledge? Where is the knowledge we have lost in information?» T. S. Elliot
modified 29-Aug-19 5:06am.
|
|
|
|
|
hello Gurus,
i am very new to C#.
just to give you a little background of myself, i work as a teamlead for a sap abap team.
i wanted to create a very simple windows form to track the productivity of my team using c#
this is the pseudo code I wanted to implement:
1. input will be taken from a textbox (numeric in value)
2. if textbox input is found in excel worksheet, (where field code = textbox)
3. then, append the value to a datagridview and clear the textbox (for the next numeric input)
4. else, popup message "value not found in the excel worksheet".
my form contains:
1 textbox
1 datagridview
my worksheet looks like this:
code | description | field3 | field4
1 | some description | field3 | field4
The field "code" is my primary key.
hope someone replies.
many many thanks,
-Myth-
|
|
|
|
|
I'm not sure what you are asking us to do. But if you do not know how to code, I would suggest sticking to Excel and building your form there.
Social Media - A platform that makes it easier for the crazies to find each other.
Everyone is born right handed. Only the strongest overcome it.
Fight for left-handed rights and hand equality.
|
|
|
|
|
Do yourself a favour, and don't use a spreadsheet - use a "proper" database (SQL Server, SQLite, Access, MySQL, ... whatever) - don't try and force a spreadsheet to do a database function.
While it's possible, it's a bit "I've got a hammer now how do I screw that desk together?".
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Griff, while I find your intuition/insight always prescient, I think, in this case, more information about how Excel is used here (work-flow) would be valuable; I've posted a query to the OP. cheers, Bill
«Where is the Life we have lost in living? Where is the wisdom we have lost in knowledge? Where is the knowledge we have lost in information?» T. S. Elliot
|
|
|
|
|
To respond to your query, I'd need to know:
1 Excel: who creates these Work/Books/Sheets; why are they used; who uses them; etc.
2 Why Excel rather than a database ?
3 What's the work-flow: how is data gathered from developers ?
«Where is the Life we have lost in living? Where is the wisdom we have lost in knowledge? Where is the knowledge we have lost in information?» T. S. Elliot
|
|
|
|
|
Hello Bill,
Thank you so much for your reply.
to answer your queries:
1 Excel: who creates these Work/Books/Sheets; why are they used; who uses them; etc.
-----> originally, what i have i mind is, to implement 2 functionalities in my windows form. 1 for creation, and the other one is display.
for the creation part, this is already done, -i have already figured out how to append entries to the excel worksheet (using text boxes and a button). for the display however, i don't know how to validate the incident number (code field) against the existing entries in my worksheet, hence this thread is created. (as described in my OP).
as for the the 'why are they used',
-----> right now, the current tracker that was handed over to my team doesn't allow simultaneous update. (which is kind of -for the lack of a better word: dumb).
for 'who uses them'
------> my team is small - just 11 people.
2 Why Excel rather than a database ?
----> i am thinking of using excel, because, the current tracker that i have is made of excel (using macros and some vbs i believe). so i was thinking, it will be easier to migrate the existing entries that my team have created. (plus the original developer of our tracker already resigned. :P ).
3 What's the work-flow: how is data gathered from developers ?
----> the data is gathered from developers via creation functionality (which, as mentioned, i already implemented -thanks to this forum. .
i am really new to C#. and one of the reasons why i wanted to create the simple tracker is for me to learn the language as well.
hope to hear from you soon.
-Myth-
|
|
|
|
|
Let my see if I really understand your comments: are you the only person who somehow monitors your team member's coding, and creates the data entries ?
I keep thinking there is some automated process being used here, and that you are accessing some data store ? Wrong ?
cheers, Bill
«Where is the Life we have lost in living? Where is the wisdom we have lost in knowledge? Where is the knowledge we have lost in information?» T. S. Elliot
|
|
|
|
|
I'm currently doing console application. How do I display S.1.1.004 into the console?
CREATE from S.1.1.001 to S.1.1.002 on Monday, 7th of May, 2019 07:20:44
CREATE from S.1.1.002 to S.1.1.003 on Tuessday, 23rd of March, 2018 10:01:22
CREATE from S.1.1.003 to S.1.1.004 on Wednesday, 4th of February, 2019 5:42:45
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
namespace ReadFromFile
{
class Program
{
static void Main(string[] args)
{
TextReader st = new StreamReader("C://test.txt");
int NumOfLines = 3;
string[] ListLines = new string[NumOfLines];
for (int i = 0; i < NumOfLines; i++)
{
ListLines[i] = st.ReadLine();
}
Console.WriteLine(ListLines[2]);
Console.ReadLine();
st.Close();
}
}
}
|
|
|
|
|
Assuming that you want to show a specific part from the last line in the file, you can do it very easily.
There are two basic ways: use Substring, which extracts a specific portion from a string (good if your line format is static and never changes) or use a Regular Expression (good if the data moves around, changes position from line to line).
First, read all the lines:
string[] lines = File.ReadAllLines(@"C:\Text.txt");
You can identify the last line directly from that
string lastLine = lines[lines.Length - 1];
You can then extract the bit you want - I'll use substring:
string bitYouWant = lastLine.Substring(25, 9);
And print it:
Console.WriteLine(bitYouWant);
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|