skip to Main Content
var result = 0;
try
{
    var MaxID = GridView1.Rows.Cast<GridViewRow>()
                .Max(r => Convert.ToInt32(r.Cells["Id"].Value));
    result = (MaxID + 1);
}
catch (Exception ex)
{
    Label6.Text ="Err " + ex ;
}

The Error

How can i fix that error? I am new to ASP.NET

3

Answers


  1. You can try with a Parse() method

    var result = 0;
            try
            {
                var MaxID = GridView1.Rows.Cast<GridViewRow>()
                            .Max(r => Int32.Parse(r.Cells["Id"].Value));
                result = (MaxID + 1);
            }
            catch (Exception ex)
            {
                Label6.Text ="Err " + ex ;
            }
    
    Login or Signup to reply.
  2. Something like this would help you:

    var result = gridView1.Rows.Cast<GridViewRow>()
                .Select(r =>
                {
                    _ = int.TryParse(r.Cells["Id"].Value?.ToString(), out var numeric);
                    return numeric;
                }).Max();
    
    Login or Signup to reply.
  3. var MaxID = GridView1.Rows.Cast()
    .Max(r => Convert.ToInt32(r.Cells["Id"].Value));

    Please note that r.Cells would return TableCellCollection object, you use r.Cells["Id"] to access specific cell instead of use index of cells, which would cause the error, like below.

    Argument 1: cannot convert from ‘string’ to ‘int’

    To fix it, you can check the datasource that you use to populate the GridView1, so that you can find the actual index of Id column in your datasource, then you can use that index to access the cell.

    For example, I populate the GridView with this source.

    var dt = new DataTable();
    dt.Columns.Add("Id");
    dt.Columns.Add("Name");
    dt.Rows.Add(1, "N1");
    dt.Rows.Add(2, "N2");
    
    GridView1.DataSource = dt;
    GridView1.DataBind();
    

    I can get the cell(s) populated with Id field using this code snippet.

    var result = 0;
    try
    {
        var MaxID = GridView1.Rows.Cast<GridViewRow>()
                    .Max(r => Convert.ToInt32(r.Cells[0].Text));
        result = (MaxID + 1);
    
        //...
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search