How would I concatenate this line with a string? - c#

Caliber = Convert.ToInt32(values[(int)TankData.Cannon]); //add measurement here
Okay so in my datagridveiw I want to add measurements to columns that need them but every time I try to concatenate this line with a string Caliber = Convert.ToInt32(values[(int)TankData.Cannon]) + " mm"; I keep getting the error of "Cannont implicitly convert type 'string' to 'int'

Your "Caliber" variable is Integer I believe. Of course, you cannot set a string value to an integer variable.
If you want to add measurement to a column, this could work
for (int i = 0; i < DataGridView.Rows.Count; i++)
{
DataGridView.Rows[i]["Caliber"] += " mm";
}

Related

Why do I need to initialize the string variable 'name'?

This was frustrating to solve. I kept getting the error "Use of unassigned local variable" on the 'name' variable in the line of code near the end where it outputs to the List Box.
The solution was to initialize the variable 'name'.
At first, I had simply declared the 'name' variable without initializing it. This threw the error of "Use of unassigned local variable". When I finally also initialized that variable (as shown below), the error went away.
But I don't understand this, because, by the time the code reaches that output line, the name variable does get assigned.
Can someone please explain WHY initializing the 'name' variable got rid of the compiling error?
'''
try
{
StreamReader inputFile; // StreamReader object to read the file
string line; // To hold a line from the file.
int row = 0; // Student/line counter.
int column = 0; // Counter for columns in CSV file.
int total = 0; // Accumulator for grades.
double average = 0; // Average test score
string name = ""; // each student's name
// Create delimiter array
// Why is this necessary? Why not just put the delimiter in the Split method call?
//char[] delim = { ',' };
// Open the CSV file
inputFile = File.OpenText("Grades.csv");
while (!inputFile.EndOfStream)
{
// increment the row counter
row++;
// Read a line from the file
line = inputFile.ReadLine();
// Get the test scores as tokens
string[] scores = line.Split(',');
// Set the accumulator to zero
total = 0;
// Calculate the total of the test score tokens
for (column = 0; column < scores.Length; column++)
{
if (column == 0)
{
name = scores[column];
}
else
{
total += int.Parse(scores[column]);
}
}
// Calculate the average test score
average = (double)total / (scores.Length - 1);
// Display the average
//averagesListBox.Items.Add("The average for student " + row + " is " + average.ToString("n1"));
averagesListBox.Items.Add("The average for " + name + " is " + average.ToString("n1"));
}
// Close the file
inputFile.Close();
// Display the total records read
totalLabel.Text = row.ToString("n0");
}
catch (Exception ex)
{
// Display an error message
MessageBox.Show(ex.Message);
}
}
'''
The compiler cannot prove that it does get set anywhere. What if scores.Length is zero? Then there is no assignment. So the compiler is correct in throwing an error of possible situation where it is not assigned a value.
If you add a condition for scores.Length always being over zero the compiler might be able to deduce that a value is always set. And you could always set it directly to the first element in an array and loop starting from 1 anyway, which is much more efficient.
Actually, it it possible that you're using the name variable without initialization if column < scores.Length.
That's what the warning is about.

Error while performing compute SUM() in a column

I've tried to compute a column in my datagrid, i will be showing these in my code as per below. I Keep getting these error.
I've go through these links
1. How To Convert The DataTable Column type?
2. Error while taking SUM() of column in datatable
3. Invalid usage of aggregate function Sum() and Type: String
//This is the column i add into my datagrid
MITTRA.Columns.Add("Min_Tol");
MITTRA.Columns.Add("Max_Tol");
MITTRA.Columns.Add("Min_Weight");
MITTRA.Columns.Add("Max_Weight");
// The following codes is working finely
// if you notice MTTRQT column, it's a data queried from database
for (int i = 0; i <= MITTRA.Rows.Count - 1; i++)
{
string item = MITTRA.Rows[i]["MTITNO"].ToString();
Tolerancechecking = database_select4.LoadUser_Tolerance(item);
MITTRA.Rows[i]["Min_Tol"] = Tolerancechecking.Rows[0]["Min_Tol"].ToString();
MITTRA.Rows[i]["Max_Tol"] = Tolerancechecking.Rows[0]["Max_Tol"].ToString();
MITTRA.Rows[i]["Min_Weight"] = Convert.ToDecimal(MITTRA.Rows[i]["MTTRQT"]) - ((Convert.ToDecimal(MITTRA.Rows[i]["MTTRQT"]) * Convert.ToDecimal(MITTRA.Rows[i]["Min_Tol"]) / 10));
MITTRA.Rows[i]["Max_Weight"] = Convert.ToDecimal(MITTRA.Rows[i]["MTTRQT"]) + ((Convert.ToDecimal(MITTRA.Rows[i]["MTTRQT"]) * Convert.ToDecimal(MITTRA.Rows[i]["Max_Tol"]) / 10));
dataGrid2.Columns.Clear();
dataGrid2.ItemsSource = null;
dataGrid2.ItemsSource = Tolerancechecking.DefaultView;
}
//Working Sum computation
Decimal Sum = Convert.ToDecimal(MITTRA.Compute("SUM(MTTRQT)", string.Empty));
MaxTol.Text = Sum.ToString(); /*** This is working as i got my value on the text box ****/
Errors when trying sum computation for different column
Initial try
1. Decimal Sum = Convert.ToDecimal(MITTRA.Compute("SUM(Min_Weight)", string.Empty));
Errors occurred
Invalid usage of aggregate function Sum() and Type: String.
Second Attempts
2. Decimal Sum = Convert.ToDecimal(MITTRA.Compute("SUM(Convert(Min_Weight,'System.Decimal'))", string.Empty));
3. Decimal Sum = Convert.ToDecimal(MITTRA.Compute("SUM(Convert(Min_Weight,'System.Decimal'))", ""));
Errors occurred
Syntax error in aggregate argument: Expecting a single column argument with possible 'Child' qualifier.
How am i going to get the compute sum function to work?
Thank you #NoChance for the solutions. Hope this post can help others too.
/***** This is the part where i declare my datacolumn data type ****/
DataColumn Min_Weight = new DataColumn("Min_Weight");
Min_Weight.DataType = System.Type.GetType("System.Decimal");
MITTRA.Columns.Add(Min_Weight);
/**** This Works finally *****/
Decimal Sum = Convert.ToDecimal(MITTRA.Compute("SUM(Min_Weight)", string.Empty));
MaxTol.Text = Sum.ToString();

how to get values from text using .IndexOf and .Substring in c#?

I need to make a summation for several values out from string variable,
Here is my variable:
string strBillHeader = "Invoice Details
INVOICE_DATE,INVOICE_DESCRIPTION,VALUE,FROM_DATE,TO_DATE
01/11/2014,New Corpbundle 7,7,01/11/2014,30/11/2014
01/11/2014,New Corpbundle 7,-7,01/11/2014,30/11/2014
01/11/2014,New Corpbundle 7,7,01/11/2014,30/11/2014
01/11/2014,Missed Call ALERT with Offer,2,01/11/2014,30/11/2014"
I need to get out the VALUES which are (7,-7,7,2) in this case? and to get 9 as a result.
I tried to do it this way:
for (int x = 4; x <= countCommas - 3; x += 4)
{
int firstCommaIndex = strBillHeader.IndexOf(',', strBillHeader.IndexOf(',') + x);
int secondCommaIndex = strBillHeader.IndexOf(',', strBillHeader.IndexOf(',') + (x + 1));
string y = strBillHeader.Substring(firstCommaIndex + 1, 1);
chargeAmount = Convert.ToInt32(y);
//chargeAmount = Int32.Parse(strBillHeader.Substring(firstCommaIndex, secondCommaIndex - firstCommaIndex));
TotalChargeAmount += ChargeAmount;
//string AstrBillHeader = strBillHeader.Split(',')[0];
}
but it did not work since I keep getting 'V' in the y variable.
Any help will be appreciated
If those commas and newlines are always there, this should work:
var lines = strBillHeader.Split(Environment.NewLine).Skip(2);
int total = lines.Split(',').Sum(line => Convert.ToInt32(line[2]));
So, you split the invoice into lines and discard the first 2 ("Invoice Details" and "INVOICE_DATE,INVOICE_DESCRIPTION,VALUE,FROM_DATE,TO_DATE"). Then you split each line on the commas, and take the third value - the first is a date, the second is the "New Corpbundle 7" part, the third is your value. You parse that value as an int, and sum the whole lot.
You may find you need to filter out the lines properly, rather than just assuming you can skip the first two and use the rest, but this should get you started.

MVC - Controller - Make a Simple Math Calculation - Variable + 1

I have a little problem to make a simple math calculation in the controller.
what I try to do is add +1 to a number of a variable.
Here is an example for you to understand better what I try to do:
var a= formcollection["Id_this"];
var next = a + 1;
Note: the value of "Id_this" is "1".
The result I need for the variable next is 2
My problem is that the result of the variable next is "12".
a is a string. Adding a number to a string results in the number being converted to a string and being concatenated.
To make it work, you first need to convert a to a number:
var next = Convert.ToInt32(a) + 1;
Reason is you are doing string concatenation. Try this safe approach:
int number;
int next = 0;
if(Int32.TryParse(formcollection["Id_this"], out number))
{
next = number + 1;
}
else
{
//formcollection["Id_this"] is not a number
}
like this :
var next = int.Parse(a) + 1;

Get csv values to add up

I have created a new integer called int VactualSum = 0;
I need VactualSum to equal the sum of all the values in an object called singleSummary[i].actual. then display the results in a text box called actualsumsent.
singleSummary[i].actual has 4 numeric values that I want my result to be the total of them when added up. e.g 10,20,30,40 the actualsumsent text box should show the value 100.
{ int VactualSum = 0;
I thought maybe having -
Vactual = Vactual + function[i].actual;
Then to put it in the text box have -
actualsumsent.Text = System.Convert.ToString(returned.Vactual)
But this does not work, the section in the array I am trying to add up is -
function[i].account = el.Descendants("var").Where(x => (string)x.Attribute("name") == "account").SingleOrDefault().Attribute("value").Value;
Any advice would be appreciated.
Assuming singleSummary is an array (or IList<T>) then you can do:
actualsumsent.Text = singleSummary.Sum(s => s.actual).ToString();
EDIT: Looking at the edit to the question, it seems you want to sum a comma-separated string containing int values. In that case you can calculate the sum like this:
int sum = singleSummary[i].account.Split(",").Select(s => int.Parse(s)).Sum();
Note this will throw an exception if the string is not well-formed.
Am I missing something? Do you simply want to sum your values and place them into your text box? If you're using 3.5 or newer, you can use the following:
actualsumset.Text = singleSummary.Sum(q=>q.actual).ToString();
Otherwise, you could sum your array up the classic way:
int VactualSum = 0;
foreach(YourObject obj in singleSummary)
{
VactualSum+=obj.actual;
}
actualsumset.Text = VactualSum;
Is a Vactual a bit like a vacuole? Or is it like an actualValue?
Sum of Comma separate values as a input
public int getSum(String inputNumbersCSV)
{
String[] inputNumbers = inputNumbersCSV.Split(',');
int sumOfNum = 0;
for (int i = 0; i < inputNumbers.Length; i++)
{
sumOfNum = sumOfNum + int.Parse(inputNumbers[i]);
}
return sumOfNum;
}

Categories

Resources