I am working on a loop that generates buttons and assigns them unique IDs. I want to check if the ID of the button exists in an SQL table, and based on that information, set the color of the button to red or green.
function InitializeButtons() {
for (i = 1; i <= 10; i++) {
var btn = document.createElement("BUTTON");
btn.id = i ;
btn.style.cssText = 'height:50px;width:50px;margin:5px;';
if (PageMethods.Check(btn.id) == true)
{
btn.style.cssText ='background:red;height:50px;width:50px;margin:5px;';
}
else
{
btn.style.cssText = 'background:green;height:50px;width:50px;margin:5px;';
}
document.getElementById("div1").appendChild(btn);
}
The C# function 'Check' below checks if there is a row in the SQL table "Book" with a matching name in the column 'Name' to the passed value 'ID'.
[System.Web.Services.WebMethod]
public static bool Check(string ID)
{
string connectionString = ConfigurationManager.ConnectionStrings["SimpleDB"].ToString();
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(@"
IF EXISTS(SELECT 1 FROM Book Where Name = @ID)
SELECT 1 ELSE SELECT 0", con))
{
con.Open();
cmd.Parameters.AddWithValue("@ID", ID);
int result = Convert.ToInt32(cmd.ExecuteScalar());
return (result == 1);
}
}
However, when calling the Check function like this
if (PageMethods.Check(btn.id) == true)
All buttons end up being green, regardless of whether their IDs match the values in the SQL table column 'Name' or not.