where are you trying to run this loop to add buttons.
are you doing a databind on gridview after that ?
If u add these 'buttons calling java-script function' on gridview.rowcreated event, they should work.
try something like below (just wrote it not tested)
void GridView_RowCreated(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
Button btn= (Button)e.Row.FindControl("btnaddcart");
btn.Attributes["onclick"] = "showstock()";
}
}