I'm reading a file that is looking like that with a lot of strings
PrId Name Quantity Price Date
3 Milk 2 100 23-08-15
I have a button - btnDat_Click. When i click it retrieves all the dates in a listbox named listDate. I create a button named btnDataToTb_Click, i need to select the date and when i click the button it gonna show properties(Id, Name,Quantity) of all products of that date.
PrId Name Quantity Price
3 Milk 2 100
That's the whole code
char[] cc = new char[500]; int i, nr;
string[] lines = new string[250];
public void btnRead_Click(object sender, EventArgs e)
{
string FileName = textBox1.Text;
FileStream r_stream = new FileStream(FileName, FileMode.Open, FileAccess.ReadWrite);
StreamReader reads_string_from_r_stream = new StreamReader(r_stream);
i = 0;
listBox1.Items.Clear();
listBox2.Items.Clear();
for (; ; i++)
{
textBox1.Text = reads_string_from_r_stream.ReadLine();
lines[i] = textBox1.Text;
listBox1.Items.Add(lines[i]);
listBox2.Items.Add(lines[i]);
if (reads_string_from_r_stream.EndOfStream.Equals(true)) goto nn;
}
nn:
textBox2.Text = reads_string_from_r_stream.EndOfStream.ToString();
r_stream.Close();
nr = listBox1.Items.Count;
textBox6.Text = nr.ToString();
}
private void SelectPath_Click(object sender, EventArgs e)
{
OpenFileDialog openFile1 = new OpenFileDialog();
openFile1.Filter = "Text Files|*.txt";
if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
textBox1.Text = openFile1.FileName;
}
public void button1_Click(object sender, EventArgs e)
{
int n = Convert.ToInt16(textBox6.Text);
ListB.Items.Clear();
for (i = 0; i < n; i++)
{
ListB.Items.Add(lines[i]);
}
}
private void btnDat_Click(object sender, EventArgs e)
{
int n = Convert.ToInt16(textBox6.Text);
for (i = 0; i < n; i++)
{
if(! listDate.Items.Contains(lines[i].Split('\t')[lines[i].Split('\t').Length - 1]))
{
listDate.Items.Add(lines[i].Split('\t')[lines[i].Split('\t').Length - 1]);
}
}
listData.Items.RemoveAt(0);
}
private void btnDataToTb_Click(object sender, EventArgs e)
{
if (listData.SelectedItems.Count > 0)
{
string data = listData.SelectedItem.ToString();
string[] date = data.Split('-');
int day = Convert.ToInt32(date[0]);
int month = Convert.ToInt32(date[1]);
int year = Convert.ToInt32(date[2]);
DateTime a = new DateTime(year, month, day);
for (i = 0; i < listBox2.Items.Count; i++)
{
DateTime data2 = DateTime.Parse(lines[i].Split('\t')[lines[i].Split('\t').Length - 1]);
int result = DateTime.Compare(a, data2);
if(result == 0)
listBox3.Items.Add(string.Format("{0}\t{1}\t{2}\t{3}", lines[i].Split('\t')[0], lines[i].Split('\t')[1], lines[i].Split('\t')[2], lines[i].Split('\t')[3]));
}
}
else
{
MessageBox.Show("Select a date");
}
}
I'd say you're approaching this problem wrong. Instead of reading the data, storing them in a list box, then reading and parsing them again when you need to, which is really complicated, you should rather do this:
Create a new class (e.g. Item) that has properties for the product id, name, quantity, price, and date.
When reading the data, parse the lines immediately and create a new instance of said class for each line. Store these in a List<Item>.
When working with FileStream, StreamReader etc (anything that implements IDisposable/has a Dispose() method) you should use them in a using block (like using (StreamReader sr = …) { /* work with sr here */ }); this will automatically free the object after use.
For making data visible to the GUI, you can either use data binding, or fill the listbox by hand and get the selected item with SelectedIndex.
Use Linq for querying data. To select all items on a specific date you can use var onThisDate = itemList.Where(item => item.Date == selectedDate). Linq has many more functions for selecting, filtering and projecting data.
Related
The label must change when the page loads. I don't get any errors but the label stays what I named the label.
my code:
private void Form1_Load(object sender, EventArgs e)
{
DateTime curTime = DateTime.Now;
int one = 5; //times of day
int two = 12;
int three = 20;
string ogg = "Oggend";
string mid = "Middag";
string aan = "Aand";
if (curTime.Hour >= one && curTime.Hour <= two)
{
timelbl.Text = ogg;
}
else if (curTime.Hour > two && curTime.Hour < three)
{
timelbl.Text = mid;
}
else
{
timelbl.Text = aan;
}
}
I tried to put timelbl.Text = "Oggend" in aswell but it didn't work.
Oggend means Morning, Middag means Day and aand means Night
Using variables for "times of day" is redundant. You may keep them if that's what you want, but it won't be the best thing to do.
private void Form1_Load(object sender, EventArgs e) {
DateTime curTime = DateTime.Now;
int one = 5; //times of day
int two = 12;
int three = 8;
string ogg = "Oggend";
string mid = "Middag";
string aan = "Aand";
if (curTime.Hour >= one && curTime.Hour <= two)
{
timelbl.Text = ogg;
}
else if (curTime.Hour > two && curTime.Hour < three)
{
timelbl.Text = mid;
}
else
{
timelbl.Text = aan;
}
}
Your code seems to be fine. You just need to make sure that page load event fires so that the variable value assigned to the label. You should add a break point in page load event and ensure that the event fires properly.
So I need to create a Yearly Summary that gives feedback from the amount of events held a year. There must be an event held each month for this to happen.
So far I have stored the months in an array like this:
public string[] sMonths = new string[12] { "01", "02", "03", "04", "05",
"06", "07", "08", "09", "10", "11", "12" };
I then initiate the array into a combo box, with a counter:
for (iCount = 0; iCount < sMonths.Length; iCount++)
{
cboMonth.Items.Add(sMonths[iCount]);
}
Then take this information from the interface (windows form) like this:
sEventName = txtEvent.Text;
sVenueName = txtVenue.Text;
lstActivity.Items.Add("Dance");
lstActivity.Items.Add("Theatre");
lstActivity.Items.Add("Music");
}
//summary
private void btnExit_Click(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Are up you sure you want to exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dialogResult == DialogResult.Yes)
{
Application.Exit();
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
using (StreamWriter sw = new StreamWriter("EVENTS.TXT", true))
{
sw.WriteLine(txtEvent.Text);
sw.WriteLine(txtVenue.Text);
sw.WriteLine(cboMonth.SelectedItem.ToString());
sw.WriteLine(lstActivity.SelectedItem);
if (rdoRange1.Checked == true)
{
sw.WriteLine(rdoRange1.Text);
}
else if (rdoRange2.Checked == true)
{
sw.WriteLine(rdoRange2.Text);
}
else if (rdoRange3.Checked == true)
{
sw.WriteLine(rdoRange3.Text);
}
else
{
sw.WriteLine(rdoRange4.Text);
}
sw.Close();
}
}
I'm not sure if I am doing this correctly, or if I am getting my counters confused, or infact need to use more than 1? But when I then try to create the summary, nothing appears at all?
private void btnSummary_Click(object sender, EventArgs e)
{
using (StreamReader sr = new StreamReader("EVENTS.TXT"))
{
for (iCount = 12; iCount < sMonths.Length; iCount++)
{
if (iCount == 12)
{
sMonths[iCount] = sr.ReadLine();
listBox1.Items.Add("You held an event every month of the year.");
}
else
{
label1.Text = " ";
listBox1.Items.Add("You cannot produce a yearly summary until you have entered an event for each month");
}
}
I try to read the information from the file but it's returning nothing at all.
I am trying to get this to work using local variables, before transferring it into classes.
there may be many errors in my code, I am new to this.
Thanks in advance, any advice appreciated.
UPDATE:
a sample of my readfile is:
jdisfhs
ddnsojds
05
Dance
0
There will be 12 records in each of them. I need to check each value against variables and produce the outcome.
There are a few problems with this chunk:
for (iCount = 12; iCount < sMonths.Length; iCount++)
sMonths is an array of 12 elements so sMonths.Length = 12.
You create your counter with the value 12 and your condition to loop is that your counter is strictly inferior to 12, so you will never enter the loop.
To loop through an array you usually want to do something like :
for(int iCount = 0; iCount < sMonths.Length; iCount++)
But in this case you want to read a file, so your loop should be on the file reader with something like that :
private void btnSummary_Click(object sender, EventArgs e)
{
using (StreamReader sr = new StreamReader("EVENTS.TXT"))
{
string line = string.Empty;
/*the condition in the while reads the next line and puts it in line,
then tests if line is null because sr.ReadLine()
returns null when the end of the document is reached*/
while ((line = sr.ReadLine()) != null)
{
//Do your tests on line
}
}
}
I am writing a program using GUI in C# that includes three text boxes (one for name input, one for grade input and one for grade output), and five buttons (one to take in the name/grade and add to corresponding arrays, one to display just the name and grade that were just entered, one to display lowest grade, one to display highest grade and one to display the class average).
I have the form designed but need help with some of the code, there are two arrays one for the grade and one for name both which have five values initially stored within them. Here is the code I have so far:
namespace WindowsFormsApplication3
{
using static System.Console;
public partial class highestGrade : Form
{
int[] grade = new int[] { 90, 80, 60, 70, 80, };
string[] name = new string[] { "Sally", "Joe", "Sue", "Pete", "Tom", };
double sum = 0;
double average;
int x = 4;
int y = 4;
int z = 0;
public highestGrade()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void addStudent_Click(object sender, EventArgs e)
{
if (x <= 9)
{
Array.Sort(grade, name);
name[x] = textBox1.Text;
grade[x] = Convert.ToInt32(textBox2.Text);
sum = sum + grade[x];
textBox1.Text = string.Empty;
textBox2.Text = string.Empty;
}
}
private void display_Click(object sender, EventArgs e)
{
outputText.Visible = true;
outputText.Text = textBox1.Text + " " + textBox2.Text;
}
private void lowestGrade_Click(object sender, EventArgs e)
{
Array.Sort(grade, name);
outputText.Visible = true;
outputText.Text = name[z] + " " + grade[z];
}
private void button4_Click(object sender, EventArgs e)
{
Array.Sort(grade, name);
outputText.Visible = true;
outputText.Text = name[y] + " " + grade[y];
}
private void averageGrade_Click(object sender, EventArgs e)
{
for (int y = 0; y < 5; y++)
{
sum = sum + grade[y];
}
average = sum / grade.Length;
string avgOutput = Convert.ToString(average);
outputText.Visible = true;
outputText.Text = "Class Average: " + avgOutput;
y++;
}
}
}
I need the program to take input for grade/name up to 10 students, while being able to output the lowest/highest grade continually whenever the user clicks. It also needs to output the total average continuously whenever the user clicks.
The average is not calculating correctly, it keeps adding to the sum for each time the average button is clicked and I cannot get the highest grade to hold its value. For example: if i enter a new grade as 100 then click highest grade, it displays that grade which is what I want. But for the next grade if i enter 95, it replaces the 100 with the 95.
Any help would be appreciated thank you.
You have to reset the current sum before adding the grades again to calculate the average correctly:
private void averageGrade_Click(object sender, EventArgs e) {
sum = 0; // reset sum
for (int y = 0; y < 5; y++) {
sum = sum + grade[y];
}
average = sum / grade.Length;
string avgOutput = Convert.ToString(average);
outputText.Visible = true;
outputText.Text = "Class Average: " + avgOutput;
}
You can also use LINQ to calculate sums and averages, no need to write for loops:
using System.Linq;
var sum = grade.Sum();
var average = grade.Average();
As for the problem with lowest/highest grade: calculate these every time the button is clicked. Eliminate the global variables y, z.
private void lowestGrade_Click(object sender, EventArgs e) {
// this probably only needs to be sorted if a value is added or removed (addStudent_Click)
Array.Sort(grade, name);
outputText.Visible = true;
// first element (with index 0) will be the lowest because arrays are sorted now
outputText.Text = name[0] + " " + grade[0];
}
You can also use LINQ .First() and .Last() to access the first or last element of a collection or without the need of sorting use LINQ .Min() and .Max() methods.
This button is populate which means click on this button will auto generate random numbers .
This is my code:
protected void Button1_Click(object sender, EventArgs e)
{
int rid = RandomNumber(-111, 999);
int rid1 = RandomNumber(-111, 999);
int rid2 = RandomNumber(-222, 888);
int rid3 = RandomNumber(-333, 777);
int rid4 = RandomNumber(-222, 777);
int rid5 = RandomNumber(-333, 444);
int rid6 = RandomNumber(-555, 888);
int rid7 = RandomNumber(444, 999);
int rid8 = RandomNumber(111, 222);
int rid9 = RandomNumber(222, 333);
txt1.Text = rid.ToString();
txt2.Text = rid1.ToString();
txt3.Text = rid3.ToString();
txt4.Text = rid4.ToString();
txt5.Text = rid5.ToString();
txt6.Text = rid6.ToString();
txt7.Text = rid7.ToString();
txt8.Text = rid8.ToString();
txt9.Text = rid9.ToString();
}
The second button is sort list.
How to take all the numbers and follow acceding to put back in the 9 different textbox ?
This is the coding for button sortlist:
protected void Button2_Click(object sender, EventArgs e)
{
int no1;
int no2;
int no3;
int no4;
int no5;
int no6;
int no7;
int no8;
int no9;
//int answer;
no1 = int.Parse(txt1.Text);
no2 = int.Parse(txt2.Text);
no3 = int.Parse(txt3.Text);
no4 = int.Parse(txt4.Text);
no5 = int.Parse(txt5.Text);
no6 = int.Parse(txt6.Text);
no7 = int.Parse(txt7.Text);
no8 = int.Parse(txt8.Text);
no9 = int.Parse(txt9.Text);
int[] a = new int[] {no1,no2,no3,no4,no5,no6,no7,no8,no9 };
Array.Sort(a);
foreach (var str in a)
{
MessageBox.Show(str.ToString());
}
}
I can display sort ACS in MessageBox but I can't put the number ACS into textbox
But still can't get the answer, where was wrong?
Thank you for help.
You could throw the generated numbers into a list, sort the list and assign the numbers accordingly. Thus, txt1.Text = sortedRandList[0]; and so on for the rest.
To get slightly cleaner code, you could consider also throwing all the text boxes within a list, and eventually end up doing textBoxesList[i] = sortedRandList[i];. That should clean up the code a little bit.
You can create List of ints and then sort it like this :
List<int> rids = null;
protected void Button1_Click(object sender, EventArgs e)
{
rids = new List<int>()
{
RandomNumber(-111, 999),
RandomNumber(-111, 999),
RandomNumber(-222, 888),
RandomNumber(-333, 777),
RandomNumber(-222, 777),
RandomNumber(-333, 444),
RandomNumber(-555, 888),
RandomNumber(444, 999),
RandomNumber(111, 222),
RandomNumber(222, 333)
};
DisplayValues(); // use it if you want to show your values in UI
}
protected void sortButton_Click(object sender, EventArgs e)
{
rids.Sort();
DisplayValues()
}
private void DisplayValues()
{
for (int i = 0; i < Controls.Count; i++)
{
if (Controls[i] is TextBox) if(Controls[i]).ID.Contains("txt"))
(Controls[i] as TextBox).Text = rids[Int32.Parse(Controls[i].ID.Replace("txt", "")) - 1].ToString();
}
}
This could be a little tricky so please bear with me.
I have this result from a gridview, the data came from a pivot table:
DateCreate 02/11/2013 02/19/2013 Total
OrdersPendInvoice 0 1 1
OrdersPendPickUp 1 15 16
Here the selectable items are the numbers, and just the numbers greater than zero.
So first I need for those items (the selectable ones) make them like linkButtons son when I click in one of them I can pass as reference (here the other tricky part) both headers.
Let's put an example:
If I clicked on number 15, which basically means that there are 15 OrdersPendPickUp for the date 02/19/2013. Then I will go to a different page with the references 02/19/2013 and OrdersPendPickUp and there show those 15 records. I have no problem with the last part as long as I have the references.
And for the Total case, I'd just need either the OrdersPendInvoice or OrdersPendPickUp (depending on the item selected) cause I will get all records for that reference no matter the date.
I did this but it's not much really, just changes the color of the items greater than zero :(
protected void gvOrdersProcessed_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.Pager)
{
for (int i = 0; i <= e.Row.Cells.Count - 1; i++)
{
if (TryToParse(e.Row.Cells[i].Text) > 0)
{
e.Row.Cells[i].ForeColor = System.Drawing.Color.Red;
}
}
}
}
private int TryToParse(string value)
{
int number;
bool result = Int32.TryParse(value, out number);
if (result)
return number;
else
return 0;
}
Yes, it is tricky. However, give the following a try:
private List<string> _headers = new List<string>();
protected void gvOrdersProcessed_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Collect the texts from the column headers
if (e.Row.RowType == DataControlRowType.Header)
{
for (int i = 0; i <= e.Row.Cells.Count - 1; i++)
{
this._headers.Add(e.Row.Cells[i].Text);
}
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i <= e.Row.Cells.Count - 1; i++)
{
if (TryToParse(e.Row.Cells[i].Text) > 0)
{
string rowKey = e.Row.Cells[0].Text;
string column = this._headers[i];
HyperLink link = new HyperLink();
link.Text = e.Row.Cells[i].Text;
link.NavigateUrl="page.aspx?key=" + rowKey + "&column=" +column;
e.Row.Cells[i].Controls.Clear();
e.Row.Cells[i].Controls.Add(link);
}
}
}
}
Links would be like:
Normal values: ~/page.aspx?key=OrdersPendPickUp&column=02/19/2013
Total: ~/page.aspx?key=OrdersPendPickUp&column=Total