Loosing focus inside the Update Panel Hi I am using Update panel and atimer control.I have a text box inside the update panel..when I am typing something I am loosing focus ..also on my div tage always my scroll bar will come to bottom after my timer interval..User cant able to scroll bar. Another issue is if I am trying to focus my textbox using text changed event then if open diffrent ie the focus will automatically come to my textbox control after the timer inetrval for the first time after that it will happen frequently below is my code snippet <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ChatWindow.aspx.cs" Inherits="ChatApplication.ChatWindow" Theme="Theme1" MaintainScrollPositionOnPostback="true"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>Private Chat</title> <script type="text/javascript"> function SetScrollPosition() { var div = document.getElementById('divMessages'); div.scrollTop = div.scrollHeight; }
function SetToEnd(txtMessage) {
if (txtMessage.createTextRange) { var fieldRange = txtMessage.createTextRange(); fieldRange.moveStart('character', txtMessage.value.length); fieldRange.collapse(); fieldRange.select(); } var div = document.getElementById('divMessages'); div.scrollTop = div.scrollHeight; }
function ReplaceChars() { var txt = document.getElementById('txtMessage').value; var out = "<"; /* replace this*/ var add = ""; /* with this*/ var temp = "" + txt; /* temporary holder*/
while (temp.indexOf(out) > -1) { pos = temp.indexOf(out); temp = "" + (temp.substring(0, pos) + add + temp.substring((pos + out.length), temp.length)); }
document.getElementById('txtMessage').value = temp; }
function FocusThisWindow(result, context) { /* don't do anything here*/ }
function FocusMe() { FocusThisWindowCallBack('FocusThisWindow'); } </script> </head> <body style="background-color: gainsboro; margin: 0 0 0 0;" onload="SetScrollPosition()"> <form id="form1" runat="server"> <div> <asp:Label Id="lblFromUserId" Visible="false" runat="server" /> <asp:Label Id="lblToUserId" Visible="false" runat="server" /> <asp:Label Id="lblFromUsername" Visible="false" runat="server" /> <asp:Label Id="lblMessageSent" Visible="false" runat="server" /> <asp:ScriptManager Id="ScriptManager1" runat="server" /> <script type="text/javascript"> var xPos, yPos; var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_beginRequest(BeginRequestHandler); prm.add_endRequest(EndRequestHandler); function BeginRequestHandler(sender, args) { xPos = $get('divMessages').scrollLeft; yPos = $get('divMessages').scrollTop; } function EndRequestHandler(sender, args) { $get('divMessages').scrollLeft = xPos; $get('divMessages').scrollTop = yPos; } </script> <asp:UpdatePanel Id="UpdatePanel1" runat="server"> <Triggers> <%--<asp:AsyncPostBackTrigger ControlId="Timer1" />--%> </Triggers> <ContentTemplate> <asp:Timer Id="Timer1" Interval="7000" OnTick="Timer1_OnTick" runat="server" /> <div id="divMessages" style="background-color: White; border-color:Black;border-width:1px;border-style:solid;height:160px;width:388px;overflow:scroll; font-size: 11px; padding: 4px 4px 4px 4px;" onload="SetScrollPosition()"> <asp:Literal Id="litMessages" runat="server" /> </div> <asp:TextBox Id="txtMessage" onkeyup="ReplaceChars()" runat="server" Width="340px" onclick="FocusMe()" onfocus="SetToEnd(this)" /> <%--<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>--%> <asp:Button Id="btnSend" runat="server" Text="Send" OnClientClick="SetScrollPosition()" OnClick="BtnSend_Click" /> </ContentTemplate> </asp:UpdatePanel> </div> </form> </body> </html> code behind using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;
namespace ChatApplication { public partial class ChatWindow : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler { private string _callBackStatus; string connectionstring; string DBName; string ChatUsername; protected void Page_Load(object sender, EventArgs e) { DBName = (string)Request["DBName"]; ChatUsername = (string)Request["From"];
Page.Title = lblFromUsername.Text + " - Private Message .................................................................."; if (!IsPostBack) { lblFromUsername.Text = (string)Request["Username"]; Page.Title = lblFromUsername.Text + " - Private Message .................................................................."; lblFromUserId.Text = (string)Request["FromUserId"]; lblToUserId.Text = (string)Request["ToUserId"]; string isReply = (string)Request["IsReply"];
if (isReply == "yes") { lblMessageSent.Text = ConfigurationManager.AppSettings["ChatWindowMessageSent"]; }
// focus this window string chatWindowToFocus = lblFromUserId.Text + "_" + lblToUserId.Text; Session["DefaultWindow"] = chatWindowToFocus; this.FocusThisWindow();
// create a call back reference so that we can refocus to this window when the cursor is placed in the message text box string focusWindowCallBackReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "FocusThisWindow",""); string focusThisWindowCallBackScript = "function FocusThisWindowCallBack(arg, context) { " + focusWindowCallBackReference + "; }"; Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "FocusThisWindowCallBack", focusThisWindowCallBackScript, true); }
}
protected void BtnSend_Click(object sender, EventArgs e) {
if (txtMessage.Text.Length > 0) { this.InsertPrivateMessage(); this.InsertMessage(); this.GetPrivateMessages(); txtMessage.Text = String.Empty; this.FocusThisWindow(); } } // This is where we send a private chat invitation to other chatters private void InsertPrivateMessage() { // if the private message is sent to this user already, // don't send it again if (String.IsNullOrEmpty(lblMessageSent.Text)) { // if any private message is found based on the // from user id, or the to user id, then this // private message will not be inserted ChatPrivateMessage privateMessage = new ChatPrivateMessage(); privateMessage.IdUser = Convert.ToInt32(lblFromUserId.Text); privateMessage.IdToUser = Convert.ToInt32(lblToUserId.Text); privateMessage.CreatedBy = ChatUsername; privateMessage.CreatedDate = System.DateTime.Now; privateMessage.ModifiedBy = ChatUsername; privateMessage.ModifiedDate = System.DateTime.Now;
LinqChatDataContext db = new LinqChatDataContext(); //string DBName = Session["DataBase"].ToString(); connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["mycon"].ConnectionString; connectionstring = connectionstring.Replace("DBName", DBName); db = new LinqChatDataContext(connectionstring); db.ChatPrivateMessages.InsertOnSubmit(privateMessage); db.SubmitChanges();
// make sure to assign any value to this label // to confirm that a message is sent to this user lblMessageSent.Text = ConfigurationManager.AppSettings["ChatWindowMessageSent"]; } } /// <summary> /// Because of the existence of the ToUserID (the user that we want to privately chat with) /// we are only retrieving private messages between two (2) users /// </summary> private void InsertMessage() { ChatMessage message = new ChatMessage(); message.IdUser = Convert.ToInt32(lblFromUserId.Text); message.IdToUser = Convert.ToInt32(lblToUserId.Text); message.TimeStamp = DateTime.Now; message.Text = txtMessage.Text.Replace("<", ""); message.CreatedBy = ChatUsername; message.CreatedDate = System.DateTime.Now; message.ModifiedBy = ChatUsername; message.ModifiedDate = System.DateTime.Now; LinqChatDataContext db = new LinqChatDataContext(); //string DBName = Session["DataBase"].ToString(); connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["mycon"].ConnectionString; connectionstring = connectionstring.Replace("DBName", DBName); db = new LinqChatDataContext(connectionstring); db.ChatMessages.InsertOnSubmit(message); db.SubmitChanges(); } private void GetPrivateMessages() { LinqChatDataContext db = new LinqChatDataContext(); // string DBName = Session["DataBase"].ToString(); connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["mycon"].ConnectionString; connectionstring = connectionstring.Replace("DBName", DBName); db = new LinqChatDataContext(connectionstring); var privateMessages = (from m in db.ChatMessages where (m.IdUser == Convert.ToInt32(lblFromUserId.Text) && m.IdToUser == Convert.ToInt32(lblToUserId.Text)) || (m.IdUser == Convert.ToInt32(lblToUserId.Text) && m.IdToUser == Convert.ToInt32(lblFromUserId.Text)) orderby m.TimeStamp descending select m).Take(20).OrderBy(m => m.TimeStamp);
if (privateMessages != null) { StringBuilder sb = new StringBuilder(); int ctr = 0; // toggle counter for alternating color
foreach (ChatMessage message in privateMessages) { // alternate background color on messages if (ctr == 0) { sb.Append("<div style='padding: 10px;'>"); ctr = 1; } else { sb.Append("<div style='background-color: #EFEFEF; padding: 10px;'>"); ctr = 0; }
sb.Append("<span style='color: black; font-weight: bold;'>" + message.User1.Login + ":</span> " + message.Text + "</div>"); }
litMessages.Text = sb.ToString(); } } protected void Timer1_OnTick(object sender, EventArgs e) { this.GetPrivateMessages();
if (Session["DefaultWindow"] != null) { this.FocusThisWindow(); } }
private void FocusThisWindow() { string chatWindowToFocus = lblFromUserId.Text + "_" + lblToUserId.Text;
if (Session["DefaultWindow"].ToString() == chatWindowToFocus) { form1.DefaultButton = "btnSend"; form1.DefaultFocus = "txtMessage"; } }
#region ICallbackEventHandler Members
string System.Web.UI.ICallbackEventHandler.GetCallbackResult() { return _callBackStatus; }
void System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent(string eventArgument) { if (!String.IsNullOrEmpty(eventArgument)) { if (eventArgument == "FocusThisWindow") { string chatWindowToFocus = lblFromUserId.Text + "_" + lblToUserId.Text; Session["DefaultWindow"] = chatWindowToFocus; this.FocusThisWindow(); } } }
#endregion
} }