Thursday, 2 July 2015

How to use Literal and Placeholder in asp.net ?

Design Page :-
       <div>
            <fieldset>
                <legend>Using Placeholder & Literals</legend>
                <asp:PlaceHolder ID="PlaceHolder1" runat="server" />
            <br />
                <asp:Literal ID="literalDemo" runat="server" />
            </fieldset>
</div>

Coding Page : -

Make class like this : -

        private static DataTable GetData()
        {
            DataTable dt = new DataTable();
            using (SqlConnection con = new SqlConnection(Common.Global.myconstring))
            {
                SqlDataAdapter adp = new SqlDataAdapter("GetData", con); //call procedure
                adp.Fill(dt);
            }
            return dt;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = GetData();
            StringBuilder sb = new StringBuilder();
            sb.Append("<table>");
            sb.Append("<tr>");
            foreach (DataColumn col in dt.Columns)
            {
                sb.Append("<th>");
                sb.Append(col.ColumnName);
                sb.Append("</th>");
            }
            sb.Append("</tr>");
            foreach(DataRow dr in dt.Rows)
            {
                sb.Append("<tr>");
                foreach(DataColumn col in dt.Columns)
                {
                    sb.Append("<td>");
                    sb.Append(dr[col.ColumnName]);
                    sb.Append("</td>");
                }
                
                sb.Append("</tr>");
            }
            sb.Append("</html>");
            literalDemo.Text = sb.ToString();

            // you can also use this if you take placeholder in design page.
            PlaceHolder1.Controls.Add(new Literal { Text = sb.ToString() });
        }

Output:-


No comments:

Post a Comment

Thanks for comments.