-3

I want to display the largest value in the ["id"] field in massbox

 private void button1_Click(object sender, EventArgs e) 
       {           
        string s=null;
        foreach (DataRow a in amDataSet.students.Rows)
        {
            if (a["id"] > s)
            {
                s = a["id"].ToString();
            }
        }
        MessageBox.Show(s);
        }
  • What you want to achieve is quite impossible to understand. What do you mean by "the largest value" if you are trying to compare a string with a unknown object? What do you expect `a["id"]` to be? – Federico Dipuma May 13 '17 at 11:08
  • i have a field named "id" data type it int I want to show the largest number in the message box @ Federico Dipuma – Ahmed Kareem May 13 '17 at 11:15
  • "a" is a datarow pointer in the dataset @Federico Dipuma – Ahmed Kareem May 13 '17 at 11:18
  • @AhmedKareem You know it's an int but the compiler doesn't. You need to cast it, e.g. (int)(a["id"]). Also `int > string` makes no sense, so it's unclear what you're really trying to achieve here. (Consider _"is 14 greater than 'hello'?"_ - that's an int > string comparison) – Luke Briggs May 13 '17 at 11:18
  • Mr @Luke Briggs Is there another way to get the MAX value in this field?can i convert from string or object to int – Ahmed Kareem May 13 '17 at 11:21
  • @AhmedKareem You'd always have to compare int with another int :) See e.g. [How to select min and max values of a column in a datatable?](http://stackoverflow.com/questions/2442525/how-to-select-min-and-max-values-of-a-column-in-a-datatable) - this is casting too. – Luke Briggs May 13 '17 at 11:24

1 Answers1

-1

If id is numeric type, you can try DataTable.Compute :

int max = Convert.ToInt32( amDataSet.students.Compute("max(id)", "") );

or using the Enumerable.Max LINQ extension :

int max = amDataSet.students.Rows.Cast<DatRow>().Max(r => Convert.ToInt32(r["id"]));
Slai
  • 22,144
  • 5
  • 45
  • 53