ninpi
ninpi

Reputation: 17

Check value of datatable with C#

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!

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");
        }

    }

Upvotes: 0

Views: 830

Answers (2)

tmaj
tmaj

Reputation: 34947

The datatable seems unnecessary here.

Maybe the following is enough.

for (i = 0; i < dataGridView1.Rows.Count; ++i)
{
  var str = dataGridView1.Rows[i].Cells[2].Value?.ToString();

  if( !string.IsNullOrEmpty(str) && Int32.TryParse(str, out var parsed)
  {
     s += parsed;
  }
}

If you want to check the type of the column in a datatable you can check its DataType.

foreach (var col in datatable1.Columns) 
{
      if ( col.DataType == typeof(System.Int16) || col.DataType == typeof(System.Int32)) // Or other types 
      {
           ....

Upvotes: 1

RobertC
RobertC

Reputation: 590

Are you just trying to evaluate if the string returned contains only numbers? If so, you may want to use a regex match on the data. There is a great example here: Regex for numbers only

Upvotes: 0

Related Questions