var result = gridView1.Rows.Cast<GridViewRow>()
.Select(r =>
{
_ = int.TryParse(r.Cells["Id"].Value?.ToString(), out var numeric);
return numeric;
}).Max();
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);
//...
3
Answers
You can try with a
Parse()
methodSomething like this would help you:
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.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.
I can get the cell(s) populated with Id field using this code snippet.