alert box not showing asp.net - c#

here is my code
ASPX Code:
<asp:Button ID="Button4" runat="server" onclick="Button4_Click" Text="Insert" />
C#:
public void MsgBox(String MessageToDisplay)
{
Label lblForMsg = new Label();
lblForMsg.Text = "<script language='javascript'>window.alert('" + MessageToDisplay + "')</script>";
Page.Controls.Add(lblForMsg);
}
protected void Button4_Click(object sender, EventArgs e)
{
SqlCommand com = new SqlCommand("insert into employe values(#id,#pass)", con);
SqlParameter obj1 = new SqlParameter("#Id", DbType.StringFixedLength);
obj1.Value = TextBox4.Text;
com.Parameters.Add(obj1);
SqlParameter obj2 = new SqlParameter("#pass", DbType.StringFixedLength);
obj2.Value = TextBox5.Text;
com.Parameters.Add(obj2);
com.ExecuteNonQuery();
con.Close();
MsgBox("Account Created");
if (Session["regis"] == null)
{
Response.Redirect("Profile.aspx");
}
else
{
Response.Redirect("Login.aspx");
}
}
i want that when i click on button4, msgbox show, after that when i click ok on msgbox then it check the condition and response to the page.
i am using visual studio 2010,asp.net/c#

To display a javascript alert message you should use RegisterClientScriptBlock
public static void ShowMessageAndRedirect(string message, string lpRedirectPage)
{
string cleanMessage = MessageToDisplay.Replace("'", "\'");
Page page = HttpContext.Current.CurrentHandler as Page;
string script = string.Format("alert('{0}');", cleanMessage);
script += " window.location.href='" + lpRedirectPage+ "';"
if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
{
page.ClientScript.RegisterClientScriptBlock(page.GetType(), "alert", script, true /* addScriptTags */);
}
}
Similar question here: JavaScript: Alert.Show(message) From ASP.NET Code-behind
if (Session["regis"] == null)
{
ShowMessageAndRedirect("Account Created","Profile.aspx");
}
else
{
ShowMessageAndRedirect("Account Created","Login.aspx");
}

I think if you want to display "Account Created to the User then do the following =
Response.Write("window.alert('" + MessageToDisplay + "');");

In your server-side code, you're attempting to add the message box, but immediately after that, either way your method ends with a Response.Redirect - so you're sending the user off to a new page (even if one of those pages is the same URL as the page you came from).
If you want the message box to show if the process was successful (your "account created" scenario), then whichever page you redirect to needs to include that javascript message box when it renders.

Since you like to use MsgBox.show() like that of windows form. This class will help you (vb.net)
Imports Microsoft.VisualBasic
Public Class MsgBox
Public Shared Sub Show(ByRef page As Page, ByVal strMsg As String)
Try
Dim lbl As New Label
lbl.Text = "<script language='javascript'>" & Environment.NewLine _
& "window.alert(" & "'" & strMsg & "'" & ")</script>"
page.Controls.Add(lbl)
Catch ex As Exception
End Try
End Sub
End Class
From within aspx.page, it can be called like this
Msgbox.show(Me,"Alert something")

Related

DotNetNuke WebForm Alert Dialog box

I am currently developing a DotNetNuke module. However, I failed to prompt user an alert dialog box in certain situations like record duplication.
I am using the following code to display an alert box in Controller class.
EditForm edForm = new EditForm();
ScriptManager.RegisterClientScriptBlock(edForm, edForm.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
The following is my full code.
Form.ascx.cs
void cmdUpdate_Click(object sender, EventArgs e)
{
UdtController.UpdateRow(Data, ModuleId, False);
}
UdtController.cs
public void UpdateRow(DataSet ds, int rowNr, bool isDataToImport)
{
var values = new Dictionary<int, string>();
string strIsUnique = "";
foreach (DataRow field in ds.Tables[DataSetTableName.Fields].Rows)
{
var strColumnName = field[FieldsTableColumn.Title].ToString();
strIsUnique = field[FieldsTableColumn.Searchable].ToString();
var strValueColumn = ((!isDataToImport &&
ds.Tables[DataSetTableName.Data].Columns.Contains(strColumnName +
DataTableColumn.
Appendix_Original))
? strColumnName + DataTableColumn.Appendix_Original
: strColumnName);
if (strIsUnique == "True")
{
int uniqueDataCount = FieldController.uniqueData(currentRow[strValueColumn].AsString());
if (uniqueDataCount == 0)
{
if (ds.Tables[DataSetTableName.Data].Columns.Contains(strValueColumn))
{
values.Add(field[FieldsTableColumn.Id].AsInt(), currentRow[strValueColumn].AsString());
}
}
else
{
EditForm edForm = new EditForm();
ScriptManager.RegisterClientScriptBlock(edForm, edForm.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
break;
}
}
else
{
if (ds.Tables[DataSetTableName.Data].Columns.Contains(strValueColumn))
{
values.Add(field[FieldsTableColumn.Id].AsInt(), currentRow[strValueColumn].AsString());
}
}
}
FieldController.UpdateData(userDefinedRowId, values);
}
You need to reference the Page, not create a new form.
Page page = HttpContext.Current.CurrentHandler as Page;
ScriptManager.RegisterStartupScript(page, page.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
However DNN has it's own message box you could use:
http://uxguide.dotnetnuke.com/UIPatterns/AlertDialog.html

Dynamically Created Button refuses to call it's onClick

So while fooling around with webforms, I tried to create a page that outputs a table from a sql server to a html table on Page_Load. I then tried to add a button to a column which would redirect to a page. The only problem is, when I press the button nothing happens at all... I've tried putting breakpoints at the onclick method but they are never reached.
num = ds.Tables[0].Rows.Count;
htmlTable.Append("<tr style='background-color:#bd0000; color: White;'><th>ID</th><th>Job #</th><th>Project</th><th>Completed By</th><th>Date Created</th><th></th></tr>");
if (!object.Equals(ds.Tables[0], null))
{
if (ds.Tables[0].Rows.Count > 0)
{
int MAX_VIEW = (ds.Tables[0].Rows.Count > 15) ? 15 : ds.Tables[0].Rows.Count;
for (int i = 0; i < MAX_VIEW; i++)
{
htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["CCPOF_ID"] + "</td>");
htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["Job_Number"] + "</td>");
htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["Project_Name"] + "</td>");
htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["CompletedBy"] + "</td>");
htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["DateCreated"] + "</td>");
htmlTable.Append("<td width=\"10%\"><button class=\"astext\" name=\"Btn" + ds.Tables[0].Rows[i]["CCPOF_ID"] + "\" id =\"" + ds.Tables[0].Rows[i]["CCPOF_ID"] + "\" OnClick =\"btnEdit_Click\" runat=\"server\" >Edit</button> | Details</td>");
htmlTable.Append("</tr>");
}
htmlTable.Append("</table>");
DBDataPlaceHolder.Controls.Add(new System.Web.UI.WebControls.Literal { Text = htmlTable.ToString() });
}
else
{
htmlTable.Append("<tr>");
htmlTable.Append("<td align='center' colspan='4'>There is no Record.</td>");
htmlTable.Append("</tr>");
}
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
String id = ((System.Web.UI.WebControls.Button)sender).ID;
Server.Transfer("CcpofDetails.aspx?ID=" + id);
}
}
When I inspect the button in the live form this is what I see
<button class="astext" name="Btn10" id="10" onclick="btnEdit_Click" runat="server">Edit</button>
Your way of generating dynamic controls seems very strange to me. It is not the way web-forms work.
To run an event on a control, it has to be loaded into servers memory first. But you are just filling some html text that is understandable only for the browser, not for asp.net engine.
take a look at this sample
To give you a better idea, create your buttons like this
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
AddControls();
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
if (ViewState["controsladded"] == null)
AddControls();
}
private void AddControls()
{
TextBox dynamictextbox = new TextBox();
dynamictextbox.Text = "(Enter some text)";
dynamictextbox.ID = "dynamictextbox";
Button dynamicbutton = new Button();
dynamicbutton.Click += new System.EventHandler(dynamicbutton_Click);
dynamicbutton.Text = "Dynamic Button";
Panel1.Controls.Add(dynamictextbox);
Panel1.Controls.Add(new LiteralControl("<BR>"));
Panel1.Controls.Add(new LiteralControl("<BR>"));
Panel1.Controls.Add(dynamicbutton);
ViewState["controlsadded"] = true;
}
private void dynamicbutton_Click(Object sender, System.EventArgs e)
{
TextBox tb = new TextBox();
tb = (TextBox) (Panel1.FindControl("dynamictextbox"));
Label1.Text = tb.Text;
}
I believe your problem comes from the fact that ASP.NET doesn't know you created a button. As far as it's concerned, all you did was pump out some text to the page.
As a result, when you post back to the server, it doesn't know it needs to do anything on the server side when you click.
Try creating it as an object (a System.Web.UI.WebControls.Button) and adding that to your page's Controls collection. Be aware that you'll have to do this both on the initial page build and on postback: if the control doesn't exist after postback, events that were hooked up to it don't fire.
Getting it to appear in the middle of your table may require you to do your HTML table creation in some other way, such as building a WebControls Table object and adding that to your Controls collection.
You are not adding corectl the button to the web form. Try this way:
Button btnEdit = New Button();
btn.Edit.Click += btnEdit_Click;
frmMain.Controls.Add(btnSave)
As shown in this question too.

Deactivate Middle Mouse Button Move in Windows Browser Form

I got a WebBrowser Control in a Windows Form and i want to use the middle mouse button click to add a new tab to my Browser. The only problem is that everytime i use the middle mouse button, the arrows to move the page appear.
So how can i disable this move/drag command only for the clicks on my links?
try this:
There are two different parts to this solution. The first is pretty easy - just set an event handler for the MouseDown event of your browser control:
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (webBrowser1.Document != null)
{
webBrowser1.Document.MouseDown += Document_MouseDown;
}
}
private void Document_MouseDown(object sender, HtmlElementEventArgs e)
{
if (e.MouseButtonsPressed == System.Windows.Forms.MouseButtons.Middle)
{
e.ReturnValue = false;
// Your custom code
}
}
but there were also some javascript-heavy websites on which this solution did not work. For those, I found another solution involving injecting javascript into the document which will prevent the middle-click:
HtmlElement head = browser.Document.GetElementsByTagName("head")[0];
HtmlElement mscript = browser.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)mscript.DomElement;
element.text = "function handleMouseEvent(e) { "
+ "var evt = (e==null ? event:e); "
+ "if ( e.which == 2 ) e.preventDefault(); "
+ "return true; } "
+ "document.onmousedown = handleMouseEvent; "
+ "document.onmouseup = handleMouseEvent; "
+ "document.onclick = handleMouseEvent; ";
head.AppendChild(mscript);
UPDATE
The JavaScript injection methodology can be improved by following the suggested way to do it using managed code only:
stackoverflow.com/a/6222430/1248295
This is an alternative example implementation of the javascript injection, wrote in VB.NET:
Private ReadOnly handleMouseEventJs As String =
"
function HandleMouseEvent(e) {
var evt = (e==null ? event:e);
if (e.which == 2) e.preventDefault();
return true;
}
document.onmousedown = HandleMouseEvent;
// These events below seems are not necessary to handle for this purpose.
// document.onmouseup = HandleMouseEvent;
// document.onclick = HandleMouseEvent;
"
Private Sub WebBrowser1_Navigated(sender As Object, e As WebBrowserNavigatedEventArgs) _
Handles WebBrowser1.Navigated
Dim wb As WebBrowser = DirectCast(sender, WebBrowser)
Dim doc As HtmlDocument = wb.Document
Dim head As HtmlElement = doc.GetElementsByTagName("head")(0)
Dim js As HtmlElement = doc.CreateElement("script")
js.SetAttribute("text", handleMouseEventJs)
head.AppendChild(js)
' This method call seems not necessary at all, it works fine without invocking it.
' doc.InvokeScript("HandleMouseEvent", Nothing)
End Sub
UPDATE 2
Inject this code instead:
document.body.onmousedown = function(e) { if (e.button === 1) return false; }
https://stackoverflow.com/a/30423534/1248295
The move icon displayed upon middle mouse click is under control of your mouse settings. But you can detect middle mouse click on your WebBrowser control.
Register DocumentCompleted event for your WebBrowser control and use the following code:
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.Document.MouseDown += Document_MouseDown;
}
void Document_MouseDown(object sender, HtmlElementEventArgs e)
{
if (e.MouseButtonsPressed == System.Windows.Forms.MouseButtons.Middle)
{
// code to add tab or do sth else
}
}

C# ASP.NET Open a new windows and redirecting in button click event

How can i redirect to another page and open a new window in one button click?
protected void ASPxButton_save_Click(object sender, EventArgs e)
{
try
{
//do other stuff
if (oSoins.DEVENIR_ECVAC_PAR != 0)
{
string AdrUrl = "Print_DosSoin.aspx?SoinId=" + Soin_Id;
ClientScript.RegisterStartupScript(this.GetType(), "newWindow", String.Format("<script>window.open('{0}');</script>", AdrUrl));
}
Response.Redirect("DossierSoin_Liste.aspx");
}
catch (ThreadAbortException) {/* do nothing, it might be a response.Redirect exception */}
catch (Exception excThrown)
{
lbl_err.Text = excThrown.Message;
if (excThrown.InnerException != null) lbl_err.Text += "-->" + excThrown.InnerException.Message;
string TempMsg = "DosSoin Fiche " + Appel_ID + "-- ASPxButton_save_Click -->" + lbl_err.Text;
Outils.SendingEmail(TempMsg);
}
With the script above it's redirecting but does not open a new window.
Thank you in advance.
You should modify your javascript to the following:
string script = default(string)
if (oSoins.DEVENIR_ECVAC_PAR != 0)
{
string AdrUrl = "Print_DosSoin.aspx?SoinId=" + Soin_Id;
script = string.Format("window.open('{0}'); ", AdrUrl);
}
script += " window.location.href = 'DossierSoin_Liste.aspx';";
ClientScript.RegisterStartupScript(this.GetType(), "newWindow", script, true);
This will create a new window then redirect on the client.

button1.Attributes.Add("onclick", "javascript:window.open('page1.aspx?CheckedItem=" + checkedItem.ToString() + "'');"); is not working properly

my client side code button1.Attributes.Add("onclick", "javascript:window.open('page1.aspx?CheckedItem=" + checkedItem.ToString() + "','mywindow',');"); is not executing on the first click.But it is working fine from second click onwards.I wrote this code inside the button click event.
I had tried to put this inside the page_load ,but the problem is i need to return a value from this page.
here is the code
protected void btnPreview_Click(object sender, EventArgs e)
{
//StringBuilder checkedItem = new StringBuilder();
checkedItem.Length = 0;
foreach (ListItem i in chkValidation.Items)
{
if (i.Selected)
{
if (string.IsNullOrEmpty(Convert.ToString(checkedItem)))
{
checkedItem.AppendFormat(i.Text);
}
else
{
checkedItem.AppendFormat(",");
checkedItem.AppendFormat(i.Text);
}
}
btn_Preview.Attributes.Add("onclick",
"javascript:window.open('TimePhaseAttributePreview.aspx?CheckedItem=" +
checkedItem.ToString() + "','mywindow','menubar=0,resizable=0,width=350,height=250');");
}
Please help me
put the code in any page event. like page_load,init.. or use RegisterClientScriptBlock
You need to use OnClientClick, not OnCLick
Change your code to
button1.OnClientClick = "javascript:window.open('page1.aspx?CheckedItem=" + checkedItem.ToString() + "'
,'mywindow',')";

Categories