.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

what's wrong in my if - else statement?

Posted By:      Posted Date: October 14, 2010    Points: 0   Category :ASP.Net

I have a problem making a couple of if - else statements work. This is what my buttonclick does: It displays ID, last name and firstname of every customer in the database that are registered with the street that is entered in the textbox in question. This works. What doesn't work is when nothing is entered into the textbox (error message label is not showing) or when a street that doesn't exist in the database is entered (error message label is not showing). Can anyone find what's wrong with my code (c#)? Thankful for help!

protected void ButtonSearch_Click(object sender, EventArgs e) 
        LabelNoStreet.Visible = false;
        LabelNoCustomerChosen.Visible = false;
        string Street = TextBoxStreet.Text;

        if (Street != null) 
            SqlConnection conn = new SqlConnection(config);

              string sql = "SELECT ID, firstname, lastname, street FROM Customer WHERE street='" + Street + "'";
              SqlCommand comm = new SqlCommand(sql, conn);
              SqlDataReader dr = comm.ExecuteReader();

                  if(Street == Convert.ToString("street")) 

View Complete Post

More Related Resource Links

Whats wrong with this statement


Im trying to updated some old ASP pages with some new .net pages and cant seem to get this update statement to work. I need to update the current ASP code below and then once thats working im going to use that same statement in a procedure for all our new .Net pages..

So can anyone see what im doing wrong by inserting the 2nd column to the update statement?

strSqual = "update tas set date_completed='" & TransDate & ", trans_id=" & InsertedTransID & "' where date_completed is null and sercontract_id="& strContractID & " and DATEDIFF(dd,task_due_date,'" & strProcDate & "')<=14"


I am trying to add an extra column to the update, but not sure if the syntax is correct.

what is wrong with the Following Update Statement


I have a Select that is defined like this



 select C.Number,A.GrpName from TBL_CNTC C
    ON A.CntcID = C.ID
    where A.GrpName <> C.Number


and it give me records that dont match in the the field "GrpName" and "Number"  and now i want to Update one table from the other like this



                UPDATE TBL_CNTC 
		SET Number = A.GrpName
		ON A.CntcID = C.ID
		where A.GrpName <> C.Number

Now as you can see above i  i want to Update the table TBL_CNTC from the table TBL_ACTV and it looks like like it updated data

(167 row(s) affected)


Passing Linq Statement between master and content page


I usually work with windows forms, and am just starting to work with ASP.Net, so appologies if this is a dumb question!

I have a master page which has a search button on it. The results of this are built up using a Linq statement and if there are any results, I want to display the results in a contents page.

On the masterpage, I have the following code:

Private _res

    Public Overridable ReadOnly Property SearchRes()
            Return _res
        End Get
    End Property

 Private Sub DoSearch()
   'some code to get a linq result

    If res.Any Then
            _res = res
            Server.Transfer("SearchResults.aspx", True)
            'no results
            LabelNoRes.Visible = True
        End If
 End Sub

On the SearchResults.aspx page I have this code.

Dim m As pxSite = CType(Page.Master, MasterPage)
        If m.SearchRes IsNot Nothing Then
            Label1.Text = "Results found = " & m.SearchRes.Count
        End If

m.searchRes is always nothing. 

What am I doing wrong here?


Wrong Account being used to access files - Help - No Impersonation


I run a simple .aspx website on a Windows Server 2008 machine.

There is NO impersonation, and System.Security.Principal.WindowsIdentity.GetCurrent().Name returns NT AUTHORITY\NETWORK SERVICE, which it the account which the application pool runs. In my web.config, I have <authentication mode="Forms">.


I tried to test the security of the application and server by removing file permissions to the .aspx files. I was greatly worried when the website continued to run without problem (it should not have been able to read the .aspx files).

By turning on file level auditing, I discovered that the .aspx files were being read by the machine$ account (if the machine is called Serv1, then the files would be read by the Serv1$ account, which seems to have access to all files on the local machine).


Is this a security breach or is this behaviour by design ?

Please can somebody assist, as I am worried.

ReportViewer :: Failed to enable constraints. But my statement is valid!!

  • A
  • n error has occurred during report processing.
      • Exception has been thrown by the target of an invocation.
        • Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.

    Why do I keep getting this error, even when not using any data on the report. When I run the query in SQL server I get a resultset. However when I try to render the report I get this error.


    If Statement Issue



    This is very strange to me. I have spent 2hrs looking into this inside out , but dont seem to get it

    I have an if statement that inserts data into the database. But i check to make sure the name is not entered twice. Now when the name is already in the db, then it should insert else put out a message saying its already in the db

    My code works fine except that  when its not in the db, its inserts but still puts out the message that says "Name is already in use" Not sure if am not seeing something. But thought i did bring it to the forum. Here is my code...Pretty simple

    Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click

            Dim objConnection As SqlConnection
            Dim objCommand As SqlCommand
            Dim strSQLQuery1 As String


            ' If there's nothing to Add for then don't search
            ' o/w build our SQL Query and execute it.
            If String.IsNullOrEmpty(txtAdd.Text) Or Leadbank.SelectedValue = "000" Then


    statement cannot appear outside of a method body


    hi all,

      i am posting my vb.net problem .plz tell me how to resolve this :-

    Dim conn As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString
        'Dim mysqlconnection As New SqlConnection(conn)
        'If mysqlconnection.State=ConnectionState.closed Then mysqlconnection.Open();
        'Dim mySqlcommand As New SqlCommand("select CategoryId,CategoryName from Categories", mysqlconnection)
        'Dim mySqlDataAdapter As New SqlDataAdapter(mySqlcommand)
        'Dim mydataSet As New DataSet()

        'if mysqlconnection.State=ConnectionState.closed Then mysqlconnection.Open();

    i m getting 5 errors in this code

    declaration expected in mySqlDataAdapter.Fill method; Gridview1.DataSource=ds; Gridview1.DataBind();

    how to multiple condition in if statement in asp.net C#



    i am using if condition to find out a time

    if(time=="08 AM)


    response.write"shift A";


    but problem is how can i put multiple condition in if like

    if(time=="06 AM" and "08 AM" and "07 AM")



    Hello, i need help changing the following code into a switch...case statementUndecided

    <script runat="server">
    void Page_Load()
        if (Page.IsPostBack)
        public String toSring()
        int intcomputerChoice=1;
           if (Page.IsPostBack)

    Usability in Practice: When Things Go Wrong


    This month our usability experts explain what it takes to create informative, useful error messages.

    Dr. Charles Kreitzberg and Ambrose Little

    MSDN Magazine January 2009

    Using a If Else Statement


    I'm working in a Wizard control and need a little help. I'm pulling in a labels text through a databound field and if it equals a certain text then I need a textbox field to be less than or equal to a certain amount. I would also like to have a message appear to prompt the user that an invalid number has been entered. I'm not sure how to go about this. Is it better to use client side javascript or use page load and perform some kind of control validation. The code I've tried isn't working so any help would be greatly appreciated.

    For instance...

    Protected Sub Page_Load(ByVal Sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If label1 = "Refrigerator" then

    TextBox1 <= "700"

    Else Label1 = "Washer" then

    TextBox1 <= "500"

    End if

    End Sub

    The statement terminated. The maximum recursion 100 has been exhausted before statement completion.


    Hi All

    I have the below sql scripts that give me the error:
    "The statement terminated. The maximum recursion 100 has been exhausted before statement completion."

    Ive tried using OPTION ( MAXRECURSION 0 ) or 1000 but it still  give me the same error.

    WITH cte as (SELECT     ticketid, setstatus, setdate, row_number() OVER (partition BY (ticketid)
    ORDER BY setdate ASC) AS rn
    FROM         [OneForm].[dbo].[TFAM_SLA_Times]
    SELECT     TicketID, 'Submitted', SubmittedON, 0
    FROM         [OneForm].[dbo].vw_TFAM_ALL)
        SELECT     a.ticketid, SUM(OneForm.dbo.[CalcMinutesSLA_TFAM](a.setdate, b.setdate)) AS SLA_in_Min
         FROM         vw_TFAM_SLA_Combined AS a LEFT JOIN
                                vw_TFAM_SLA_Combined AS b ON a.ticketid = b.ticketid AND a.rn = b.rn - 1
         WHERE     (a.SetStatus = 'Submitted' OR
                                a.SetStatus = 'Acknowledged' OR
                                a.SetStatus = 'Pending')
         GROUP BY a.TicketID

    If i remove the call to the function [CalcMinutesSLA_TFAM] or the b.rn - 1 it works fine.

    Here is the code for the function:

    CREATE FUNCTION [dbo].[CalcMinutesSLA2

    Wrong root, absolute paths '~' don't work.


    Hi guys,

    I have some kind of strange problem. I use Visual Studio 2008 Standard Edition, and whenever I use ~ in links (like PostBackUrl = "~/Admin/AddProduct.aspx"),  ~ is translated into "C:\DocumentAndSettings\User\Desktop" instead of my application root. Of course I dont have any project on Desktop. It happens in every project I run , even in project from pendrive which works properly on other computers.

    How can i solve this problem ? What and where should i change ? I will be very thankful for any help.


    Whats wrong with this code, im getting blue line under the createStatus next the switch

    Error message: Use of unassigned local variable 'createStatus'
                MembershipCreateStatus createStatus;
                MembershipUser newUser = Membership.CreateUser(Username.Text, Password.Text, Email.Text);
                switch (createStatus)
                    case MembershipCreateStatus.Success:
                        this.CreateAccountResults.Text = "The user account was successfully created!";
                    case MembershipCreateStatus.DuplicateUserName:
                        this.CreateAccountResults.Text = "There already exists a user with this username.";
                    case MembershipCreateStatus.DuplicateEmail:
                        this.CreateAccountResults.Text = "There already exists a user with this email address.";
                    case MembershipCreateStatus.InvalidEmail:
                        this.CreateAccountResults.Text = "There email address you provided in invalid.";
                    case MembershipCreateStatus.InvalidPassword:
                        this.CreateAccountResults.Text = "The password you provided is invalid. It must be seven characters long and have at least one non-a

    Extended MySite: Profile picture uploading to the wrong zone.

    I'm experiencing a problem where uploading a profile picture, in a MySite, uploads it to the wrong zone.

    What I've done is created one web application and configured SSP to use that same one. As a result, the MySite host location is in that same web application:

    Default Zone:
    http://my.domain.com  <-- default SharePoint site.
    http://my.domain.com/personal <-- MySite host

    I then extended that web application to enable FBA & anonymous access:

    Internet Zone:
    http://extended.domain.com <-- extended default SharePoint site.

    Now I"m able to navigate to a user's MySite using the extended URL (http://extended.domain.com/personal)...but when I upload a new profile picture in my MySite... it prompts me for new credentials because it's trying to upload to the Default zone (http://my.domain.com).

    I found the following thread that talks about this...but there wasn't any resolution:

    What is the best practices when configuring a MySite in an extended web application? How can I fix the situation I'm encountering above?

    P.S. I tried to change the MySite Host location (via SSP in the Central Administration)

    Published site - wrong links



    we have published our sharepoint site outside domain.

    Unfortunately big problems with links in document library appeared.

    The url for outside users is "it.company.cz", the internal url is "sp001:55680".

    When I open the page and select Shared Documents, the site is still it.company.cz. But when select any folder in document library the site url changes to sp001:55680.

    Strange is that the mouseover url is correct but when I click it, it changes to internal url.


    Mouseover url: http://it.compay.cz/Shared%20Documents/Forms/AllItems.aspx?RootFolder=%2fShared%20Documents%2fProjects&FolderCTID=&View=%7bBEBFF1D2%2d5910%2d4A36%2dB049%2d971F95E752E7%7d

    After click url: http://sp001:55680/Shared%20Documents/Forms/AllItems.aspx?RootFolder=%2fShared%20Documents%2fProjects&FolderCTID=&View=%7bBEBFF1D2%2d5910%2d4A36%2dB049%2d971F95E752E7%7d

    Please help.

    Where to place if statement


    I have a design problem I could use some help determining how to code this problem.

    I have a table with 3 fields, catCode, startDate and endDate. I am having trouble deciding how to query my DB based on the following...

    By default a gridview will return all records that match the catCode selected from a dropdown list.


    If the user checks a check box, only records are returned where....

    startDate <= today AND endDate >= today


    How can I apply the If condition to compare when the check box is selected? I used the wizard to build the select statment for the gridview, but I can switch that to a SP if that makes life easier.


    Thanks for any and all help and suggestions.

    ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
    Sql Server  SharePoint  Silverlight  Others  All   

    Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend