PDA

View Full Version : Help with basic ASP.NET page using Access DB as datasource?


Iconoclast
09-17-2009, 09:07 PM
Hey guys, I'm familiar with both ASP and C#, but I'm pretty new to ASP.NET...anyways, I'm looking to make a pretty basic page that will use a customer-based Access DB (which I have already created and can provide if necessary) as a datasource...when the page loads, I want it to load the first customers' information onto the page. I also want to have a drop-down menu that users can click to select different customers within the DB and have it load their respective data.


Here's what I know:

I know I need to make a Customer.cs class within C# with public fields for each column in the Customers table in the DB, and somehow use it to create a Customer object that will contain the information about the selected customer.

I know I need to add the database as the datasource for the default page of the site...it needs to return all rows and columns from the Customers table sorted by Name...then somehow I need to bind the drop down menu to the datasource so the name column is displayed for each item in the list and the CustomerID column is stored as the value for each item. (I'm not exactly sure how I would do this, if anyone can help me with this part)

I'm going to use a table to align the information being returned from the DB (phone #, address, email, etc.)


If anyone can help me out with what I need to do to start something simple like this, I would greatly appreciate it, I'm kind of at a loss of where to start and I know it shouldn't be too complicated. Thanks for any help! And remember I'm new to this stuff! :)

ragol_67
10-06-2009, 10:21 PM
I would recommend picking up the book ASP.NET Step-by-Step. You can order this from MSPRESS, or pick it up at your University/College bookstore.

This assignment is pretty big, so I'm not going to write out all the code for you, but here is where I would start:

Use a 3-layer design model.

Start with the DataAccess Layer. Test the DA to ensure it can actually retrieve the info from the database. The step-by-step book shows you exactly how to do this. You could even create an Abstract class to encapsulate all your similar code. Then if you ever need to add more tables to your database, you can easily add another DA class.

Then move onto creating your Business Objects. This would be your Customer.cs class that holds your customer objects once retrieved from the database.

Once you have written that code, it is very simple to populate a DataGrid with the data, using:

gridName.DataSource = _customers.ReadOnlyCopy();
gridName.DataBind();


Here is an example of an Abstract Data Access Class:


using System;
using System.Data;
using System.Data.Common;

namespace Content.DataAccess
{
/// <summary>
/// Encapsulates common functionality needed by our data access classes
/// </summary>
public abstract class AbstractDA
{

/// <summary>
/// Defines the basic select statement for retrieving data
/// without criteria.
///
/// This property is implemented by the concrete subclasses.
/// </summary>
protected abstract string SelectStatement
{
get;
}


/// <summary>
/// Defines any sort order fields
///
/// This property is implemented by the concrete subclasses.
/// </summary>
protected abstract string OrderFields
{
get;
}


/// <summary>
/// Defines any field name of primary key field
///
/// This property is implemented by the concrete subclasses.
/// </summary>
protected abstract string KeyFieldName
{
get;
}

/// <summary>
/// Returns a data table containing PostCategory table info for this id.
/// Note that this data set will contain either 0 or 1 rows of data.
/// </summary>
public DataTable GetById(int id)
{
// set up parameterized query statement
string sql = SelectStatement + " WHERE " + KeyFieldName + "=@id";

// construct array of parameters
DbParameter[] parameters = new DbParameter[] {
DataHelper.MakeParameter("@id", id, DbType.Int32)
};

// return result
return DataHelper.GetDataTable(sql, parameters);
}

/// <summary>
/// Returns all the data for the data source
/// </summary>
public DataTable GetAll()
{
string sql = SelectStatement;
return DataHelper.GetDataTable(sql, null);
}
/// <summary>
/// Returns all the data for the data source
/// </summary>
public DataTable GetAllSorted(bool ascending)
{
string sql = SelectStatement;
sql += " ORDER BY " + OrderFields;
if (!ascending)
sql += " DESC";
return DataHelper.GetDataTable(sql, null);
}

/// <summary>
/// Returns a data table containing the top X records (based on the sort order).
///
/// Note that this data set will contain either 0 or 1 rows of data.
/// </summary>
public virtual DataTable GetTop(int howMany, bool ascending)
{
// set up parameterized query statement
string sql = SelectStatement;
sql += " ORDER BY " + OrderFields;
if (!ascending)
sql += " DESC";

string topSql = sql.Replace("SELECT", "SELECT TOP " + howMany);

// return result
return DataHelper.GetDataTable(topSql, null);
}
}
}




Here is an example of an Abstract Business Object Class:


using System;
using System.Data;
using System.Collections.Generic;

using Content.DataAccess;

namespace Content.Business
{
/// <summary>
/// Repesents the base class for all business objects
/// </summary>
public abstract class AbstractBO
{
// data members
#region data members
protected const int DEFAULT_ID = 0;

private int _id;
private AbstractDA _dataAccess;

// flags for whether object is new or has been modified
private bool _isNew = true;
private bool _isModified = false;
private BusinessRuleManager _businessRules = new BusinessRuleManager();


#endregion

#region abstracts

/// <summary>
/// Given a data table with data, populate the business objects data members.
///
/// Implemented by each business object subclass
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
public abstract void PopulateDataMembersFromDataRow(DataRow table);

/// <summary>
/// Each subclass will be responsible for checking if its
/// own state (data members) has any broken business rules
/// </summary>
protected abstract void CheckIfSubClassStateIsValid();


/// <summary>
/// Update the content of the current business object
/// </summary>
public abstract void Update();

/// <summary>
/// Inserts the content of the current business object
/// </summary>
public abstract void Insert();

/// <summary>
/// Deletes the content of the current business object
/// </summary>
public abstract void Delete();
#endregion

#region public methods
/// <summary>
/// Saves the current business object
/// </summary>
public void Save()
{
if (IsValid)
{
if (IsModified)
{
if (IsNew)
Insert();
else
Update();
}
}
}
/// <summary>
/// Removes the current business object
/// </summary>
public void Remove()
{
Delete();
}

/// <summary>
/// Fetches a business object's data
/// </summary>
public bool FetchById(int id)
{
DataTable table = DataAccess.GetById(id);

// if the table has no data than load failed
BusinessRules.Assert("FetchIdNotFound", "Business Object with id=" + id + " was not found", table.Rows.Count == 0);
if (!BusinessRules.AreNoBrokenRules)
return false;

PopulateDataMembersFromDataRow(table.Rows[0]);
IsNew = false;
IsModified = false;

// make sure loaded data is valid according to business rules
return IsValid;
}
#endregion

#region protected properties
/// <summary>
/// The manager for the business rules for this object
/// </summary>
protected BusinessRuleManager BusinessRules
{
get { return _businessRules; }
}

/// <summary>
/// The data access class used by this business object
/// </summary>
protected AbstractDA DataAccess
{
get { return _dataAccess; }
set { _dataAccess = value; }
}

/// <summary>
/// Has the business object been modified since last save
/// </summary>
protected bool IsModified
{
get { return _isModified; }
set { _isModified = value; }
}

/// <summary>
/// Is this business object new or does it contain
/// data that exists in database
/// </summary>
public bool IsNew
{
get { return _isNew; }
set { _isNew = value; }
}
#endregion

#region public properties

/// <summary>
/// The id of the business object
/// </summary>
public int Id
{
get { return _id; }
set
{
if (_id != value)
{
_id = value;
IsModified = true;
}
}
}

/// <summary>
/// Is the business object valid
/// </summary>
public bool IsValid
{
get
{
BusinessRules.Assert("IdNotLessZero", "Id can not be less than zero", Id < 0);
CheckIfSubClassStateIsValid();
return BusinessRules.AreNoBrokenRules;
}
}

public List<string> BrokenRules
{
get { return BusinessRules.BrokenRules; }
}
#endregion
}
}



Hope this helps,

Nick.