Web Technologies

BLOG for Web Technologies

Freewares, Free E-Books Download, SEO, Tips, Tricks, Tweaks, Latest News, .Net, PHP, ASP, ASP.Net, CSP, MS SQL Server, MySQL, Database
earnptr.com
Friday, December 12, 2008
ASp.Net 2.0 GridView Delete Button Confirmation pop-up

While using GridView in asp.net pages wants to confirm the deletion form user. To do this we can take him to another page having GUI to confirm and then delete the record on that page.

Instead of doing so much hardwork you can achieve this on the same page with a little bit of extra code.

Workaround

Add a client alert script to the delete button of every row.
In the delete event of GridView delete the record.

Code

==================================================
Page’s Aspx Design File Begins
==================================================
<asp:GridView ID=”gvFaq” runat=”server” AutoGenerateColumns=”False” CellPadding=”4″
ForeColor=”#333333″ GridLines=”None” OnRowDataBound=”gvFaq_RowDataBound” OnRowDeleting=”gvFaq_RowDeleting”>
<footerstyle backcolor=”#5D7B9D” bold=”True” forecolor=”White”>
<rowstyle backcolor=”#F7F6F3″ forecolor=”#333333″>
<columns>
<asp:boundfield datafield=”slno” headertext=”Sl">
<asp:boundfield datafield=”cHeading” headertext=”Question”>
<asp:boundfield datafield=”cPosition” headertext=”Position”>
<asp:commandfield headertext=”Manage” showselectbutton=”True”>
<asp:commandfield headertext=”Delete” showdeletebutton=”True”>
</columns>
<pagerstyle backcolor=”#284775″ forecolor=”White” horizontalalign=”Center”>
<selectedrowstyle backcolor=”#E2DED6″ bold=”True” forecolor=”#333333″>
<headerstyle backcolor=”#5D7B9D” bold=”True” forecolor=”White”>
<editrowstyle backcolor=”#999999″>
<alternatingrowstyle backcolor=”White” forecolor=”#284775″>
</asp:GridView>
==================================================
Page’s Aspx Design File Ends
==================================================

==================================================
Code Behind File Begins
==================================================
1) Import Namespaces
using System.Data.SqlClient;

2) Declare global variables which will be used in page
DataSet ds = new DataSet();
SqlDataAdapter da;
SqlConnection myConnection;
String connStr = “your database connection string goes here”‘;
String sql = string.Empty;

3) Page Load event
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
fillGridView();
}
}

4) GridView filling method
private void fillGridView()
{

try
{
myConnection = new SqlConnection(connStr);
sql = “select * from tblFaq order by slno desc”;

da = new SqlDataAdapter(sql, myConnection);
ds.Clear();
da.Fill(ds, “tblFaq”);

gvFaq.DataSource = ds.Tables[0];
Page.DataBind();

}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}

5) In the RowDataBound event add a java script event to the delete cell.
protected void gvFaq_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[4].Attributes.Add(”onClick”, “return confirm(’Are you sure you want to delete the record?’);”);
}
}

6) Handle the RowDeleting event to delete the record of current row.

protected void gvFaq_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
myConnection = new SqlConnection(connStr);
myConnection.Open();
sql = “delete from tblFaq where slno = ” + Convert.ToInt32(gvFaq.Rows[e.RowIndex].Cells[0].Text);
SqlCommand oldcom = new SqlCommand(sql, myConnection);
oldcom.ExecuteNonQuery();
myConnection.Close();
fillGridView();
Response.Write(”Record Deleted”);
}
catch (Exception ex)
{
lblError.Text = ex.Message;
}
}

==================================================
Code Behind File Ends
==================================================

Labels: , ,

posted by WebTeks @ 6:06 PM   0 comments
Thursday, September 18, 2008
JavaScript - Cross Browser Modal Dialog Box
The following JavaScript code snippet demonstrates how to create a wide variety of modal dialog boxes. The first block of JavaScript code can be put into a generic .js script file. The second JavaScript block contains a couple of wrapper samples for creating a yes, no, cancel option as well as a yes, no, maybe option to demonstrate that you can create an unlimited number of customized dialogs. You'll probably want to create a few standard options and put them in your own generic .js script file. It is pretty easy to force the window to be modal. We'll attack the issue in both the window.opener and the modal dialog window itself. In the window.opener, we'll use the window.setInterval() method to repeatedly check to see if our globally defined winmodal window is open. If so, we'll set its focus by using window.focus(). To avoid any extra window minimization of the modal dialog window, we'll call window.focus() in the dialog window body tag's onblur() event. When we launch the modal dialog window, we'll also include the name of the method we want called when an option is selected by the user and the window is closed. Notice how I opted to use eval() to dynamically fire the passed in JavaScript method when the window is closed to handle the business logic when the user selects a response. Unlike typical modal dialogs in windows, you have to separate out the code the launches the window and the code that reacts to the response into two separate JavaScript functions.I believe you'll find this to be an effective way to create modal dialog windows. In fact, it even handles the user clicking on non IE windows and then attempting to return to the window.opener or if the user tries to close the browser window by right clicking on it while in a minimized state. I hope you found this little snippet helpful.

Modal Dialog Box Sample Code

<html>
<script language="JavaScript">

var ModalDialogWindow;
var ModalDialogInterval;
var ModalDialog = new Object;

ModalDialog.value = '';
ModalDialog.eventhandler = '';


function ModalDialogMaintainFocus()
{
try
{
if (ModalDialogWindow.closed)
{
window.clearInterval(ModalDialogInterval);
eval(ModalDialog.eventhandler);
return;
}
ModalDialogWindow.focus();
}
catch (everything) { }
}

function ModalDialogRemoveWatch()
{
ModalDialog.value = '';
ModalDialog.eventhandler = '';
}

function ModalDialogShow(Title,BodyText,Buttons,EventHandler)
{

ModalDialogRemoveWatch();
ModalDialog.eventhandler = EventHandler;

var args='width=350,height=125,left=325,top=300,toolbar=0,';
args+='location=0,status=0,menubar=0,scrollbars=1,resizable=0';

ModalDialogWindow=window.open("","",args);
ModalDialogWindow.document.open();
ModalDialogWindow.document.write('<html>');
ModalDialogWindow.document.write('<head>');
ModalDialogWindow.document.write('<title>' + Title + '</title>');
ModalDialogWindow.document.write('<script' language="JavaScript">');
ModalDialogWindow.document.write('function CloseForm(Response) ');
ModalDialogWindow.document.write('{ ');
ModalDialogWindow.document.write(' window.opener.ModalDialog.value = Response; ');
ModalDialogWindow.document.write(' window.close(); ');
ModalDialogWindow.document.write('} ');
ModalDialogWindow.document.write('</script' + '>');
ModalDialogWindow.document.write('</head>');
ModalDialogWindow.document.write('<body onblur="window.focus();">');
ModalDialogWindow.document.write('<table border="0" width="95%" align="center" cellspacing="0" cellpadding="2">');
ModalDialogWindow.document.write('<tr><td align="left">' + BodyText + '</td></tr>');
ModalDialogWindow.document.write('<tr><td align="left"><br /></td></tr>');
ModalDialogWindow.document.write('<tr><td align="center">' + Buttons + '</td></tr>');
ModalDialogWindow.document.write('</body>');
ModalDialogWindow.document.write('</html>');
ModalDialogWindow.document.close();
ModalDialogWindow.focus();
ModalDialogInterval = window.setInterval("ModalDialogMaintainFocus()",5);

}

</script>

<script language="JavaScript">


function YesNoCancel(BodyText,EventHandler)
{
var Buttons='';
Buttons = '<a href="javascript:CloseForm(">Yes</a> ';
Buttons += '<a href="javascript:CloseForm(">No</a> ';
Buttons += '<a href="javascript:CloseForm(">Cancel</a> ';
ModalDialogShow("Dialog",BodyText,Buttons,EventHandler);
}

function YesNoMaybe(BodyText,EventHandler)
{
var Buttons='';
Buttons = '<a href="javascript:CloseForm(">Yes</a> ';
Buttons += '<a href="javascript:CloseForm(">No</a> ';
Buttons += '<a href="javascript:CloseForm(">Maybe</a> ';
ModalDialogShow("Dialog",BodyText,Buttons,EventHandler);
}

function YesNoCancelReturnMethod()
{
document.getElementById('modalreturn1').value = ModalDialog.value;
ModalDialogRemoveWatch();
}

function YesNoMaybeReturnMethod()
{
document.getElementById('modalreturn2').value = ModalDialog.value;
ModalDialogRemoveWatch();
}

</script>

<body>

<table border="1" cellpadding="2" cellspacing="2" align="center" width="60%">
<tr><td align="left"></td></tr>
<tr><td align="left"></td></tr>
<tr><td align="left"></td></tr>
<tr>
<td align="left"><a href="javascript:YesNoCancel('Yes, no, or cancel me',
'YesNoCancelReturnMethod()');">Show Modal #1</a>
1. <input type="text" id="modalreturn1" name="modalreturn1" value="''"></td>
</tr>
<tr>
<td align="left"><a href="javascript:YesNoMaybe('Yes, no, or maybe me',
'YesNoMaybeReturnMethod()');">Show Modal #2</a>
2. <input type="text" id="modalreturn2" name="modalreturn2" value="''"></td>
</tr>

</table>

</body>
</html>


Labels: ,

posted by WebTeks @ 5:53 AM   0 comments
Saturday, August 23, 2008
JavaScript: Alert.Show(message) from ASP.NET Code-behind

In highly interactive websites and intranet sites, you probably want to let the users know what's going on when they delete, save, export etc. on the site.

Those kinds of status messages are widely used and are often implemented by a JavaScript alert box on the web page. ASP.NET doesn't natively support JavaScript functions from the code-behind files. You manually have to print out a script tag and add the alert() call to it.

As easy as it may be, the extensive use of the alert() status message though out a website calls for a unified and simple implementation in order to avoid duplicate code - a centralized method.

In Windows Forms it is very easy to pop up a status message by calling MessageBox.Show("message"). It is that kind of object model we want in ASP.NET for printing out JavaScript alerts. We want Alert.Show("message") in ASP.NET.

Such a thing doesn't exist so we have to create it our selves.

I've written a static class called Alert with one public method called Show. The implementation is as simple as can be. Just put the .cs file in the App_Code folder on your website and you instantly have access to the method from all pages and user controls.

using System.Web;
using System.Text;
using System.Web.UI;

///


/// A JavaScript alert
///

public static class Alert
{

///


/// Shows a client-side JavaScript alert in the browser.
///

/// The message to appear in the alert.
public static void Show(string message)
{
// Cleans the message to allow single quotation marks
string cleanMessage = message.Replace("'", "\\'");
string script = "";

// Gets the executing web page
Page page = HttpContext.Current.CurrentHandler as Page;

// Checks if the handler is a Page and that the script isn't allready on the Page
if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
{
page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
}
}
}

Demonstration

That class of only 30 lines of code enables us to add a JavaScript alert to any page at any time. Here is an example of a Button.Click event handler that uses the method for displaying status messages.

void btnSave_Click(object sender, EventArgs e)
{
try
{
SaveSomething();
Alert.Show("You document has been saved");
}
catch (ReadOnlyException)
{
Alert.Show("You do not have write permission to this file");
}
}

Labels: ,

posted by WebTeks @ 2:29 AM   1 comments
Previous Post
Archives
Links
Template by

Free Blogger Templates

BLOGGER

Subscribe in NewsGator Online Subscribe in Rojo Add to Google Add to netvibes Subscribe in Bloglines Web Developement Blogs - BlogCatalog Blog Directory Blogarama - The Blog Directory Blog Directory & Search engine Computers Blogs - Blog Top Sites Top Computers blogs