简体   繁体   中英

How to create asp.net app combining ListBox, TextBox and Button

I'm designing small instant messenger app on .NET platform.

I have a ListBox , TextBox and Button (called Send).
When user click send button , Text of TextBox will be appeared on ListBox but user should not send 3 messages in 1 minute(message restriction) and also his/her size of message should consist min 20 max 140 strings.

How can I do this?

The example below uses the timer control, if you would like to learn more about using timers in ASP.NET have a look at this video tutorial by Joe Stagner.

Basically I'm storing the number of messages in ViewState and when that number reaches 3 I start the timer which will reset the ViewState["Messages"] back to 0 after 1 minute (60 000 milliseconds) and the user is once again able to send more messages.

ASPX:

    <asp:ScriptManager ID="Scriptmanager" runat="server" />
    <asp:Timer ID="timer" runat="server" Enabled="false" Interval="60000" OnTick="Tick" />
    <asp:UpdatePanel ID="updatePanel" runat="server">
        <ContentTemplate>
            <asp:TextBox MaxLength="140" ID="txtMessage" runat="server" />&nbsp;
            <asp:Button ID="btnSend" runat="server" Text="Send" OnClick="Send" />&nbsp; <span
                id="error" runat="server" style="color: Red;" />
            <br />
            <asp:ListBox ID="lbMessages" runat="server" Width="240" />
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="timer" />
        </Triggers>
    </asp:UpdatePanel>

Code behind:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
        ViewState["Messages"] = 0;
}

public void Send(object sender, EventArgs e)
{
    error.InnerHtml = string.Empty;
    string message = txtMessage.Text;

    if (message.Length < 20)
    {
        error.InnerHtml = "The message should be at least 20 characters long";
        return;
    }

    int messageNumber = (int)ViewState["Messages"];
    if (messageNumber < 3)
    {
        lbMessages.Items.Add(message);
        ViewState["Messages"] = ++messageNumber;

        if (messageNumber.Equals(3))
            timer.Enabled = true;
    }
}

protected void Tick(object sender, EventArgs e)
{
    ViewState["Messages"] = 0;
    timer.Enabled = false;
}

Also you don't need to check for maximum length in code, there is a property for that on the textbox - MaxLength

Maybe you can set an hidden field in your page load to store serialised three last requests time and another for last minute message count.

in the click button event get text of the textbox apply your size restriction and verify message count.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM