Click here to Skip to main content
15,890,897 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
i want to check if values of datatable of the same column are equals to "int" or not , so if it's true i want to calculate with content value the sum. This is my code which return always when i click on sum button "pas tous entier" .
Thank you in advance!


What I have tried:

private void button7_Click(object sender, EventArgs e)
        {
            int i = 0, s = 0;
            String type ="int";

            DataTable dt = new DataTable("Table_insertion");

            bool exists = dt.AsEnumerable().Any(row => type == row.Field<String>("Type"));
            if (exists== true)
            {
                for (i = 0; i < dataGridView1.Rows.Count; ++i)
                {
                    s += Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);

                }
                label5.Text = s.ToString();           
            } 
            else
            {
                MessageBox.Show("pas tous entiers");
            }
          
        }
Posted
Updated 12-Nov-19 5:13am
v2
Comments
ZurdoDev 11-Nov-19 14:16pm    
What are you asking us to do?
foreigh 11-Nov-19 14:32pm    
to help me knowing why the sum won't be calculated and always show me the message "pas tous entiers" even if all types value are "int".
ZurdoDev 11-Nov-19 14:50pm    
We can't because we can't run your code. Just debug it and see what's happening. It's very easy.

Don't use Convert functions except on values you know are valid: since you don't know if it's an integer you need to use int.TryParse instead - it returns a bool to say "converted / not valid".
C#
int value;
if (int.TryParse(dataGridView1.Rows[i].Cells[2].Value, out value))
   {
   s += value;
   }
 
Share this answer
 
Comments
foreigh 11-Nov-19 16:13pm    
when i try that it shows me the error =>cannot convert object to string
You can find out if there is an int type column like this:
bool exists = false;

foreach (DataColumn col in dt.Columns)
{
    if (col.DataType.Name == "Int32")
    {
        exists = true;
    }
}
 
Share this answer
 
Quote:
C#
DataTable dt = new DataTable("Table_insertion");
bool exists = dt.AsEnumerable().Any(row => type == row.Field<String>("Type"));
You create a new empty DataTable, which doesn't have any rows. You then test to see whether any of the zero rows in that table match your condition.

Unsurprisingly, the answer will always be "no". :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900