Reputation: 85
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
Reputation: 40
Here is my suggestions:
Upvotes: 1
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
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