0

I have a simple application in ASP.NET C# and using MS SQL Server 2008. I need to register all visitor users to my site. For that users will have to fill a form. The problem is that as the user enters the Desired Username field, I should be able to check in background whether another user has already taken that username. I will have to fire an sql select query to check for the availability.

Currently I am using the TextBoxName_TextChanged method but it does not work in realtime. It works only on a postback. The code is that follows:

protected void TextBox3_TextChanged(object sender, EventArgs e)
        {
            if (TextBox3.Text.Length == 0)
            {
                availability.Text = "";
                return;
            }

            SqlDataAdapter adp = new SqlDataAdapter("select username from users where username='" + TextBox3.Text + "'", con);
            DataSet ds = new DataSet();
            adp.Fill(ds, "users");
            if (ds.Tables["users"].Rows.Count > 0)
            {
                availability.ForeColor = System.Drawing.Color.Red;
                availability.Text = "Not Available";
            }
            else
            {
                availability.ForeColor = System.Drawing.Color.White;
                availability.Text = "Available";
            }

        }

Please suggest me something as all I searched on web was about PHP, Not ASP.NET

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
</asp:UpdatePanel>
    <table cellpadding="5" class="style1"> 
        <tr>
            <td class="style3">
                <asp:Label ID="Label3" runat="server" Text="Username" ForeColor="White"></asp:Label>&nbsp;&nbsp; </td>
            <td style="border:0px none #FF0000;">
                <asp:TextBox ID="TextBox3" runat="server" Width="175px" 
                    CssClass="input-control" ForeColor="Black" ontextchanged="TextBox3_TextChanged" AutoPostBack="true"></asp:TextBox></td>
        </tr>
        <tr>
            <td class="style3"></td>
            <td style="border:0px none #FF0000;"> 

                <asp:Label ID="availability" runat="server" Width="175px" CssClass="text" Text="availability"></asp:Label></td>
        </tr>
        <tr>
            <td class="style3">
                <asp:Label ID="Label4" runat="server" Text="Password" ForeColor="White"></asp:Label>&nbsp;&nbsp;&nbsp; </td>
            <td style="border:0px none #FF0000;">
                <asp:TextBox ID="TextBox4" runat="server" Width="175px" TextMode="Password" CssClass="input-control" ForeColor="Black"></asp:TextBox></td>
        </tr>
        <tr>
            <td class="style3">
                <asp:Label ID="Label5" runat="server" Text="Email" ForeColor="White"></asp:Label>&nbsp;&nbsp;&nbsp; </td>
            <td style="border:0px none #FF0000;">
                <asp:TextBox ID="TextBox5" runat="server" Width="175px" CssClass="input-control" ForeColor="Black"></asp:TextBox></td>
        </tr>

        <tr>

            <td class="style3">

            <td style="width:30%; text-align: right; padding: 10px; border:none;">
                <div class="button-set" data-role="button-set">
                    <asp:Button ID="Button2" runat="server" class="active bg-color-red" Text="Sign Up" />
                </div>
        </tr>
        </table></asp:UpdatePanel>

Update:

Following Everybody's comments and answers I have achieved this much with a little problem shown in this screenshot: Screenshot Don't know why there are another label with status and the availability_status stays as it is. Please help.

Samarth Agarwal
  • 2,044
  • 8
  • 39
  • 79

5 Answers5

1

You need to fire off your request via AJAX. Hook up to the 'changed' event of the text box client side and trigger it from there - best option would be to use jQuery e.g.

<script text="text/javascript">

$(document).ready(function() {
    var searchTimer;
    ...
    $('TextBox3').change(function() {
        var searchTerm = $(this).val();
        clearTimer(searchTimer);
        searchTimer = setTimeout(1000, function() {
            $.get('findUsers', { userName: searchTerm }, function(response) {
                // process successful response
            }).error(function(error) {
                // process error response
            });
        });
    });
});
<script>

<table>
    ...
    <input type="text" id="TextBox3" />
</table>

The above would fire a request to an API call "findUsers" 1 second after every text change. This is to avoid sending unnecessary requests when the user is typing as you only want to send the request when the user has finished.

James
  • 80,725
  • 18
  • 167
  • 237
  • How can I do that? I think that is what I want, something that keeps firing sql queries as I type in that TextBox. – Samarth Agarwal Jan 12 '13 at 09:10
  • @SamarthArgarwal I was in the middle of adding an example, I am on my mobile so not quite as easy to type/formatting code! – James Jan 12 '13 at 09:27
  • Which language is this example in? – Samarth Agarwal Jan 12 '13 at 09:28
  • It's Javascript, it's also using [jQuery](http://jquery.com/) which makes writing client side AJAX requests simple (as per the example) – James Jan 12 '13 at 09:33
  • Thanks for your effort. I don't feel like understanding it at all! I have a ASP.NET project. Where do I put it? – Samarth Agarwal Jan 12 '13 at 09:34
  • I have updated the answer to show you an example of where you would place the code. However, if you don't know anything about client-side programming I suggest you read a bit more into it... – James Jan 12 '13 at 09:46
  • Thank you. Can you please tell me a little more about it? Like what things do I need to replace? What is findUsers? What should I replave it with in my code? – Samarth Agarwal Jan 12 '13 at 10:00
  • @SamarthAgarwal I suggest you go *research* client-side programming as it's a pretty large topic...not suitable for an SO comment. Don't take the example I have provided literally it was for demonstration purposes - you won't have an API call `findUsers` that was just an example. What you would need to do is create your own API call which you can query to give you what you need to know. – James Jan 12 '13 at 10:12
1

Does the textbox have AutoPostBack="true" ? You will certainly need to add an UpdatePanel aroud your textbox in order to prevent the full page load.

Stephane Mathis
  • 6,542
  • 6
  • 43
  • 69
1

I believe that you're update panel is not well formatted. You need to put "availability" label into update panel, then set a trigger for the username text box and then set the event name. something like :

 <asp:UpdatePanel ID="UpdatePanel1" runat="server">
  <ContentTemplate>
    <asp:Label ID="availability" AppendDataBoundItems="true" runat="server" >                                         
    </asp:Label>
  </ContentTemplate>
  <Triggers>
   <asp:AsyncPostBackTrigger ControlID="TextBox3" EventName="TextChanged" />
    </Triggers>
 </asp:UpdatePanel>

you also nee to set AutoPostBack="True" in your text box. I think it shall work.

Mohsen Rabieai
  • 244
  • 3
  • 17
  • Could not find an event named 'TextBox3_TextChanged' on associated control 'TextBox3' for the trigger in UpdatePanel 'UpdatePanel1'. – Samarth Agarwal Jan 12 '13 at 09:54
  • double check the event name! event name in trigger must be "TextChanged" alone. – Mohsen Rabieai Jan 12 '13 at 09:57
  • Ok, its working. But it updates the Label only when the TextBox loses focus. Is there anyway so that the Label Updates with each character I type? – Samarth Agarwal Jan 12 '13 at 09:58
  • 1
    Postback by default only send when you loose focus on textbox, if you want to fire the event whenever a character is typing, you will need to send postback when a character types. I never done that before, but hell yeah, it's possible. let me work on it. takes some time sorry. hint: I think we must use javascript to manually send postbacks. – Mohsen Rabieai Jan 12 '13 at 10:03
  • 1
    Check if these are helpfull : http://stackoverflow.com/questions/1758240/how-do-i-make-a-textbox-postback-on-keyup http://stackoverflow.com/questions/1009086/how-to-make-an-asp-net-textbox-fire-its-ontextchanged-event-fire-in-an-ajax-upd – Mohsen Rabieai Jan 12 '13 at 10:09
  • Well thanks for the links, they helped and I have almost achieved what I wanted. But one small problem, it displays "Available" and "Not Available" separately and doesn't alter my label text! The label text remains as it is. Why? _Also note that, I have taken out my textbox from the UpdatePanel! Kept my label inside it, AsyncTriggers in place and JS for postbacks on KeyUp. Also set AutoPostback=false._ – Samarth Agarwal Jan 12 '13 at 10:32
  • Please check the screenshot added and help. – Samarth Agarwal Jan 12 '13 at 11:07
0

Finally, I got it working, Thanks to all those who took interest and tried. The solution is to make PostBack on every OnkeyUp event, and this can be done using JS.

The markup is

<asp:TextBox ID="TextBox3" runat="server" Width="175px" 
                    CssClass="input-control" ForeColor="Black" onkeyup="RefreshUpdatePanel();" ontextchanged="TextBox3_TextChanged" AutoPostBack="false"></asp:TextBox>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
                    <ContentTemplate><asp:Label ID="availability" runat="server" Width="175px" CssClass="text" Text="availability_label"></asp:Label>
                    </ContentTemplate>
                    <Triggers>
                        <asp:AsyncPostBackTrigger ControlID="TextBox3" EventName="TextChanged" />
                    </Triggers>

The Javascript is:

<script type="text/javascript">
      function RefreshUpdatePanel() {
          __doPostBack('<%= TextBox3.ClientID %>', '');
      };
</script>

And the code for checking if the username exists or not is written inside the

TextBox3_TextChanged() Method. It worked.

Samarth Agarwal
  • 2,044
  • 8
  • 39
  • 79
-2

I recently built this function you can try it out by yourself.

public bool IsExist(string name, string pass)  /// in your case you only need to save the textbox on a string variable
    {
        string sql = "select * from Users where UName='" + name + "' and Pass='" + pass + "'"; ; 
        DataSet ds = General.GetData(sql); // General class has function called GetData which obviouslly gets the data of the required SQL information.
        if (ds.Tables[0].Rows.Count > 0)
            return true;
        return false;
    }
Oneill
  • 149
  • 1
  • 8
  • The Op isn't asking *how* to query their DB he is asking how to query it without having to do a post back. – James Jan 12 '13 at 09:19