Yasserzaid’s Weblog

March 31, 2009

Show and Hide DIV with Button Click using Javascript

Filed under: Javascript — yasserzaid @ 8:05 pm

Hi

try this example :-

<script language=”javascript” type=”text/javascript”>
       function toggleDiv() 
       { 
         if (document.getElementById(“myDivBox”).style.display == “block”) 
         { 
           document.getElementById(“myDivBox”).style.display = “none”; 
         } 
         else 
         { 
           document.getElementById(“myDivBox”).style.display = “block”; 
         } 
       } 
     </script>

<asp:Button ID=”button1″ runat=”server” OnClick=”toggleDiv()” />
    <div>

        <div id=”myDivBox” style=”display:none; width :300px”>
          Get a head start on making money from surveys! We worked out special deals with
        </div>
    </div>

and in code behind :-

protected void Page_Load(object sender, EventArgs e)
    {
        button1.Attributes.Add(“onclick”, “javascript:toggleDiv(); return false;”);
    }

//– There is another way to Hide Button after Show DIV

<script language=”javascript” type=”text/javascript”>
       function toggleDiv() 
       { 
         if (document.getElementById(“myDivBox”).style.visibility == “hidden”) 
         { 
           document.getElementById(“myDivBox”).style.visibility = “visible”;
           document.getElementById(“Button1″).style.visibility=”hidden”; 
         } 
         else 
         { 
           document.getElementById(“myDivBox”).style.visibility = “hidden”;
           document.getElementById(“Button1).style.visibility=”visible”;
         } 
       } 
     </script>
<asp:Button ID=”button1″ runat=”server” OnClientClick=”toggleDiv(); return false;”  />
    <div>
   
        <div id=”myDivBox” style=” width :300px; visibility:hidden”>
          Get a head start on making money from surveys! We worked out special deals with
        </div>

Hope this helps

Good Luck

Delete Checked Checkbox in Datalist

Filed under: ASP.Net — yasserzaid @ 7:06 am

Hi

try this example :-

protected void Button1_Click(object sender, EventArgs e)
    {
        for(int i = 0;i <this.DataList1.Items.Count ;i++)
        {
            DataList inner = this.DataList1.Items[i].FindControl(“DataList2″) as DataList;
            for (int j = 0; j < inner.Items.Count; j++)
            {
                CheckBox chk = inner.Items[j].FindControl(“CheckBox1″) as CheckBox;
                if (chk.Checked)
                {
                    HiddenField hf = inner.FindControl(“HiddenField2″) as HiddenField;
                    string sql = “delete from City where cityid = ” + hf.Value;
                    //ado.net code here
                }
            }
        }
    } 

 <form id=”form1″ runat=”server”>
         <asp:SqlDataSource ID=”SqlDataSource1″ runat=”server” ConnectionString=”<%$ ConnectionStrings:ConnectionString2 %>”
            SelectCommand=”SELECT * FROM [country]“></asp:SqlDataSource>
        <asp:DataList ID=”DataList1″ runat=”server” DataKeyField=”countryid” DataSourceID=”SqlDataSource1″>
            <ItemTemplate>
                countryname:
                <asp:Label ID=”countrynameLabel” runat=”server” Text=’<%# Eval(“countryname”) %>’></asp:Label><br />
                <asp:HiddenField ID=”HiddenField1″ runat=”server” Value=’<%# Eval(“countryid”) %>’ />
                <br />
                <asp:DataList ID=”DataList2″ runat=”server” DataKeyField=”cityid” DataSourceID=”SqlDataSource2″>
                    <ItemTemplate>
                        cityname:
                        <asp:Label ID=”citynameLabel” runat=”server” Text=’<%# Eval(“cityname”) %>’></asp:Label>
                        <asp:CheckBox ID=”CheckBox1″ runat=”server” Text=”delete” />
                        <asp:HiddenField ID=”HiddenField2″ runat=”server” Value=’<%# Eval(“cityid”) %>’ />
                    </ItemTemplate>
                </asp:DataList><br />
                <asp:SqlDataSource ID=”SqlDataSource2″ runat=”server” ConnectionString=”<%$ ConnectionStrings:ConnectionString2 %>”
                    SelectCommand=”SELECT * FROM [city] WHERE ([countryid] = @countryid)”>
                    <SelectParameters>
                        <asp:ControlParameter ControlID=”HiddenField1″ Name=”countryid” PropertyName=”Value”
                            Type=”Int64″ />
                    </SelectParameters>
                </asp:SqlDataSource>
            </ItemTemplate>
        </asp:DataList>
        <asp:Button ID=”Button1″ runat=”server” OnClick=”Button1_Click” Text=”delete” />

    </form>

Hope this helps

Good Luck

March 27, 2009

AJAX Modal Popup Extender to Delete With Confirmation From Gridview

Filed under: AJAX — Tags: — yasserzaid @ 6:17 pm

Hi

try this example to use AJAX Modal Popup Extender to Delete With Confirmation From Gridview

In this Example i will use Products Table from Northwind Database

.ASPX

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default3.aspx.cs” Inherits=”Default3″ %>

<%@ Register Assembly=”AjaxControlToolkit” Namespace=”AjaxControlToolkit” TagPrefix=”cc1″ %>

<!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 runat=”server”>
    <title>ModalPopup for Delete</title>
    <style type=”text/css”>
    .modalBackground {
            background-color:Gray;
            filter:alpha(opacity=70);
            opacity:0.7;
        }
        .confirm{
           background-color:White;
           padding:10px;
           width:370px;
        }
    </style>
   
    <script type=”text/javascript”>
        //  keeps track of the delete button for the row
        //  that is going to be removed
        var _source;
        // keep track of the popup div
        var _popup;
       
        function showConfirm(source){
            this._source = source;
            this._popup = $find(‘mdlPopup’);
           
            //  find the confirm ModalPopup and show it   
            this._popup.show();
        }
       
        function okClick(){
            //  find the confirm ModalPopup and hide it   
            this._popup.hide();
            //  use the cached button as the postback source
            __doPostBack(this._source.name, ”);
        }
       
        function cancelClick(){
            //  find the confirm ModalPopup and hide it
            this._popup.hide();
            //  clear the event source
            this._source = null;
            this._popup = null;
        }
    </script>
   
</head>
<body>
    <form id=”form1″ runat=”server”>
        <asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
        </asp:ScriptManager>
       
        <asp:UpdateProgress ID=”UpdateProgress1″ runat=”server” AssociatedUpdatePanelID=”UpdatePanel1″>
            <ProgressTemplate>
                <div id=”progressBackgroundFilter”>
                </div>
                <div id=”processMessage”>
                    Please Wait …..</div>
            </ProgressTemplate>
        </asp:UpdateProgress>
        <cc1:modalpopupextender id=”md1″ runat=”server” backgroundcssclass=”modalBackground”
            behaviorid=”mdlPopup” cancelcontrolid=”btnNo” okcontrolid=”btnOk” oncancelscript=”cancelClick();”
            onokscript=”okClick();” popupcontrolid=”div” targetcontrolid=”div”> </cc1:modalpopupextender>
        <div id=”div” runat=”server” align=”center” class=”confirm” style=”display: none”>
            Are you sure you want to delete ?
            <asp:Button ID=”btnOk” runat=”server” Text=”Yes” Width=”50px” />
            <asp:Button ID=”btnNo” runat=”server” Text=”No” Width=”50px” />
        </div>
        <asp:UpdatePanel ID=”UpdatePanel1″ runat=”server”>
            <ContentTemplate>
                &nbsp;<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False” CellPadding=”4″
                    DataKeyNames=”ProductID” DataSourceID=”SqlDataSource1″ ForeColor=”#333333″ AllowPaging=”True”>
                    <FooterStyle BackColor=”#507CD1″ Font-Bold=”True” ForeColor=”White” />
                    <Columns>
                        <asp:BoundField DataField=”ProductName” HeaderText=”ProductName” SortExpression=”ProductName” />
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:Button ID=”Button1″ runat=”server” CausesValidation=”False” CommandArgument=’<%# Eval(“ProductID”) %>’
                                    OnClick=”Button1_Click” OnClientClick=”showConfirm(this); return false;” Text=”Delete” />
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <RowStyle BackColor=”#EFF3FB” />
                    <EditRowStyle BackColor=”#2461BF” />
                    <SelectedRowStyle BackColor=”#D1DDF1″ Font-Bold=”True” ForeColor=”#333333″ />
                    <PagerStyle BackColor=”#2461BF” ForeColor=”White” HorizontalAlign=”Center” />
                    <HeaderStyle BackColor=”#507CD1″ Font-Bold=”True” ForeColor=”White” />
                    <AlternatingRowStyle BackColor=”White” />
                </asp:GridView>
                <asp: SqlDataSource ID=”SqlDataSource1″ runat=”server” ConnectionString=”<%$ ConnectionStrings: NorthwindConnectionString %>”
                    SelectCommand=”SELECT [ProductID], [ProductName] FROM [Products]“></asp: SqlDataSource>
            </ContentTemplate>

Hope this helps

Good Luck
        </asp: UpdatePanel>
    </form>
</body>
</html>

and In Code behind :-

protected void Button1_Click(object sender, EventArgs e)
    {
        //  get the gridviewrow from the sender so we can get the datakey we need
        Button btnDelete = sender as Button;
        //GridViewRow row = (GridViewRow)btnDelete.NamingContainer;
        int ProductID = int.Parse(btnDelete.CommandArgument);
        ///– you delete Method here
    }

and in web.config file :-

<connectionStrings>
  < add name=”NorthwindConnectionString” connectionString=”Data Source=.;Initial Catalog=Northwind;Integrated Security=True” providerName=”System.Data.SqlClient”/>
 </connectionStrings>

Good Luck

Close Popup window When Press Esc Key

Filed under: Javascript — yasserzaid @ 12:57 pm

Hi

try this In you Popup window

<script type=”text/javascript”>
function ESCclose(evt)
{
if (evt.keyCode == 27)
window.close();
}
</script>

Then add an onkeypress attribute in the body tag, like this:

<body onkeypress=”ESCclose(event)”>

Hope this helps

Good Luck

Style for Button Control

Filed under: CSS — yasserzaid @ 11:26 am

Hi

try this Example to make CSS for Button Control :-

.buttonBlue
{
 cursor: hand;
 background-color: #3C5F84;
 color: #F9A464;
 text-align: center;
 vertical-align: text-top;
 font-Weight: bold;
 font-size: 11pt;
 border: 0px Outset Transparent;
}

<asp:Button ID=”btnSubmit” ToolTip=”Submit Query” runat=”server” Text=”Submit” CssClass=”buttonBlue” Height=”100%” Width=”100%” onclick=”btnSubmit_Click” />

Good Luck

March 25, 2009

Display Confirmation Message on GridView Deleting

Filed under: ASP.Net — yasserzaid @ 6:30 pm

Hi

try this example to Display Confirmation Message on GridView Deleting

//— with Delete CommandField —–

<head runat=”server”>
    <title>GridView Data Manipulation</title>
    <script type=”text/javascript” language=”javascript”>
        function ConfirmOnDelete(item)
        {
          if (confirm(“Are you sure to delete: ” + item + “?”)==true)
            return true;
          else
            return false;
        }
    </script>
</head>
<Columns>
    <asp:BoundField DataField=”CustomerID” HeaderText=”ID” ReadOnly=”true” />
    <asp:BoundField DataField=”CompanyName” HeaderText=”Company”/>
    <asp:BoundField DataField=”ContactName” HeaderText=”Name”/>
    <asp:BoundField DataField=”ContactTitle” HeaderText=”Title” />
    <asp:BoundField DataField=”Address” HeaderText=”Address”/>
    <asp:BoundField DataField=”Country” HeaderText=”Country”/>
    <asp:CommandField ShowDeleteButton=”True” ShowEditButton=”True” />
</Columns>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowState != DataControlRowState.Edit) // check for RowState
   {
     if (e.Row.RowType == DataControlRowType.DataRow) //check for RowType
     {
       string id = e.Row.Cells[0].Text; // Get the id to be deleted
       LinkButton lb = (LinkButton)e.Row.Cells[6].Controls[2]; //cast the ShowDeleteButton link to linkbutton
       if (lb != null)
       {
          lb.Attributes.Add(“onclick”, “return ConfirmOnDelete(‘” + id + “‘);”); //attach the JavaScript function with the ID as the paramter
       }      
      }
  }
}
//—— With LinkButton  Control ———-

<Columns>
 <asp:BoundField DataField=”CustomerID” HeaderText=”ID” ReadOnly=”true” />
 <asp:BoundField DataField=”CompanyName” HeaderText=”Company”/>
 <asp:BoundField DataField=”ContactName” HeaderText=”Name”/>
 <asp:BoundField DataField=”ContactTitle” HeaderText=”Title” />
 <asp:BoundField DataField=”Address” HeaderText=”Address”/>
 <asp:BoundField DataField=”Country” HeaderText=”Country”/>
 <asp:TemplateField>
      <ItemTemplate>
      <asp:LinkButton ID=”LinkDelete” runat=”server”>Delete</asp:LinkButton>
      </ItemTemplate>
 </asp:TemplateField>
</Columns>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
 if (e.Row.RowState != DataControlRowState.Edit) // check for RowState
 {
    if (e.Row.RowType == DataControlRowType.DataRow) //check for RowType
    {
      string id = e.Row.Cells[0].Text; // Get the id to be deleted
      LinkButton lb = (LinkButton)e.Row.Cells[6].FindControl(“LinkDelete”); //access the LinkButton from the TemplateField using FindControl method
      if (lb != null)
      {
        lb.Attributes.Add(“onclick”, “return ConfirmOnDelete(‘” + id + “‘);”); //attach the JavaScript function
      }
     }
 }
}

Hope this helps

Good Luck

Bind Enum to DropdownList Control

Filed under: ASP.Net — Tags: — yasserzaid @ 6:14 pm

Hi

try this example :-

Step1 :- create new website and add web page and add DropdownList control in this page

Step2 :- in code behind :

public enum Days

monday=1, 
tuesday, 
wednesday, 
thursday, 
friday, 
saturday, 
sunday
}

protected void Page_Load(object sender, EventArgs e)   
{       
Hashtable ht = BindEnum(typeof(Days));       
ddlDays.DataSource = ht;       
ddlDays.DataTextField = “value”;       
ddlDays.DataValueField = “key”;       
ddlDays.DataBind();          
}   

public Hashtable BindEnum(Type enumeration)   
{       
string[] names = Enum.GetNames(enumeration);       
Array values = Enum.GetValues(enumeration);       
Hashtable ht = new Hashtable();       
for (int i = 0; i < names.Length; i++)       
{           
ht.Add(Convert.ToInt32(values.GetValue(i)).ToString(), names[i]);       
}       
return ht;   
}

Hope this helps

March 24, 2009

Disable Browser Back Button

Filed under: ASP.Net — yasserzaid @ 8:09 pm

The browser back button cannot be disabled as the browser security will not allow this. If you want user to stay on the same page, even if user presses back button, try this java script..

<script language=”JavaScript”>
javascript:window.history.forward(1);
</script>

What if the JavaScript is disabled by the client, then this code doesn’t work. And also it works great in IE, but not in other browsers. So I do not highly recommend using this.

Here is another solution for back button problem..

Add this code to Page_load

Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now); 

The above code will disable page cache, so if user hits back button page will postback to server.

Validate at least one of two TextBox

Filed under: ASP.Net — Tags: — yasserzaid @ 8:08 pm

Hi

try these examples :

<script type=”text/javascript” language=”javascript”>
   
     function checkInput()
     {
       var tb1 = document.getElementById(‘<%= TextBox1.ClientID %>’);
       var tb2 = document.getElementById(‘<%= TextBox2.ClientID %>’);
            if( tb1.value == “” && tb2.value == “”)
            {
               alert(‘TextBox cannot be emplty!’);
               return false;

            }
            else
            {return true;}
     }
    </script>

<asp:Button ID=”Button1″ runat=”server” Text=”Button” OnClientClick=”return checkInput();” />

//——or

<script type=”text/javascript”>
        function validateControls(txt1, txt2)
        {
            if (document.getElementById(txt1).value == ” && document.getElementById(txt2).value == ”)
            {
                alert(‘Atleaset one value required.’);
                return false;
            }
            else
                return true;
        }
    </script>

and the button that submits the page or on which you want to validate the textboxes you can add an attribute like this

this.Button1.Attributes.Add(“onclick”, “javascript: return validateControls(‘” + TextBox1.ClientID + “‘, ‘” + TextBox2.ClientID + “‘)”);

//– or using CustomValidator Control

<script type=”text/javascript” language=”javascript”>
     function checkInput(source, args)
     {
       var tb1 = document.getElementById(‘<%= TextBox1.ClientID %>’);
       var tb2 = document.getElementById(‘<%= TextBox2.ClientID %>’);
            if( tb1.value ==”" && tb2.value == “”)
            {
               args.IsValid =false;
            }
            else
            {
                args.IsValid =true;
            }
     }
    </script>
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
        <asp:TextBox ID=”TextBox2″ runat=”server”></asp:TextBox>
        <asp:CustomValidator ID=”CustomValidator1″ runat=”server” ErrorMessage=”Enter at least one” ClientValidationFunction=”checkInput”></asp:CustomValidator>
<asp:Button ID=”Button1″ runat=”server” Text=”Submit” />

hope it helps

Good Luck

Validate Fileupload Control

Filed under: ASP.Net — Tags: — yasserzaid @ 8:07 pm

Hi

try this example to Validate Fileupload Control to allow user to upload Doc files only

<asp:FileUpload ID=”UploadFile” runat=”server” />
<asp:Button Text=”Save” ID=”btnSave” runat=”server”
OnClientClick=”javascript:return ValidateUpload();” />    
 
<script type=”text/javascript” language=”javascript”>
    function ValidateUpload()
            {          
                var Upload_file = document.getElementById(‘<%= UploadFile.ClientID %>’);               
                var myfile = Upload_file.value;              
                if(myfile.indexOf(“doc”)>0)
                {
                 alert(‘Valid Format’);
                }
                else
                {
                 alert(‘Invalid Format’);
                }           
            }
 </script>

Validating with RegularExpression validator:

<asp:FileUpload ID=”UploadFile” runat=”server” />
<asp:RegularExpressionValidator ID=”RegularExpressionValidator1″ runat=”server”
ErrorMessage=”Only Doc files are allowed”
ControlToValidate=”UploadFile” ValidationExpression=”^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.doc|.DOC)$”>
</asp:RegularExpressionValidator>

Hope this helps

Good Luck

Older Posts »

Blog at WordPress.com.