Tuesday, 2 October 2012

Adding to columns together to produce a new column






using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnload_Click(object sender, EventArgs e)
    {
        string constring = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Abayomi\Documents\Visual Studio 2010\WebSites\calculatedcolumns2\App_Data\product.mdf;Integrated Security=True;User Instance=True";

        SqlConnection conn = new SqlConnection(constring);
        string sqlcat = "select categoryID,categoryName from CategoriesTB";
        string sqlprod = "select productName,categoryID,UnitPrice from productsTB";

        SqlDataAdapter da = new SqlDataAdapter(sqlcat, conn);
        DataSet ds = new DataSet();

        conn.Open();
        da.Fill(ds, "CategoriesTB");
        da.SelectCommand.CommandText = sqlprod;
        da.Fill(ds, "productsTB");
        conn.Close();

        // Define the realationships between Categories and Products
        DataRelation relat = new DataRelation("CatProds", ds.Tables["CategoriesTB"].Columns["categoryID"], ds.Tables["productsTB"].Columns["categoryID"]);
        ds.Relations.Add(relat);

        DataColumn count = new DataColumn("Product(#)", typeof(int), "SUM(Child(CatProds).categoryID)");

        ds.Tables["categoriesTB"].Columns.Add(count);

        GridView1.DataSource = ds.Tables["CategoriesTB"];
        GridView1.DataBind();
    }
}

No comments:

Post a Comment