Popular Posts

Jul 25, 2013

Web page title change (Asp.net)





<body>
   <form id="Form2" runat="server">
      Title: <asp:Label id="_titleLabel"
                 Text="{no title assigned yet}"
                 runat="server"/>
   </form>
</body>


  In the code-behind

protected void Page_Load(object sender, EventArgs e)
    {
        int id;
        try
        {
            if (int.TryParse(Request.QueryString["id"], out id))
            {
                _titleLabel.Text = GetContentTitle(id);
            }
            else
            {
                _titleLabel.Text = "no id given; cannot look up title";
            }
        }
        catch (Exception ex)
        {
            // do something with the exception info
        }
    }

    private static string GetContentTitle(int id)
    {
        using (SqlConnection conn = new SqlConnection("your-connection-string"))
        using (SqlCommand cmd = new SqlCommand(
            "select ContentTitle from table where id = @id", conn))
        {
            SqlParameter param = new SqlParameter();
            param.ParameterName = "@id";
            param.Value = yourIdGoesHere;
            cmd.Parameters.Add(param);

            conn.Open();
            return (string)conn.ExecuteScalar();
        }
    }

No comments:

Post a Comment