This foreach loop works fine while testing and only returning 5 rows of data, but I am well aware of how porly it is written , is there a better way, possibly using stringbuilder to re-write this more efficiently?
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connstring"].ConnectionString);
SqlCommand comm = new SqlCommand("SELECT Title, StartDate FROM tblEvents JOIN eo_UserEventWatch ON eo_UserEventWatch.EventID=tblEvents.ID WHERE eo_UserEventWatch.UserID = @GUID ;", conn);
comm.Parameters.AddWithValue("GUID", userID);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(comm);
DataTable dt = new DataTable();
da.Fill(dt);
string result ="{ \"event\" :[";
foreach (DataRow dr in dt.Rows)
{
result += "{\"title\" : \"" + dr[0].ToString() + "\" , \"start\" : \"" + dr[1].ToString() +"\"} ,";
}
result = result.TrimEnd(',');
result += "] }";
return result;
Well yes, it would be more efficient to use
StringBuilder:However, it’s still not nice code – because you’ve got all that horrible literal JSON. I would suggest using Json.NET or another JSON library. You can probably use LINQ at that point, e.g.
Aside from anything else, now you don’t need to worry about the format of the start value, or whether the title contains quotes etc.
(EDIT: As noted, you should absolutely have
usingstatements for SQL connections etc. That’s outside the main point of the question, which is why I didn’t mention it here.)