Alert(“Message”) box in Asp.Net Codebehind and Call java fuction from codebehind

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. You can call Alert.Show(“Message”) from Asp.Net Codebehind.

On button click, alert box display values in textbox1.
Here is code:

protected void Button1_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + TextBox1.Text.Replace("'","\\'")  + "');</script>");
}

Another way, You can just call javascript from codebehind.

<head runat="server">
    <title>Ashish's Blog</title>
    <script type="text/javascript">
    function callAlert(msg)
    {
        alert(msg);
    }
    </script>
 </head>

Codebehind code:

protected void Button1_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "Message", "callAlert('" + TextBox1.Text.Replace("'","\\'")  + "');",true);
}

If your content page is wrapped in an ASP.NET AJAX UpdatePanel, then you cannot use the ClientScript.RegisterStartupScript to call a JavaScript function during a partial-page postback. Instead, use the ScriptManager.RegisterStartupScript() method.

    protected void Button1_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + TextBox1.Text.Replace("'","\\'")  + "');</script>", false);
     }

Thanks.

IF THEN in SQL SELECT Statement

I recently came across the CASE WHEN statement work Similar to IF statement into SQL SELECT , Maybe you’ll find it useful.

Create table called Student using SQL Query:

CREATE TABLE [dbo].[Student](
	[StudentID] [int] NULL,
	[Marks] [float] NULL
)

Insert some data into student:

INSERT INTO [Student] ([StudentID],[Marks]) VALUES (1,30)
INSERT INTO [Student] ([StudentID],[Marks]) VALUES (1,65)
INSERT INTO [Student] ([StudentID],[Marks]) VALUES (1,90)
INSERT INTO [Student] ([StudentID],[Marks]) VALUES (1,55)
INSERT INTO [Student] ([StudentID],[Marks]) VALUES (1,70)

We can use CASE WHEN statement instead of IF. Here is Query:

SELECT [StudentID]
      ,[Marks]
      ,case When [Marks] <65 and &#91;Marks&#93; >49
            then 'Pass' 
            When [Marks] <75 and &#91;Marks&#93; >64
            then 'Credit' 
            When [Marks] <85 and &#91;Marks&#93; >74
            then 'Distinction' 
            When [Marks] <101 and &#91;Marks&#93; >84
            then 'High Distinction' 
            else 'Fail' 
                  end As Result    
  FROM [Student]

Thanks

Display Notification Messages using jQuery

In this article, I am going to show you how to display notification messages in Webpage. Toastmessage-plugin is a JQuery plugin which provides android-like notification messages. The toasted messages arriving on the screen in a seamless and natural way. It’s a quite nice way to report info or error or warning to the user.

Demo

Demo


The plugin is entirely customizable. So you can change the positioning, the required user action, the style and so on.

Installation
The plugin is download from here .

jquery.toastmessage.js        -- the plugin
css/jquery.toastmessage.css   -- the css file
images/error.png              -- image
images/close.gif              -- image
images/notice.png             -- image
images/success.png            -- image
images/warning.png            -- image

Types of messages
4 different types message you can use. Each type comes with its own icon and colored border. The types are:

  • notice
  • success
  • warning
  • error

Easy to use
The following methods will display a toast message:

$().toastmessage('showNoticeToast', 'some message here');
$().toastmessage('showSuccessToast', 'some message here');
$().toastmessage('showWarningToast', 'some message here');
$().toastmessage('showErrorToast', 'some message here');

You can alter the configuration to your special use case.

// user configuration of all toastmessages to come:
$().toastmessage({
    text     : 'Ashish Blog',     // content of the item
    sticky   : true,               // should the toast item sticky or not?
    position : 'top-right',       // top-left, top-center, top-right, middle-left, middle-center, middle-right
                                      // Position of the toast container holding different toast.
                                      // Position can be set only once at the very first call,
                                     // changing the position after the first call does nothing
    type     : 'success',        // notice, warning, error, success
    close    : function () {console.log('toast is closed ...');}
});

Here is example of all type of message code:

<!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>Ashish's Blog</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script src="jquery.toastmessage.js" type="text/javascript"></script>
    <link href="jquery.toastmessage.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript">

        function showSuccessToast() {
            $().toastmessage('showSuccessToast', "Success Dialog which is fading away ...");
        }
        function showStickySuccessToast() {
            $().toastmessage('showToast', {
                text: 'Success Dialog which is sticky',
                sticky: true,
                position: 'top-right',
                type: 'success',
                closeText: '',
                close: function () {
                    console.log("toast is closed ...");
                }
            });

        }
        function showNoticeToast() {
            $().toastmessage('showNoticeToast', "Notice  Dialog which is fading away ...");
        }
        function showStickyNoticeToast() {
            $().toastmessage('showToast', {
                text: 'Notice Dialog which is sticky',
                sticky: true,
                position: 'top-left',
                type: 'notice',
                closeText: '',
                close: function () { console.log("toast is closed ..."); }
            });
        }
        function showWarningToast() {
            $().toastmessage('showWarningToast', "Warning Dialog which is fading away ...");
        }
        function showStickyWarningToast() {
            $().toastmessage('showToast', {
                text: 'Warning Dialog which is sticky',
                sticky: true,
                position: 'middle-right',
                type: 'warning',
                closeText: '',
                close: function () {
                    console.log("toast is closed ...");
                }
            });
        }
        function showErrorToast() {
            $().toastmessage('showErrorToast', "Error Dialog which is fading away ...");
        }
        function showStickyErrorToast() {
            $().toastmessage('showToast', {
                text: 'Error Dialog which is sticky',
                sticky: true,
                position: 'center',
                type: 'error',
                closeText: '',
                close: function () {
                    console.log("toast is closed ...");
                }
            });
        }
 
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
 
    <p>
            <span class="description">Show a success toast</span> <a href="javascript:showSuccessToast();">not
            sticky</a>|<a href="javascript:showStickySuccessToast();">sticky</a>
        </p>
 
        <p>
            <span class="description">Show a notice toast</span> <a href="javascript:showNoticeToast();">not sticky</a>|<a
                href="javascript:showStickyNoticeToast();">sticky</a>
        </p>
 
        <p>
            <span class="description">Show a warning toast</span> <a href="javascript:showWarningToast();">not
            sticky</a>|<a href="javascript:showStickyWarningToast();">sticky</a>
        </p>
 
        <p>
            <span class="description">Show a error toast</span> <a href="javascript:showErrorToast();">not sticky</a>|<a
                href="javascript:showStickyErrorToast();">sticky</a>
        </p>
 
    </div>
    </form>
</body>
</html>

Thanks.

Nested GridView in Show/Hide effect using C#.Net

This article explains how to make an ASP.NET nested GridView. There may be many ways to do this, but here is my code.



First, put gridview1 into asp design page then put another gridview2 inside previous gridview.
Here is code file

<form id="form1" runat="server">
<asp:GridView ID="GridView1"
runat="server"
DataKeyNames="CustomerID" AutoGenerateColumns="false"
OnRowDataBound="gv_RowDataBound" Width="80%"
AllowPaging="True" PageSize="20" >
<HeaderStyle CssClass="dataTable" />
<RowStyle CssClass="dataTable" />
<AlternatingRowStyle CssClass="dataTableAlt" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<a href="javascript:switchViews('div<%# Eval("CustomerID") %>', 'one');">
<img id="imgdiv<%# Eval("CustomerID") %>" alt="Click to show/hide orders" border="0" src="Images/expand_button.png" />
</a>
</ItemTemplate>
<AlternatingItemTemplate>
<a href="javascript:switchViews('div<%# Eval("CustomerID") %>', 'alt');">
<img id="imgdiv<%# Eval("CustomerID") %>" alt="Click to show/hide orders" border="0" src="Images/expand_button.png" />
</a>
</AlternatingItemTemplate>
</asp:TemplateField>

<asp:BoundField DataField="CustomerID" HeaderText="CustomerID" HtmlEncode="False" />
<asp:BoundField DataField="Name" HeaderText="Name" HtmlEncode="False" />
<asp:BoundField DataField="Address" HeaderText="Address" HtmlEncode="False" />
<asp:TemplateField>
<ItemTemplate>
</td></tr>
<tr>
<td colspan="100%" >
<div id="div<%# Eval("CustomerID") %>" style="display:none;position:relative;left:25px;" >
<asp:GridView ID="GridView2" runat="server" Width="80%"
AutoGenerateColumns="false" DataKeyNames="ItemCode"
EmptyDataText="No orders for this customer." >
<HeaderStyle CssClass="dataTable" />
<AlternatingRowStyle CssClass="dataTableAlt" />
<RowStyle CssClass="dataTable" />
<Columns>
<asp:BoundField DataField="OrderDate" HeaderText="Order Date" HtmlEncode="False" />
<asp:BoundField DataField="ShippedDate" HeaderText="ShippedDate" HtmlEncode="False" />
<asp:BoundField DataField="ShipTO" HeaderText="Ship TO" />

</Columns>
</asp:GridView>
</div>
</td>
</tr>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>

In above code, To get nested gridview effect I simply injected some HTML to end the current row and create a new row. The nested GridView is then placed inside a < DIV> tag where the display of that < DIV> is controled by Javascript. Each < DIV> is assigned a unique ID that corresponds to the main GridView’s rowID and that is passed to the javascript to control the opening and closing of the nested GridView.

Second, In Codebehind file I put datasource of gridview. In order to bind the child GridView2, we can’t use the static DataSource control. We will have to dynamically prepare the query based on the customer ID of the corresponding parent row, and that we can do it in the RowDataBound event of the parent grid as below:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlDataSource dbSrc= new SqlDataSource();
dbSrc.ConnectionString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString2"].ConnectionString;
dbSrc.SelectCommand = "SELECT CustomerID, Name, Address FROM Customer";
GridView1.DataSource = dbSrc;
GridView1.DataBind();
}
}
//The code to populate the nested GridView that is called on the main GridView's OnRowDataBound event
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{

GridView gv = (GridView)e.Row.FindControl("GridView2");
SqlDataSource dbSrc = new SqlDataSource();
dbSrc.ConnectionString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString2"].ConnectionString;
dbSrc.SelectCommand = "SELECT OrderDate,ShippedDate, ShipTO FROM Orders where customerID='" + ((DataRowView)e.Row.DataItem)["CustomerID"].ToString() + "'";
gv.DataSource = dbSrc;
gv.DataBind();
}
}

Finally, put JavaScript to show/hide Child gridview ..

<script type="text/javascript">
function switchViews(obj, row) {
var div = document.getElementById(obj);
var img = document.getElementById('img' + obj);

if (div.style.display == "none") {
div.style.display = "inline";
img.src = "images/expand_button_down.png";
} else {
div.style.display = "none";
img.src = "images/expand_button.png";
}
}
</script>

Here is css file for design purpose.

<style type="text/css">
.dataTable
{
text-align:left;
font-size:10pt;
font-family:Verdana, Sans-Serif;
border:solid 1px rgb(210,210,210);
color:gray;

}
.dataTable CAPTION
{
color:Black;
text-align:left;
font-size:12pt;
font-weight:bold;
padding-bottom:5px;
padding-top:15px;
}
.dataTable TH
{
text-decoration:none;
background-color:rgb(210,210,210);
font-family:Tahoma, Sans-Serif, Arial;
font-size:11pt;
font-weight:normal;
color:Black;
border:solid 0px;
padding:2px 4px 2px 2px;
}
.dataTable TD
{
padding-left:6px;
border:solid 0px;
min-width:100px;
}
.dataTable TR
{
border:solid 0px;

}
.dataTableAlt TD
{
font-size: 10pt;
color:rgb(75,75,75);
font-family:Verdana;
border: solid 0px;
padding:2px 0px 2px 8px;
background-color:rgb(245,245,245);
min-width:100px;
}
.dataTableRow
{
color:rgb(75,75,75);
font-family:Verdana;
padding:2px 0px 2px 8px;
border:solid 0px;
background-color:White;
}
.dataTable A:Link, .dataTable A:Visited
{
text-decoration:none;
color:black;
}
.dataTable A:Hover
{
color:Red;
text-decoration:none;
}
</style>

Thanks.