Saturday, July 4, 2015

Change the StyleSheet (CSS) file dynamically in Asp.net

Introduction: In this article I will explain how to how to change the stylesheet (CSS) file dynamically in asp.net

Description:

To implement this functionality in asp.net website/project I have create an example. I have created 3 stylesheet (CSS) files in CSS folder.
StyleSheet:
body {
    font-family:Arial;
    font-size:15px;
    }
.container
{
    background:#fff;
    color:#000;
    text-align:center;
    font-weight:bold;
    }
table {
  margin-left: 375px;
}

StyleSheet2:
body {
    font-family:Arial;
    font-size:15px;
    }
.container
{
    background:#0094ff;
    color:#fff;
    text-align:center;
     font-weight:bold;
    }
table {
  margin-left: 375px;
}

StyleSheet3:
body {
    font-family:Arial;
    font-size:15px;
    }
.container
{
    background:#ff0000;
    color:#fff;
    text-align:center;
    font-weight:bold;
    }
table {
  margin-left: 375px;
}

StyleSheet is default Stylesheet of project/website.
I have added three buttons to webform to change the stylesheet.

Html Markup of webform:-
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
     <link href="css/StyleSheet.css" rel="stylesheet" id="linkstylesheet" runat="server"/>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div class="container">
        Welcome to ArticleMirror Blog
    </div>
        <table><tr><td>
            <asp:Button ID="btndefault" runat="server" Text="Change To Default StyleSheet"/></td><td><asp:Button ID="btnstyle2" runat="server" Text="Change To Second StyleSheet" /></td><td><asp:Button ID="btnstyle3" runat="server" Text="Change To 3rd StyleSheet"/></td></tr></table>
    </div>
    </form>
</body>
</html>

Write the code on button Click.
C#:
protected void btndefault_Click(object sender, EventArgs e)
    {
        linkstylesheet.Href = "~/CSS/" + "StyleSheet.css";
    }
    protected void btnstyle2_Click(object sender, EventArgs e)
    {
        linkstylesheet.Href = "~/CSS/" + "StyleSheet2.css";
    }
    protected void btnstyle3_Click(object sender, EventArgs e)
    {
        linkstylesheet.Href = "~/CSS/" + "StyleSheet3.css";
    }

VB:
Protected Sub btndefault_Click(sender As Object, e As EventArgs) Handles btndefault.Click
        linkstylesheet.Href = "~/CSS/" + "StyleSheet.css"
    End Sub
    Protected Sub btnstyle2_Click(sender As Object, e As EventArgs) Handles btnstyle2.Click
        linkstylesheet.Href = "~/CSS/" + "StyleSheet2.css"
    End Sub
    Protected Sub btnstyle3_Click(sender As Object, e As EventArgs) Handles btnstyle3.Click
        linkstylesheet.Href = "~/CSS/" + "StyleSheet3.css"
    End Sub

Build, run the project and check out the result.
 Result:-
Change the stylesheet (CSS) file dynamically in asp.net


 In this article we have learn how to change the StyleSheet (CSS) file dynamically in asp.net. I hope you enjoyed this article. 

No comments:

Post a Comment