// Use int.TryParse to safely convert the QueryString value to an integer
int.TryParse(Request.QueryString["ID"], out int getId);
string queryYear = "SELECT Year from MyTable where ColID = @ColID";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(queryYear, conn))
{
cmd.Parameters.AddWithValue("@ColID", getId);
conn.Open();
using (SqlDataReader readerYear = cmd.ExecuteReader())
{
bool isFirst = true;
int positionCounter = 1;
while (readerYear.Read())
{
// If it is NOT the first item, append a comma to the PREVIOUS item before writing the next one
if (!isFirst)
{
jsonBuilder.AppendLine(",");
}
// C# string interpolation makes this much cleaner to read than VB concatenation
jsonBuilder.Append($" {{ \"@type\": \"ListItem\", \"position\": {positionCounter}, \"name\": \"{game} {readerYear["Year"]?.ToString()} Archive\" }}");
positionCounter++;
isFirst = false;
}
// Add a final newline after the loop finishes if any records were read
if (!isFirst)
{
jsonBuilder.AppendLine();
}
}
}
}
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "ItemList",
"name": "MyList Years History Archive",
"description": "Browse past history for MyList grouped by year.",
"itemListElement": [
{ "@type": "ListItem", "position": 1, "name": "MyList 2010 Archive" },
{ "@type": "ListItem", "position": 2, "name": "MyList 2011 Archive" },
{ "@type": "ListItem", "position": 3, "name": "MyList 2012 Archive" },
{ "@type": "ListItem", "position": 4, "name": "MyList 2013 Archive" },
{ "@type": "ListItem", "position": 5, "name": "MyList 2014 Archive" },
{ "@type": "ListItem", "position": 6, "name": "MyList 2015 Archive" },
{ "@type": "ListItem", "position": 7, "name": "MyList 2016 Archive" },
{ "@type": "ListItem", "position": 8, "name": "MyList 2017 Archive" },
{ "@type": "ListItem", "position": 9, "name": "MyList 2018 Archive" },
{ "@type": "ListItem", "position": 10, "name": "MyList 2019 Archive" },
{ "@type": "ListItem", "position": 11, "name": "MyList 2020 Archive" },
{ "@type": "ListItem", "position": 12, "name": "MyList 2021 Archive" },
{ "@type": "ListItem", "position": 13, "name": "MyList 2022 Archive" },
{ "@type": "ListItem", "position": 14, "name": "MyList 2023 Archive" },
{ "@type": "ListItem", "position": 15, "name": "MyList 2024 Archive" },
{ "@type": "ListItem", "position": 16, "name": "MyList 2025 Archive" },
{ "@type": "ListItem", "position": 17, "name": "MyList 2026 Archive" }
]
}
</script>