How to get values from data grid view in c#? - c#

I tried with this code..
for (int i = 0; i < datagridItemEntry.RowCount; i++)
{
int a = Convert.ToInt32(datagridItemEntry.Rows[i].Cells[4].Value);
int b = Convert.ToInt32(datagridItemEntry.Rows[i].Cells[5].Value);
int c = a * b;
datagridItemEntry.SelectedRows[i].Cells[6].Value = c.ToString();
}
I want value of cell 4 & 5 to be get multiplied and the result should be reflect in cell 6..
Nothing is happening with the above code..
Help me with the proper code..

Your problem may be here
datagridItemEntry.SelectedRows[i].Cells[6].Value = c.ToString();
Replace .SelectedRows to .Rows
for (int i = 0; i < datagridItemEntry.RowCount; i++)
{
int a = Convert.ToInt32(datagridItemEntry.Rows[i].Cells[4].Value);
int b = Convert.ToInt32(datagridItemEntry.Rows[i].Cells[5].Value);
int c = a * b;
datagridItemEntry.Rows[i].Cells[6].Value = c.ToString();
}

Related

I'm generating a list of 100 random "names", now I need to follow it up with 100 more names and 100 random numbers. C#

I'm making a program that generates the "names" (random lines of text from the ASCII) that are the names of movies in this instance. I should follow them up with a "name" of a director for each (can also be generated from the ASCII), and after that the random year that is the year the "movie" was made (from 1896 to 2021).
I have two separate functions that randomize the names of the movies and directors, but I'm confused with the supposed placement of the Console.Writeline which the intelligence only allows inside their own loops. Otherwise it doesn't seem to be able to use the values "directorname" and "moviename".
I need it to write the names in a single line, ai. (KHGTJ, KGHTJF).
Also I need a way to generate a random year from 1896 to 2021 that is printed after the names of the movie, and director, ai. (KFJU, MDDOS, 1922).
private static void GenerateRandomNames()
{
Random random = new Random();
char y = (char)65;
for (int p = 0; p < 100; p++)
{
string directorname = "";
for (int m = 0; m < 5; m++)
{
int b = random.Next(65, 90);
y = (char)b;
directorname += y;
}
Console.WriteLine(directorname);
}
Random rnd = new Random();
char x = (char)65;
for (int j = 0; j < 100; j++)
{
string moviename = "";
for (int i = 0; i < 5; i++)
{
int a = rnd.Next(65, 90);
x = (char)a;
moviename += x;
}
Console.WriteLine(moviename);
}
Console.WriteLine();
I need to fix the plecement of the Console.Writeline() so it can print both names in the same line, and be able to print the year after them.
I've tried placing the Console.Writeline() outside the loops, but of course it can't then use the name. But this way it prints them the wrong way.
If you want to have minimal changes in your code, you can use the following code:
private static void GenerateRandomNames()
{
//a separate thing for the names of the directors (ASCII)
// then for the years they were made (1896-2021)
//they should all be printed in the end ie. (KGMFK, JDBDJ, 1922)
Random rnd = new Random();
char x = (char)65;
for (int j = 0; j < 100; j++)
{
string directors = "";
string moviename = "";
for (int i = 0; i < 5; i++)
{
int a = rnd.Next(65, 90);
x = (char)a;
moviename += x;
}
for (int i = 0; i < 5; i++)
{
int a = rnd.Next(65, 90);
x = (char)a;
directors += x;
}
Console.WriteLine("( "+directors +", "+ moviename + ", " +rnd.Next(1896, 2021).ToString()+" )");
}
Console.WriteLine();
}
and result:
Not sure if it is good to answer this type of question, but answering it anyway.
Since you only want other 5-letter words and 4-digit numbers ranging from 1896 - 2021,
Just get another variable 'b' and do the same as you did for 'a', like :
int b = rnd.Next(65,90) ;
y = char(b) ;
director name += y ;
and to get the year value, you can use this :
year = rnd.Next(1896,2021)
So, by combining all of the above, you have the code like this :
internal class Program
{
private static void GenerateRandomNames()
{
Random rnd = new Random();
char x = (char)65;
char y = (char) 65 ;
for (int j = 0; j < 100; j++)
{
string moviename = "";
string directorName = "";
int year = rnd.Next(1896,2021);
for (int i = 0; i < 5; i++)
{
int a = rnd.Next(65, 90);
int b = rnd.Next(65, 90);
x = (char)a;
moviename += x;
y = (char)a;
directorName += x;
}
Console.WriteLine(moviename);
Console.WriteLine(directorName);
Console.WriteLine(year);
}
Console.WriteLine();
}
static void Main(string[] args)
{
GenerateRandomNames();
}
}
The task becomes easier if you extract the creation of a random name to a new method. This allows you to call it twice easily. I moved the random object to the class (making it a class field), so that it can be reused in different places.
internal class Program
{
private static readonly Random _rnd = new Random();
private static string CreateRandomName(int minLength, int maxLength)
{
string name = "";
for (int i = 0; i < _rnd.Next(minLength, maxLength + 1); i++)
{
char c = (char)_rnd.Next((int)'A', (int)'Z' + 1);
name += c;
}
return name;
}
private static void WriteRandomNames()
{
for (int i = 0; i < 100; i++)
{
string movie = CreateRandomName(4, 40);
string director = CreateRandomName(3, 30);
int year = _rnd.Next(1896, 2022);
Console.WriteLine($"{movie}, {director}, {year}");
}
Console.WriteLine();
}
static void Main(string[] args)
{
WriteRandomNames();
}
}
Note that the second parameter of the Next(Int32, Int32) method is the exclusive upper bound. Therefore I added 1.
output:
HATRHKYAHQTGS, NCPQ, 1999
QVJAYOTTISN, LJTGJDMB, 2018
JEXJDICLRMZFRV, GJPZHFBHOTR, 1932
SKFINIGVYUIIVBD, DIZSKOS, 1958
LWWGSEIZT, AMDW, 1950
OAVZVQVFPPBY, SPEZZE, 2008
YLNTZZIXOCNENGYUL, URNJMK, 1962
ONIN, WUITIL, 1987
RJUXGORWDVQRILDWWKSDWF, MOEYPZQPV, 1946
YUQSSOPZTCTRM, UEPPXIVGERG, 1994
KILWEYC, QJZOTLKFMVPHUE, 1915
Wow, in the time it took me to write an answer, three or more others appeared. They all seem like pretty good answers to me, but since I went to the trouble of writing this code, here you go. :)
I focused on using the same Random in different ways, because I think that's what you were asking about.
using System;
using System.Collections.Generic;
using System.Linq;
Random rnd = new Random(1950);
GenerateRandomNames();
void GenerateRandomNames()
{
for (int j = 0; j < 100; j++)
{
// here's one way to get a random string
string name = Guid.NewGuid().ToString().Substring(0, 5);
string description = new string(GetRandomCharacters(rnd.Next(5,16)).ToArray());
string cleaner = new string(GetCleanerCharacters(rnd.Next(5, 16)).ToArray());
string preferred = new string(GetPreferredRandomCharacters(rnd.Next(5, 16)).ToArray());
int year = rnd.Next(1896, DateTime.Now.Year + 1);
Console.WriteLine($"{year}\t{preferred}");
Console.WriteLine($"{year}\t{cleaner}");
Console.WriteLine($"{year}\t{name}\t{description}");
Console.WriteLine();
}
Console.WriteLine();
}
// Not readable
IEnumerable<char> GetRandomCharacters(int length = 5)
{
for (int i = 0; i < length; i++)
{
yield return Convert.ToChar(rnd.Next(0, 255));
}
}
// gives you lots of spaces
IEnumerable<char> GetCleanerCharacters(int length = 5)
{
for (int i = 0; i < length; i++)
{
char c = Convert.ToChar(rnd.Next(0, 255));
if (char.IsLetter(c))
{
yield return c;
}
else
{
yield return ' ';
}
}
}
// Most readable (in my opinion), but still nonsense.
IEnumerable<char> GetPreferredRandomCharacters(int length = 5)
{
for (int i = 0; i < length; i++)
{
bool randomSpace = rnd.Next(0, 6) == 3;
if (i > 0 && randomSpace) // prevent it from starting with a space
{
yield return ' ';
continue;
}
var c = Convert.ToChar(rnd.Next(65, 91)); // uppercase letters
if (rnd.Next(0, 2) == 1)
{
c = char.ToLower(c);
}
yield return c;
}
}

Converting this MatLab iterating code to C#. Outputs from matlab and c# are different

I am trying to convert this code:
function [C] = cumulativeMaxV2(A)
cols = size(A,2);
bscans = size(A,3);
C = zeros(size(A));
for col = 1:cols
for bscan = 1:bscans
aline = A(:,col,bscan);
for i = 1:length(aline)
if i == 1
C(i,col,bscan)=0;
else
C(i,col,bscan) = max(A(1:i-1, col,bscan));
end
end
end
end
My C# code is below:
static double[,,] CumulativeMax(double[,,] A)
{
int cols = 304; //A.GetLength(1);
int bscans = 304; //A.GetLength(2);
double[,,] C = new double[160, 304, 304];
Console.Write("Processing... ");
using (var progress = new ProgressBar())
{
for (int col = 0; col < cols; col++)
{
for (int bscan = 0; bscan < bscans; bscan++)
{
double[] aline = new double[160];
for (int i = 0; i < 160; i++)
aline[i] = A[i,col,bscan];
for (int i = 0; i < aline.GetLength(0); i++)
{
if (i == 0)
C[i,col,bscan] = 0d;
else if (i == 1)
{
double[] temp = new double[i];
for (int x = 0; x < i; x++)
temp[x] = A[x,col,bscan];
C[i,col,bscan] = temp.Max();
}
else
{
double[] temp = new double[i - 1];
for (int x = 0; x < i - 1; x++)
temp[x] = A[x,col,bscan];
C[i,col,bscan] = temp.Max();
}
}
}
progress.Report((double)col/cols);
}
}
Console.WriteLine("Done.");
return C;
}
Outputs from MatLab do not match those from the C# code.
Any pointers to where the bugs are in my C# code would be great. I'm not very good with MatLab.
I think this may be due to how MatLab's max function deals with infinity and NaNs.

Substring causing index and length error

I have a section in my code that I run to check to see if the item is an spanish item or english item. I am using this logic from an old vb.net application.
public int Spanish_Item()
{
int i = 0;
object j = 0;
int k = 0;
string ss = null;
string sp_item = null;
sp_item = TxtItem.Text.Trim();
k = 0;
for (i = 1; i <= 15; i++)
{
ss = sp_item.Substring(i, 2);
if (ss == "XX")
{
k = 1;
i = 16;
}
}
return k;
}
The following code loops around
then I get this error message :
ex.Message "Index and length must refer to a location within the
string.\r\nParameter name: length" string
please help!!!
You always go from 1 to 15 - if the (trimmed) text of TxtItem.Text is shorter then 15 chars you'll get the exception.
You should use the length-2 of sp_item as upper bound to avoid the error.
Also, instead of setting i = 16 you should use break to stop the for loop.
However, I think your algorithm could also be written like this instead of the for loop:
if (sp_item.IndexOf("XX")>=1) {
k=1;
}
In c# the first position is at index 0 not 1 like vb
public int Spanish_Item()
{
int i = 0;
object j = 0;
int k = 0;
string ss = null;
string sp_item = null;
sp_item = TxtItem.Text.Trim();
k = 0;
for (i = 0; i < sp_item.len-2; i++)
{
ss = sp_item.Substring(i, 2);
if (ss == "XX")
{
k = 1;
i = 15;
}
}
return k;
}
you can use
if (sp_item.IndexOf("XX")>=0) {
k=1;
}

Insert a Row in Existing DataTable

I tried a method for the question Asked.
public DataTable allSupportPoints(DataTable createPath, double rMax, double interval, int curveType)
{
List <DataTable> theCornerCurves = cornerCurves(createPath, rMax, interval, curveType);
DataTable curvePoints = CustomMerge(theCornerCurves);
double X1 = Convert.ToDouble(createPath.Rows[0][1]);
double Y1 = Convert.ToDouble(createPath.Rows[0][2]);
double X2, Y2;
int count = curvePoints.Rows.Count;
double theDistance;
int pointInsert;
for (int i = 0; i < count;)
{
X2 = Convert.ToDouble(theCornerCurves[i].Rows[0][0]);
Y2 = Convert.ToDouble(theCornerCurves[i].Rows[0][0]);
theDistance = distance(X1,Y1,X2,Y2);
int j=0;
if ( theDistance> interval)
{
pointInsert = Convert.ToInt32 (theDistance / interval);
DataTable temp = straightLineGenerator(X1, Y1, X2, Y2,interval);
for (j = 0; j < temp.Rows.Count; j++)
{
var rowTemp = temp.NewRow();
rowTemp.ItemArray = temp.Rows[j].ItemArray.Clone() as object[];
curvePoints.Rows.InsertAt(rowTemp, i + j);
}
}
X1=Convert.ToDouble(curvePoints.Rows[i+j][0]);
Y1 = 0;
count = curvePoints.Rows.Count;
i = i + 1;
}
return curvePoints;
}
I get This runTime Error: This row already belongs to another table.
I have tried different methods to Insert yet the error is same, i referred some posts also but it doesnt seem to work
Please help!!!!
Change this:
var rowTemp = temp.NewRow();
to this:
var rowTemp = curvePoints.NewRow();
In fact the row must be created by the same table you want to add it
This part of your code:
for (j = 0; j < temp.Rows.Count; j++)
{
var rowTemp = temp.NewRow();
rowTemp.ItemArray = temp.Rows[j].ItemArray.Clone() as object[];
curvePoints.Rows.InsertAt(rowTemp, i + j);
}
is incorrect. First you're adding new row to temp, and then trying to insert it into curvePoints. Since it already belongs to temp datatable - you're getting exception you've mentioned.
This code can be simplified as
for (j = 0; j < temp.Rows.Count; j++)
curvePoints.ImportRow(temp.Rows[j]);
But note: ImportRow inserts row at last position, so if you really need to insert row into specific position like you're doing - just leave your code as is and only change var rowTemp = temp.NewRow(); to var rowTemp = curvePoints.NewRow();

Sum Column in DataGridView ignore negative numbers

Hello I need to ignore negative numbers in a sum of a DGV column. The code I am using to add the values is as follows:
private double DGVTotal()
{
double tot = 0;
int i = 0;
for (i = 0; i < dataGridView1.Rows.Count; i++)
{
tot = tot + Convert.ToDouble(dataGridView1.Rows[i].Cells["Total"].Value);
}
return tot;
}
How would I change that so if the value of the Row is a negative number to not have it be included in the sum?
Thanks!
Kor
One line change:
tot = tot + Math.Max(0, Convert.ToDouble(dataGridView1.Rows[i].Cells["Total"].Value));
Look Ma! No IF! No ternary operators! Just plain Math!
Something like this:
private double DGVTotal()
{
double tot = 0;
int i = 0;
for (i = 0; i < dataGridView1.Rows.Count; i++)
{
Double dbTemp = Convert.ToDouble(dataGridView1.Rows[i].Cells["Total"].Value);
if (dbTemp > 0)
tot = tot + dbTemp;
}
return tot;
}
Change the body of the for loop to
{
double rowValue = Convert.ToDouble(dataGridView1.Rows[i].Cells["Total"].Value);
if (rowValue > 0)
tot += rowValue;
}
for (i = 0; i < dataGridView1.Rows.Count; i++)
{
double val = Convert.ToDouble(dataGridView1.Rows[i].Cells["Total"].Value);
tot = tot + val > 0.0 ? val : 0.0;
}

Categories

Resources