In previous article we added html markup in our web pages. In this article we’ll add C# codes in the code behind files. These codes will do the main work of pulling database information to our web pages.
First we need to make connection to our database in order to fetch information from it. So we’ll add a database connection string to our web.config file. Go to server explorer and select our database in Data Connection category. Now from properties window copy the connection String. Open web.config file and add this under the <configuration> tag:

<connectionStrings>
  <add name="ourdb" providerName="System.Data.SqlClient" connectionString="your connection string"/>
</connectionStrings>

First open write.aspx.cs file so that we can write a blog. Put these lines of codes in this file. Don’t remove the earlier references in these file. We need the System.Data and System.Data.SqlClient references for database related operations :

using System.Data;
using System.Data.SqlClient;

public partial class write : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ourdb"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }

            SqlCommand cmd = new SqlCommand("insert into BlogPost(Title,Content,Author, BlogDate) values(@title,@content,@author,@date)", con);
            cmd.Parameters.AddWithValue("@title", txbxTitle.Text);
            cmd.Parameters.AddWithValue("@content", txbxContent.Text);
            cmd.Parameters.AddWithValue("@author", txbxAuthor.Text);
            cmd.Parameters.AddWithValue("@date", System.DateTime.Now);
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            Response.Write("done!!!!!!");
        }
        catch (Exception k)
        {
            Response.Write(k.Message);
            //throw;
        }
        finally { con.Close(); }
    }
}

Add these lines in default.aspx.cs file:

using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ourdb"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        BindBlog();
    }

    void BindBlog()
    {
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }

            SqlCommand cmd = new SqlCommand("select * from BlogPost order by BlogDate desc ", con);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
            cmd.Dispose();
        }
        catch (Exception k)
        {
            Response.Write(k.Message);
            //throw;
        }
        finally
        {
            con.Close();
        }

    }
}

And finally add these lines in details.aspx.cs file :

using System.Data;
using System.Data.SqlClient;

public partial class details : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ourdb"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString.Get("Id") != null)
        {
            DetailsView1.DefaultMode = DetailsViewMode.ReadOnly;
            detail();
            bindComment();
        }
    }

    void detail()
    {
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            SqlCommand cmd = new SqlCommand("select * from BlogPost where Id=@id", con);
            cmd.Parameters.AddWithValue("@id", Request.QueryString["Id"]);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            ds.Tables[0].Columns.Add("FormDate", typeof(string));
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                DateTime date = (DateTime)ds.Tables[0].Rows[0]["BlogDate"];
                string format = "MMM ddd d, yyyy";
                ds.Tables[0].Rows[0]["FormDate"] = date.ToString(format);
            }
            DetailsView1.DataSource = ds;
            DetailsView1.DataBind();
            cmd.Dispose();
        }
        catch (Exception k)
        {
            Response.Write(k.Message);
            //throw;
        }
        finally
        {
            con.Close();
        }
    }

    void bindComment()
    {
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }

            SqlCommand cmd = new SqlCommand("select * from Comments where BlogId=@id", con);
            cmd.Parameters.AddWithValue("@id", Request.QueryString["Id"]);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            if (ds.Tables[0].Rows.Count == 0)
            {
                GridViewcomment.Visible = false;
                LabelNoComment.Visible = true;
            }
            else
            {
                GridViewcomment.Visible = true;
                LabelNoComment.Visible = false;
                GridViewcomment.DataSource = ds;
                GridViewcomment.DataBind();
            }

        }
        catch (Exception)
        {

            throw;
        }
        finally { con.Close(); }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            if (txbxcomment.Text != txbxcomment.ToolTip.ToString() || txbxcommentauthor.Text != txbxcommentauthor.ToolTip.ToString())
            {
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }

                SqlCommand cmd = new SqlCommand("insert into Comments(BlogId, Comment, Name, Date) values(@bid,@com,@name,@date)", con);
                cmd.Parameters.AddWithValue("@bid", Request.QueryString["Id"]);
                cmd.Parameters.AddWithValue("@com", txbxcomment.Text);
                cmd.Parameters.AddWithValue("@name", txbxcommentauthor.Text);
                cmd.Parameters.AddWithValue("@date", System.DateTime.Now);
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                txbxcomment.Text = String.Empty;
                txbxcommentauthor.Text = String.Empty;
                bindComment();
            }
            else
            {

            }

        }
        catch (Exception)
        {

            throw;
        }
        finally { con.Close(); }
    }
}

Now open your write.aspx file in browser and write a test blog. After successful submission of test blog run default.aspx file. You will see your blog. Click on Blog title , it will redirect to details.aspx page, where you can write comments. You can add other functionality to you blog and that will look much better than this. This tutorial was only for beginners to give them basic idea of blogging application.