Faraz Shah Khan

MCP, MCAD.Net, MCSD.Net, MCTS-Win, MCTS-Web, MCPD-Web

February 2008 - Posts

Javascript Enable/Disable Dropdown in Gridview using Checkboxes

If you come up with some requirement in which you have a Checkbox and a DropDownList in GridView control and you are requried to enable disable the DropDownList on the basis of the CheckBox value you can use following Code.


-----------------------------------.aspx file ----------------------------------

<script type="text/javascript">
        function StatusGridDropdown(drpdown)
        {
            document.getElementById(drpdown).disabled = !document.getElementById(drpdown).disabled;
        }
</script>
.
.
.
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" Width="400px">
        <Columns>
            <asp:TemplateField>
                <AlternatingItemTemplate>
                    <asp:CheckBox ID="cbStatus" runat="server" />
                </AlternatingItemTemplate>
                <ItemTemplate>
                    <asp:CheckBox ID="cbStatus" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <AlternatingItemTemplate>
                    <asp:DropDownList ID="ddl" runat="server" Enabled="False" Width="169px">
                    </asp:DropDownList>
                </AlternatingItemTemplate>
                <ItemTemplate>
                    <asp:DropDownList ID="ddl" runat="server" Width="169px" Enabled="False">
                    </asp:DropDownList>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
</asp:GridView>


----------------------------------.vb file if VB.Net is the language ------------------------------------

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            DirectCast(e.Row.FindControl("cbStatus"), CheckBox).Attributes.Add("onclick", "javascript:StatusGridDropdown('" & DirectCast(e.Row.FindControl("ddl"), DropDownList).ClientID & "')")
        End If
End Sub


----------------------------------.cs file if C#.Net is the language ------------------------------------

protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
    if ((e.Row.RowType == DataControlRowType.DataRow)) {
        ((CheckBox)e.Row.FindControl("cbStatus")).Attributes.Add("onclick", "javascript:StatusGridDropdown('" + ((DropDownList)e.Row.FindControl("ddl")).ClientID + "')");
    }
}

Reading file content from different webserver using HttpWebRequest

I was replying to one of the post on the ASP.Net forum in which the requirement was like reading txt file contents from different webservers. When he got satisfied with the solution then I thought to put the piece of code in my blog as well for others and my future reference.

--- .vb file if VB.Net is the language ---

        If Not (IsPostBack) Then
            Try
                Dim fr As System.Net.HttpWebRequest = DirectCast(System.Net.HttpWebRequest.Create(New Uri("http://weblogs.asp.net/farazshahkhan")), System.Net.HttpWebRequest)
                'In above code http://weblogs.asp.net/farazshahkhan is used as an example it can be different domain with different filename and extension
                If (fr.GetResponse().ContentLength > 0) Then
                    Dim str As New System.IO.StreamReader(fr.GetResponse().GetResponseStream())
                    Response.Write(str.ReadToEnd())
                End If

            Catch ex As System.Net.WebException
                Response.Write("File does not exist.")
            End Try
           
        End If

--- .cs file if C#.Net is the language ---

if (!(IsPostBack))
    {
        try {
            System.Net.HttpWebRequest fr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(new Uri("http://weblogs.asp.net/farazshahkhan"));
            //In above code http://weblogs.asp.net/farazshahkhan is used as an example it can be different domain with different filename and extension
            if ((fr.GetResponse().ContentLength > 0)) {
                System.IO.StreamReader str = new System.IO.StreamReader(fr.GetResponse().GetResponseStream());
                Response.Write(str.ReadToEnd());
            }
        }
       
        catch (System.Net.WebException ex) {
            Response.Write("File does not exist.");
        }
       
    }

Passing value from popup window to parent form's TextBox

Once again seen lot of questions on the forum related to passing values from popup window to the parent form textbox. Specially when they have some GridView type control in the popup. In the following example I will be using two forms, parent form will be parent.aspx and popup will be popup.aspx. Also note that my parent.aspx form is derived from some MasterPage. Code is provided both in VB.Net and C#.Net.

--- .aspx of parent form ---

<script type="text/javascript">
        function OpenPopup()
        {
            window.open("popup.aspx","List","scrollbars=no,resizable=no,width=400,height=280");
            return false;
        }
</script>
.
.
.
<asp:TextBox ID="txtPopupValue" runat="server" Width="327px"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Show List" />

--- .vb of parent.aspx if vb.net is the language ---

If Not IsPostBack Then
 Me.Button1.Attributes.Add("onclick", "javascript:return OpenPopup()")
End If

--- .cs of parent.aspx if C#.net is the language ---

if !(IsPostBack)
{
 this.Button1.Attributes.Add("onclick", "javascript:return OpenPopup()");
}

 

--- .aspx of popup form ---

<script language="javascript">
        function GetRowValue(val)
        {
            window.opener.document.getElementById("ctl00_ContentPlaceHolder1_TextBox2").value = val; //hardcoded value used to minimize the code. ControlID can be passed as query string to the popup window
            window.close();
        }
</script>
.
.
.
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" Width="400px" AllowPaging="True">
            <Columns>
                <asp:TemplateField>
                    <AlternatingItemTemplate>
                        <asp:Button ID="btnSelect" runat="server" Text="Select" />
                    </AlternatingItemTemplate>
                    <ItemTemplate>
                        <asp:Button ID="btnSelect" runat="server" Text="Select" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

--- .vb file if vb.net is the language ---

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            DirectCast(e.Row.FindControl("btnSelect"), Button).Attributes.Add("onclick", "javascript:GetRowValue('" & e.Row.Cells(1).Text & "')") 'assuming that the required value column is the second column in gridview
        End If
    End Sub

--- .cs file if C#.net is the language ---

protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
    if ((e.Row.RowType == DataControlRowType.DataRow)) {
        ((Button)e.Row.FindControl("btnSelect")).Attributes.Add("onclick", "javascript:GetRowValue('" + e.Row.Cells(1).Text + "')");
        //assuming that the required value column is the second column in gridview
    }
}

 

I hope the code above is straight forward and easy to understand.

Happy Coding!!!

Javascript to display time on Web page

Javascript to display continuous time on the Web page. By continuous it means that it will be displayed second by second.

    <script type="text/javascript">
        function ShowTime()
        {
            var dt = new Date();
            document.getElementById("<%= TextBox1.ClientID %>").value = dt.toLocaleTimeString();
            window.setTimeout("ShowTime()", 1000);
        }
       
            
    </script>

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>


If you are using normal Webform then it can be called on Body load event. If you are using MasterPage then it can be called within ContentTemplate at the end afte all the controls will be rendered.

Check/Uncheck checkboxes in GridView using javascript
Seen a lot of questions regarding how to check/uncheck CheckBoxes within a GridView control using JavaScript. So I thought to put it on my blog for quick reference for others and for myself. Following is the code:
------------------------------------------- .aspx code ---------------------------------------------
<script type="text/javascript">
function SelectAll(id)
      {
       var frm = document.forms[0];
           
            for (i=0;i<frm.elements.length;i++)
            {
                if (frm.elements[i].type == "checkbox")
                {
           frm.elements[i].checked = document.getElementById(id).checked;
                }
            }
        }
               
</script>
<!-- assuming that SqlDataSource1 is the datasource for my GridView -->
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" Width="400px">
        <Columns>
            <asp:TemplateField>
                <AlternatingItemTemplate>
                    <asp:CheckBox ID="CheckBox1" runat="server" />
                </AlternatingItemTemplate>
                <ItemTemplate>
                    <asp:CheckBox ID="CheckBox1" runat="server" />
                </ItemTemplate>
                <HeaderTemplate>
                    <asp:CheckBox ID="cbSelectAll" runat="server" Text="Select All" />
                </HeaderTemplate>
                <HeaderStyle HorizontalAlign="Left" />
                <ItemStyle HorizontalAlign="Left" />
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

----------------------------------------- .vb file if VB.Net is the language ------------------------------------------
VB.Net Code

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        If (e.Row.RowType = DataControlRowType.Header) Then
            'adding an attribut for onclick event on the check box in the hearder and passing the ClientID of the Select All checkbox
            DirectCast(e.Row.FindControl("cbSelectAll"), CheckBox).Attributes.Add("onclick", "javascript:SelectAll('" & DirectCast(e.Row.FindControl("cbSelectAll"), CheckBox).ClientID & "')")
        End If
    End Sub


----------------------------------------- .cs file if C#.Net is the language ------------------------------------------
C#.Net Code


protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
        if ((e.Row.RowType == DataControlRowType.Header))
        {
            //adding an attribut for onclick event on the check box in the hearder and passing the ClientID of the Select All checkbox
            ((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick", "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "')");
        }
    }

Personalization Scope
I was working on a site in which I had to implement webparts. The problem which I faced was I could only allow the admin to change the layout of the page (positioning of webparts) and that updated layout must be visible to all users.
 
Working with webparts we require WebpartManager who manages all the webparts. There is a property of WebpartManager which is called Scope, it is a read only property. There are two types of scopes that are PersonalizationScope.User and PersonalizationScope.Shared. PersonalizationScope is an enumeration for the two scopes.
 
If you are using personalization all the changes made will only be visible to that particular user who made those changes, because when user logs in it enters into PersonalizationScope.User and the changes will not be visible to anyone else. What to do if we have above mentioned scenario in which only one user can make changes and it will be visible to everyone.
 
in the Form_Load even try to do this.
 
if (this.WebpartManager1.Personalization.Scope==PersonalizationScope.User)
     this.WebpartManager1.Personalization.ToggleScope();
 
ToggleScope() method will invert this scope if it is User then it will change it to Shared or vice versa.
 
In this case if the user logs in who have rights to change out will enter in Shared mode and all the changes he made will be visible to all users.
 
You will be required to add following attribute in the webconfig's webpart tag which is bold
 
<webParts>
.
. //webParts other settings

<authorization>
<
allow verbs="enterSharedScope" users="*"
/>
</
authorization
>
.
.

</personalization>

</webParts>

More Posts