[top1]Asp.Net经典常见代码Access版(常见模板,常见数据库操作代码,经典导航条)
一:常见模板
见模板篇。
二:常见数据库操作代码
2.1数据库的连接
在web.config中
<appSettings>
<add key="constr" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|topDB.mdb"/>
</appSettings>
在类Tools.cs中
OleDbConnection myConnection;
public void GetConnection()
{
//1.连接数据库
myConnection = new OleDbConnection(ConfigurationManager.AppSettings["constr"]);
myConnection.Open();
}
2.2 添加Query方法
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public DataSet Query(string SQLString)
{
DataSet ds = new DataSet();
try
{
GetConnection();
OleDbDataAdapter command;
string[] tempsql = SQLString.Split(';');
for (int i = 0; i < tempsql.Length; i++)
{
command = new OleDbDataAdapter(tempsql[i], myConnection);
command.Fill(ds, i.ToString());
}
return ds;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
if (myConnection != null)
{
myConnection.Close();
myConnection.Dispose();
}
}
}
2.3在需要绑定新闻的页面添加DataList控件
<asp:datalist ID="DataListWorkShop" runat="server" RepeatDirection="Vertical" DataKeyField="id" onitemcommand="DataListWorkShop_ItemCommand">
<itemtemplate>
<table width="100%" cellpadding="0" style="font-size:13px; font-family:宋体;display:inline;">
<tr onmouseover="this.style.backgroundColor='#FFFFFF'" onmouseout="this.style.backgroundColor=''">
<td width="19px"> <img src="images/news_header.jpg" /></td>
<td align="left" style="width:220px">
<asp:LinkButton ID="LinkButton1" runat="server"> <%# Intercept(DataBinder.Eval(Container.DataItem, "title").ToString())%></asp:LinkButton>
</td>
<td align="left" style="width:100px">
<%#DataBinder.Eval(Container.DataItem, "nDate", "{0:yyyy-MM-dd}")%>
</td>
</tr></table>
</itemtemplate>
</asp:datalist>
2.4让datalist绑定数据源
void bindWorkShop()
{
DataSet ds = new Tools().Query("select top 8 * from WorkShop order by id desc");
DataView dv = ds.Tables[0].DefaultView;
DataListWorkShop.DataSource = ds;
DataListWorkShop.DataBind();
}
protected void DataListWorkShop_ItemCommand(object source, DataListCommandEventArgs e)
{
string keyStr = this.DataListWorkShop.DataKeys[e.Item.ItemIndex].ToString();
Response.Redirect("pic_shows.aspx?Nid=" + keyStr + "&tableName=WorkShop");
}
2.5在页面加载时显示新闻
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindWorkShop();
}
}
一个新闻显示模块就做好了。