Computation of final grades in a listview - c#

This is all of the code i have done so far. The system has a listview that has a column header:
subject name | 1st | 2nd | 3rd | 4th | Final Grades
If the column 1st to 4th contains value it will compute for the final grade of the student. sum(1st to 4th) / 4 *50 + 50. if one of the column does not have a value then the user will be prompted and no final grades will be computed.
I am confused on how do i get all the listview value from 1st to 4th then automatically computes the final grade.
PLease help
private void button1_Click(object sender, EventArgs e)
{
flag = false;
if (txt_numValue.Text != "")
{
char[] entereddata = txt_numValue.Text.ToCharArray();
foreach (char aChar in entereddata.AsEnumerable())
{
if (!Char.IsDigit(aChar))
{
MessageBox.Show("Please enter only numbers.", "In the field Numeric Value");
flag = true;
break;
}
}
}
else if (txt_numValue.Text == "")
{
MessageBox.Show("Please do not leave the field, 'Numeric Value', blank.", "Attention!");
flag = true;
}
if (flag == false)
{
string period = txt_gradingPeriod.Text;
string numeric = txt_numValue.Text;
int cell = 0;
if (period == "1st") { cell = 1; }
else if (period == "2nd") { cell = 2; }
else if (period == "3rd") { cell = 3; }
else if (period == "4th") { cell = 4; }
foreach (ColumnHeader header in listView1.Columns)
{
if (header.Text == period)
{
listView1.Items[0].SubItems[cell].Text = numeric;
break;
}
}
}
}

Once you have got all the data in your list view you can do something like this,
int sum = 0;
foreach (ListViewItem v in listView1.Items)
{
bool hasBlank = false;
for (int i = 0; i < v.SubItems.Count;i++ )
{
if (v.SubItems[i].Text == null || v.SubItems[i].Text == string.Empty)
{
//code
hasBlank = true;
break;
}
else
{
sum += Convert.ToInt16(v.SubItems[i].Text);
}
}
if (!hasBlank)
{
string grade="something";
//formula to calculate grade based on sum.set the result to string grade
v.SubItems[4].Text = grade;
}
else
{
v.SubItems[4].Text = "has blank";
}
sum = 0;
}
This will fill grade if all values are present else a message that it has a blank value.

Related

values are not transforming in datagridview as per condition c#

I want to change the value of datagridview column according to the condition if the cell.value is minimum of the all values the cell must contain "L" , that is low. If the value is highest of all the cell.value = "H" rest should be medium. This is what i have done so far:
//Function to display interaction as High, Medium and Low
public void ShowInteraction(DataGridView dv, string columnName)
{
//MAX
var Max = dv.Rows.Cast<DataGridViewRow>()
.Max(r => Convert.ToDouble(r.Cells[columnName].Value));
//MIN
List<double> arr = new List<double>();
foreach (DataGridViewRow row in dv.Rows)
{
if (row != null && row.Cells[columnName].Value != null)
{
arr.Add(Convert.ToDouble(row.Cells[columnName].Value.ToString()));
}
}
double Min = arr.Min();
//show interaction in datagridview as H, M nad L
foreach (DataGridViewRow row in dv.Rows)
{
if (row.Cells[columnName].Value != null)
{
if ((double)row.Cells[columnName].Value == Min)
{
row.Cells[columnName].Value = Convert.ToString( "L" );
}
else if ((double)row.Cells[columnName].Value == Max)
{
row.Cells[columnName].Value = Convert.ToString( "H" );
}
else if ((double)row.Cells[columnName].Value < Max && (double)row.Cells[columnName].Value > Min)
{
row.Cells[columnName].Value = Convert.ToString("M");
}
else if ((double)row.Cells[columnName].Value == 0.0000)
{
row.Cells[columnName].Value = Convert.ToString("N");
}
else
{
row.Cells[columnName].Value = Convert.ToString("L");
}
}
}
}
And this the result:
My problem is that the medium and high values are showing but some times it escape the lowest value and do not show any "L" at some columns. The data generated is random data.
I cleaned up your code a little bit and I'm not seeing the error you are. Let me know if this helps you with your issue or not.
public partial class MainForm : Form {
public MainForm() {
InitializeComponent();
DataGridView dgv = new DataGridView();
dgv.Columns.Add("columnName", "columnName");
dgv.AllowUserToAddRows = false;
dgv.Rows.Add(21.0);
dgv.Rows.Add(15.0);
dgv.Rows.Add(20.0);
dgv.Rows.Add(25.0);
dgv.Rows.Add(30.12354122);
this.Controls.Add(dgv);
ShowInteraction(dgv, "columnName");
}
public void ShowInteraction(DataGridView dv, string columnName) {
List<double> values = dv.Rows.Cast<DataGridViewRow>().Select(row => Convert.ToDouble(row.Cells[columnName].Value)).ToList();
double Max = values.Max();
double Min = values.Min();
foreach (DataGridViewRow row in dv.Rows)
{
if (row.Cells[columnName].Value != null)
{
double cellValue = Convert.ToDouble(row.Cells[columnName].Value);
var cell = row.Cells[columnName];
if (cellValue == Min)
{
cell.Value = "L";
}
else if (cellValue == Max)
{
cell.Value = "H";
}
else if (cellValue < Max && cellValue > Min)
{
cell.Value = "M";
}
else if (cellValue == 0)
{
cell.Value = "N";
}
else
{
cell.Value = "L";
}
}
}
}
}

Math error using % in a loop

I am trying to use mod division to determine whether a year in a loop is a census or election year, and I have two issues:
1. I cannot get the wording in line with the year for ex:
It is like:
2000
this is an election year
this is a census year
2001
but I need it to say:
2000, this is an election year, this is a census year
2001 etc
2 : My math is some sort of wrong but I am having trouble identifying why or where, the division needs to apply to a user entered year range, and it needs to divide each year by 10, or 4, and the years that have no remainder are election or census years, but it is not doing that properly, it is not dividing all of the years, just some. My code is this:
private void buttonGo_Click(object sender, EventArgs e)
{
//Variables
int startYr = 0;
int endYr = 0;
int yearDisp = 0;
//Input Validation
startYr = int.Parse(textBoxStartYr.Text);
endYr = int.Parse(textBoxEndYr.Text);
if (int.TryParse(textBoxStartYr.Text, out startYr))
{
//correct
}
else
{
MessageBox.Show("Please enter a four digit year");
return;
}
if (int.TryParse(textBoxEndYr.Text, out endYr))
{
//correct
}
else
{
MessageBox.Show("Please enter a four digit year");
return;
}
//Loop
for (yearDisp = startYr; yearDisp <= endYr; yearDisp++)
{
listBoxDisp.Items.Add("Year:" + yearDisp.ToString());
if (checkBoxCensus.Checked == true )
{
if ((yearDisp % 10) == 0)
{
listBoxDisp.Items.Add("This is a census year");
}
else { }
}
else
{
//nothing needed
}
if (checkBoxElection.Checked == true)
{
if ((yearDisp % 4) == 0)
{
listBoxDisp.Items.Add("This is an election year");
}
else { }
}
else
{
//nothing
}
}
}
Try this:
private void buttonGo_Click(object sender, EventArgs e)
{
// Variables
int startYr = 0;
int endYr = 0;
bool checkForCensus = checkBoxCensus.Checked;
bool checkForElection = checkBoxElection.Checked;
// Input Validation
string errorMsg = "";
if (!int.TryParse(textBoxStartYr.Text, out startYr))
errorMsg += "Please enter a four digit year";
if (!int.TryParse(textBoxEndYr.Text, out endYr))\
errorMsg += String.Format("{0}Please enter a four digit year",
errorMsg == "" ? "" : " ");
if (errorMsg != "")
{
MessageBox.Show(errorMsg);
return;
}
// Loop
for (int yearDisp = startYr; yearDisp <= endYr; yearDisp++)
{
bool isCensusYear, isElectionYear;
if (checkForCensus && (yearDisp % 10) == 0)
isCensusYear = true;
if (checkForElection && (yearDisp % 4) == 0)
isElectionYear = true;
listBoxDisp.Items.Add(String.Format("{0}: {1}{2}{3}",
yearDisp.ToString(),
isCensusYear ? "this is a census year" : "",
(isCensusYear && isElectionYear) ? "," : "",
isElectionYear ? "this is an election year" : ""
));
}
}
Notes:
The empty if and else statements are unnecessary. I have removed the to make them more concise.
On the topic of conditionals in if statements: the ! means "not" or "the opposite of". Examples: !false == true and !true == false.
You do not need the initial int.Parse() statements because TryParse()'s second parameter is an out parameter (it outputs the parsed integer).
I created two variables which get the value of the check box. That way you don't have to check the value every time the loop is executed.
I used a ternary operator and String.Format() to determine what text to display.
Although you didn't mention it, I did change the input validation so that only one message box is displayed.
Try this for your listbox issue.
for (yearDisp = startYr; yearDisp <= endYr; yearDisp++)
{
int index = listBoxDisp.Items.Add("Year:" + yearDisp.ToString());
if (checkBoxCensus.Checked == true)
{
if ((yearDisp % 10) == 0)
{
listBoxDisp.Items[index] += ",This is a census year";
}
else { }
}
else
{
//nothing needed
}
if (checkBoxElection.Checked == true)
{
if ((yearDisp % 4) == 0)
{
listBoxDisp.Items[index] += ",This is an election year";
}
else { }
}
else
{
//nothing
}
}
Try something like this:
private void buttonGo_Click(object sender, EventArgs e)
{
//Variables
int startYr = 0;
int endYr = 0;
int yearDisp = 0;
//Input Validation
if (!int.TryParse(textBoxStartYr.Text, out startYr))
{
MessageBox.Show("Please enter a four digit year");
return;
}
if (!int.TryParse(textBoxEndYr.Text, out endYr))
{
MessageBox.Show("Please enter a four digit year");
return;
}
//Loop
for (yearDisp = startYr; yearDisp <= endYr; yearDisp++)
{
bool isElection = 0 == (yearDisp % 4);
bool isCensus = 0 == (yearDisp % 10);
if (isCensus && checkBoxCensus.Checked && isElection && checkBoxElection.Checked)
{
listBoxDisp.Items.Add(String.Format("{0} This is a both a census year and an election year", yearDisp));
}
else if (isCensus && checkBoxCensus.Checked)
{
listBoxDisp.Items.Add(String.Format("{0} This is a census year", yearDisp));
}
else if (isElection && checkBoxElection.Checked)
{
listBoxDisp.Items.Add(String.Format("{0} This is an election year", yearDisp));
}
else {
listBoxDisp.Items.Add(yearDisp.ToString());
}
}
}
Here's a more concise version of the for loop:
for (yearDisp = startYr; yearDisp <= endYr; yearDisp++)
{
bool isElection = (0 == (yearDisp % 4)) && checkBoxCensus.Checked;
bool isCensus = 0 == (yearDisp % 10) && checkBoxElection.Checked;
string text = yearDisp.ToString();
if (isCensus && isElection)
{
text += " This is a both a census year and an election year";
}
else if (isCensus)
{
text += " This is a census year", yearDisp;
}
else if (isElection)
{
text += " This is an election year";
}
listBoxDisp.Items.Add(text);
}

how to remove space after pressing buttons

i was doing a ITP assignment, when i got an error. The code for the part with the problem is:
private void btnAddWord_Click(object sender, EventArgs e)
{
//if the textbox is empty
if (string.IsNullOrEmpty(tbxAddWord.Text))
{
MessageBox.Show("You have entered no characters in the textbox.");
tbxAddWord.Focus();
}
//if the number of items in the listbox is greater than 29
else if (lbxUnsortedList.Items.Count > 29)
{
MessageBox.Show("You have exceeded the maximum number of words in the list.");
tbxAddWord.Text = "";
}
//error message for entering word that is already in the list
bool contains = false;
for (int i = 0; i < lbxUnsortedList.Items.Count; i++)
{
if (lbxUnsortedList.Items[i].ToString().ToLower() == this.tbxAddWord.Text.ToString().ToLower())
{
contains = true;
}
}
//if there is no match in the list
if (!contains)
{
//add word to the listbox
lbxUnsortedList.Items.Add(tbxAddWord.Text);
//update tbxListBoxCount
tbxListboxCount.Text = lbxUnsortedList.Items.Count.ToString();
//onclick, conduct the bubble sort
bool swapped;
string temp;
do
{
swapped = false;
for (int i = 0; i < lbxUnsortedList.Items.Count - 1; i++)
{
int result = CarNameData[i].ToString().CompareTo(CarNameData[i + 1]);
if (result > 0)
{
temp = CarNameData[i];
CarNameData[i] = CarNameData[i + 1];
CarNameData[i + 1] = temp;
swapped = true;
}
}
} while (swapped == true);
tbxAddWord.Text = "";
}
// if there is a match in the list
else
{
MessageBox.Show("The word that you have added is already on the list");
tbxAddWord.Text = "";
tbxAddWord.Focus();
}
}
When i leave the textbox blank and click the add button, it comes up with the error message, but still adds a blank space. how do i stop this from happening?
You need to return from the method if you don't want to execute more code:
if (string.IsNullOrEmpty(tbxAddWord.Text))
{
MessageBox.Show("You have entered no characters in the textbox.");
tbxAddWord.Focus();
return;
}
//if the number of items in the listbox is greater than 29
else if (lbxUnsortedList.Items.Count > 29)
{
MessageBox.Show("You have exceeded the maximum number of words in the list.");
tbxAddWord.Text = "";
return;
}
First thing is if you are using CarNameData list as Generic collection list List<string> its allows inbuilt sort method like CarNameData.Sort();
Second thing you have to put your code in else part like this
private void btnAddWord_Click(object sender, EventArgs e)
{
//if the textbox is empty
if (string.IsNullOrEmpty(tbxAddWord.Text))
{
MessageBox.Show("You have entered no characters in the textbox.");
tbxAddWord.Focus();
}
else
{
//if the number of items in the listbox is greater than 29
if (lbxUnsortedList.Items.Count > 29)
{
MessageBox.Show("You have exceeded the maximum number of words in the list.");
tbxAddWord.Text = "";
}
//error message for entering word that is already in the list
bool contains = false;
for (int i = 0; i < lbxUnsortedList.Items.Count; i++)
{
if (lbxUnsortedList.Items[i].ToString().ToLower() == this.tbxAddWord.Text.ToString().ToLower())
{
contains = true;
}
}
//if there is no match in the list
if (!contains)
{
//add word to the listbox
lbxUnsortedList.Items.Add(tbxAddWord.Text);
//update tbxListBoxCount
tbxListboxCount.Text = lbxUnsortedList.Items.Count.ToString();
//onclick, conduct the bubble sort
bool swapped;
string temp;
do
{
swapped = false;
for (int i = 0; i < lbxUnsortedList.Items.Count - 1; i++)
{
int result = CarNameData[i].ToString().CompareTo(CarNameData[i + 1]);
if (result > 0)
{
temp = CarNameData[i];
CarNameData[i] = CarNameData[i + 1];
CarNameData[i + 1] = temp;
swapped = true;
}
}
} while (swapped == true);
tbxAddWord.Text = "";
}
// if there is a match in the list
else
{
MessageBox.Show("The word that you have added is already on the list");
tbxAddWord.Text = "";
tbxAddWord.Focus();
}
}
}

How to calculate the one particular column total by differentiating items?

I Have a DataGridView, with columns Item, description, quantity, rate & total.
I have two types of items, one item have vapasi == yes (vapasi is a kind of deposite amount), & another item have vapasi == No.I want to calculate the sum of 'total' column by differentiating items with vapasi & items without vapasi, & want to display this calculated total into two respective textboxes that is 'txtboxwithvapasi', n 'txtboxwithoutvapasi' which are there after the grid.I did following code :
private void grdPurchase_CellEndEdit_1(object sender, DataGridViewCellEventArgs e)
{
try
{
try
{
string value = grdPurchase.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
if (e.ColumnIndex == 2)
{
int val = int.Parse(value);
quantity = val;
}
if (e.ColumnIndex == 4)
{
float val = float.Parse(value);
total = val;
if (vapasi1 == "Yes")
{
vtot += total; //vtot=0+10
txt_forvapasitotal.Text = vtot.ToString(); //10
float vapsitot =float.Parse(txt_forvapasitotal.Text);
float vapsicalculate = (vapsitot * a);
float tax = vapsicalculate / 100;
float with_vapasi = vtot + tax;
txt_withvapasi.Text =Convert.ToString(with_vapasi);
}
else
{
nvtot = 0;
for (int i = 0; i < grdPurchase.Rows.Count; i++)
{
if (vapasi1 == "No")
{
if (grdPurchase.Rows[e.RowIndex].Cells[3].Selected == true)
{
nvtot += float.Parse(grdPurchase[4, i].EditedFormattedValue.ToString());
txt_withoutvapasitot.Text = nvtot.ToString();
}
}
}
}
txt_vapasiincludedtot.Text =(float.Parse(txt_withvapasi.Text) +float.Parse(txt_withoutvapasitot.Text)).ToString();
}
if (e.ColumnIndex == 1)
{
int val = int.Parse(value);
materialid = val;
string vapasi = "Select material_vapasi from tbl_material_master where active_flag=1 AND material_id =" + materialid + "";
SqlCommand cmd = new SqlCommand(vapasi, con);
sdr = cmd.ExecuteReader();
if (sdr.HasRows)
{
while (sdr.Read())
{
vapasi1 = sdr["material_vapasi"].ToString();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
grdPurchase.Columns[3].ReadOnly = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
Problem is:-when I am selecting item with vapasi in first row & in second row item without vapasi , its working properly.But if i Select any item at third row ,then its doing sum of all the three items in 'txtboxwithoutvapasi' without differentiating items.
You need to keep track of vapasi being "Yes" or "No" for each row in the grid, but you are using a single variable. Can't you add this column to the grid (as a hidden column if you don't want to show this to the user)? Then whenever you need to calculate the totals you simply iterate through the grid rows and check the vapasi column in stead of the vapasi1 variable.

Assigning values from a cell to another

int rowsCount = 0;
//This checks to see that both textbox for items and subitems do not gain focus at the same time
if (textBoxSubItems.Text != string.Empty)
txtItems.Enabled = false;
else
txtItems.Enabled = true;
if (comboBoxItems.SelectedItem != null)
{
int idx = dataGridViewTimesheet.Rows.Add();
DataGridViewRow row = dataGridViewTimesheet.Rows[idx];
row.Cells["items"].Value = comboBoxItems.SelectedItem.ToString() + "-" + textBoxSubItems.Text;
row.Cells["fromTime"].Value = DateTime.Now.ToLongTimeString();
row.Cells["toTime"].Value = null;
row.Cells["duration"].Value = null;
row.Cells["subTotal"].Value = null;
// row.Cells["comments"].Value = "1";
}
else
MessageBox.Show("Please select an item");
string strGetColumnValue;
if (dataGridViewTimesheet.Rows.Count != 0)
rowsCount = dataGridViewTimesheet.Rows.Count;
else
MessageBox.Show("No row in the datagridview");
while (dataGridViewTimesheet.Rows.Count > 0)
{
try
{
if (dataGridViewTimesheet.CurrentRow != null)
for (int counter = 0; counter < dataGridViewTimesheet.Columns.Count; counter++)
{
if (dataGridViewTimesheet.Columns[counter].Index == 3)
{
strGetColumnValue = dataGridViewTimesheet.Rows[rowsCount].Cells[counter].Value.ToString();
dataGridViewTimesheet.Rows[rowsCount - 1].Cells[3].Value = strGetColumnValue;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Please i have 6 columns in a datagridview, the rows are added dynamically. What i want is when rows are more than one in the datagridview it should assign the value of the second column on the current(the last row created) row to the third column of the previous row. How do I achieve this.
Try this kind of thing
int count =1;
foreach (DataGridRow row in dataGridViewTimesheet.Rows)
{
if (count % 2 == 0)
{
string secondColumn = dataGridViewTimesheet.Rows[count -1].Cells[1].ToString();
dataGridViewTimesheet.Rows[count].Cells[2].Value = secondColumn;
}
count++;
}

Categories

Resources