C# – Can’t activate message box with SQL data – ASP.NET

ado.netasp.netcpopulatesql

I am testing my knowledge of ADO.NET and SQL and am currently just trying to do the basics. I want to read from a table and when the user clicks a button, a message box pops up with the value in the ApplicationName column.

It currently doesn't do anything when I click the button… any ideas?

protected void TestSubmit_ServerClick(object sender, EventArgs e)
    {
        // Initialize the database connector.
        SqlConnection connectSQL = new SqlConnection();

        // Send the connection string.
        connectSQL.ConnectionString = @"Data Source = localhost\SQLEXPRESS;" + 
            "Initial Catalog = Inputs; Integrated Security = SSPI";

        try
        {
            // Setup our command.
            SqlCommand theCommand = new SqlCommand("SELECT * FROM Inputs", connectSQL);

            // Write the stored value in the text boxes.
            connectSQL.Open();

            SqlDataReader theReader;

            theReader = theCommand.ExecuteReader();
            theReader.Read();
            MessageBox(theReader["ApplicationName"].ToString());

            theReader.Close();
            connectSQL.Close();
        }
        catch (Exception ee)
        {
            MessageBox("Oopsie: " + ee);
        }       

 private void MessageBox(string msg)
    {
        Label lbl = new Label();
        lbl.Text = "" + Environment.NewLine + "window.alert('" + msg + "')";
        Page.Controls.Add(lbl);
    }

Best Answer

You are basically just sending "window.alert('your message');" as HTML to the browser, this wont execute as JavaScript. Do you really want it to be a "popup"? If so consider using RegisterStartupScript() instead of outputting the JS via a label (http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx). If not then why not just set the contents of the label to your return message?

Related Topic