Hameed
Hameed

Reputation: 85

How to display alert message when SQL COMMAND return null? ASP.NET C#

I want that when SqlCommand returns zero result or null, then show alert message. I try but it always giving me

Object reference not set to an instance of an object.

Here is my code

ASPX.CS

public void gettable()
{
    string user = Session["name"].ToString();

    SqlConnection cnn = new SqlConnection("Data Source=LIFE_WELL;Initial Catalog=db_compiler;Integrated Security=True");
    //string db = Session["value"].ToString();

    string db = Session["value"].ToString();

    SqlCommand cmd3 = new SqlCommand("SELECT Database_id from Create_db WHERE Database_Name='" + db + "'", cnn);

    cnn.Open();

    string dbid = cmd3.ExecuteScalar().ToString();

    SqlCommand cmd4 = new SqlCommand("SELECT DISTINCT (Table_Name) from tbl_field WHERE Database_id=" + dbid + "", cnn);
    string tbl_name = cmd4.ExecuteScalar().ToString();

    DataTable dt = new DataTable();
    SqlDataAdapter da = new SqlDataAdapter(cmd4);
    da.Fill(dt);

    if (dt.Rows.Count == 0)
    {
        Response.Write("<Script>alert('" + Server.HtmlEncode("No Tables Found") + "')</Script>");
    }
    else
    {
        foreach (DataRow dr in dt.Rows)
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
            cnn.Close();
        }
    }
}

Upvotes: 0

Views: 1578

Answers (3)

yu wayne
yu wayne

Reputation: 40

Here is my suggestions:

  1. Data binding is one thing, display message is another. You should do data boning first, then display any message to users.
  2. Do remember to close DB connection, or it will be a disaster.
  3. I don't think you have to data binding in a loop, just do it one time.
  4. You can refer "registerstartupscript" in MSDN.

Upvotes: 1

Nazir Ullah
Nazir Ullah

Reputation: 610

try this

if (dt == null || dt.Rows.Count <= 0)
{
 Response.Write("<Script>alert('No Tables Found')</Script>");
 return;
}

also replace your code as

string tbl_name = Convert.ToString(cmd4.ExecuteScalar());

Upvotes: 2

Midhun Mundayadan
Midhun Mundayadan

Reputation: 3182

ExecuteScalar only returns one value. You have to make sure your query only returns that value.

use ExecuteReader

gives you a data reader back which will allow you to read all of the columns of the results a row at a time.

An example would be pulling profile information for one or more users.

SELECT * FROM pro WHERE id = '123456'

Upvotes: 1

Related Questions