Muhammad Ibrar Muhammad Ibrar - 1 month ago 19
C# Question

Why Label in if else condition not calling in ASP.NET WebForms?

I am applying search using a textbox and button and results are shown in GridView in ASP.NET. If result do not match with the search then I want that the Label1 "your search do not match" should be visible.
Here is issue that if search result do not match, Label1 is not called.
the code is given below:

SqlConnection con4 = new SqlConnection("Data Source=***; Initial Catalog=***;Integrated Security=***;");
SqlCommand cmd4 = new SqlCommand("select newsid, title, thumbnail,imagepath,imagename from addnews where (title like'%" + TextBox1.Text.ToString() + "%')", con4);
SqlDataAdapter sda4 = new SqlDataAdapter(cmd4);
DataTable dt4 = new DataTable();

sda4.Fill(dt4);
if (dt4 != null)
{
GridView3.DataSource = dt4;
GridView3.DataBind();
}
else
{
Label1.Visible = true;
}


ASPX markup

<asp:Label ID="Label1" runat="server" ForeColor="Red" Text="Search do not match" Visible="False"></asp:Label>
<asp:GridView ID="GridView3" runat="server"> </asp:GridView>

Answer

Refer the below code:

DataTable dt4 = new DataTable();

sda4.Fill(dt4);
if (dt4.Rows.Count > 0)
{
    GridView3.DataSource = dt4;
    GridView3.DataBind();
}
else
{
    Label1.Visible = true;
}