I am facing an issue while trying to execute code in my Code Behind to query my SQL Server using a JavaScript variable and then return the result as an Integer back to my Javascript.
My approach involves running some Javascript code initially to obtain a variable for the SQL SELECT statement, and then passing it to a hidden ASP field (currently set as a textbox for testing).
Unfortunately, whenever I run the code through refreshHTML(), the value of the hidden field (textbox) appears blank, returning 999999999 instead.
Interestingly, when I run the application, the textbox seems to be populated with the correct value.
Below is the C# code from my Code Behind:
public int ucount
{
get
{
if (String.IsNullOrEmpty(invoicenumberhidden.Text))
{
return 999999999;
}
else {
int invoicenumber = int.Parse(invoicenumberhidden.Text);
string commandText = "SELECT COUNT(*) AS distinct_count FROM (SELECT DISTINCT [inv_section],[invoice_number], [cust_po] FROM [Indigo].[dbo].[invoice_items] WHERE invoice_number=" + invoicenumber + ") AS I;";
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Indigo2.Properties.Settings.Constr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(commandText, conn))
{
conn.Open();
cmd.ExecuteNonQuery();
int uniquecount = (Int32)cmd.ExecuteScalar();
conn.Close();
return uniquecount;
}
}
}
}
And here is the relevant JavaScript function triggered by an ASP OnClientClick event:
//Get Primary Key from Grid1
var grid = jQuery("#<%= JQGrid1.ClientID %>");
var rowKey = grid.getGridParam("selrow");
document.getElementById('<%= invoicenumberhidden.ClientID %>').value = rowKey;
var jsucount = '<%=this.ucount%>';
alert(jsucount);
This is the relevant ASP code snippet:
<div hidden> <asp:Button ID="btnDownload" runat="server" OnClientClick="refreshHtml();" OnClick="btnDownloadButton_Click" Text="Export PDF"></asp:Button></div>
<asp:TextBox ID="invoicenumberhidden" runat="server"></asp:TextBox>