自己做的資料繫結控制項
最後更新:2017-02-28
來源:互聯網
上載者:User
控制項|資料 很久都沒有寫一點東西了,最近一直在學習.net,前兩天看到椰子林寫的一篇《ASP.NET分頁組件學與用》,於是自己就跟著做了一遍,一次成功,在此向他表示感謝,也向他那種共用的精神致敬!可是後來我發覺這個組件用起來有點麻煩,在Page_Load裡面不但要得到記錄集,還要寫SQL語句分頁,最後還要自己寫代碼將包含資料的<table></table>輸出到用戶端,於是我就想呀要是可以像DataGrid那樣只是簡單的綁定一下就可以用就好,分頁,顯示資料呀這些都交給組件去完成,正是這靈光一現,我就開始衝動了,沒辦法程式就是有這麼大的魅力!結果,我昨天晚上失眠了,哎!衝動的懲罰呀!今天早上,我帶著紅腫的眼睛走進了機房,開始實現我昨天晚上夢見的那個東東,幸運的是--我實現了,呵呵,一個字爽!忘了告訴大家,我還是一個學生,做出來我很高興了,技巧談不上,高手們看了莫怪。下面我把基本的做法說一下!
如何做自訂控制項,以及如何?分頁在這裡我就不多說了,大家可以看一下椰子林寫的相關文章,我要說說我的做法:
首先定義一個DataSource屬性,如下:
private DataTable dt; //資料來源
/// <summary>
/// 資料來源
/// </summary>
public DataTable DataSource
{
get
{
return dt;
}
set
{
if (value == null)
throw new Exception("資料來源不可為空白");
else
dt = value;
}
}
該屬性用於接受前端傳進來的DataTable對象。我們可以在前端使用ADO.NET獲得資料並將資料填充到一個DataTable中,再將此包含資料的DataTable賦於組件的DataSource屬性,接下來的工作就是由組件向用戶端輸出包含資料的<table></table>標籤了,怎麼樣簡單吧!其實沒有做多少改進,只是簡單的擴充了一下,如下:
/// <summary>
/// 建立資料表
/// </summary>
/// <returns>表格的Html表示字串</returns>
protected string CreateDataTable()
{
string table = null; //表格,顯示了所有的欄位和記錄
string tableHead = null; // 表頭用於顯示欄位名的<tr>
string tdHead = null; // 表頭用於顯示欄位名的<td>包含在tableHead中
string tableBody = null; // 表主體用於顯示記錄的<tr>
// 為了實現分頁定義min和max兩個變數
// min代表從那一條記錄開始顯示
// max代表到那一條記錄結束
// 如果當前是第2頁每頁顯示10條記錄的話,那麼min的值就是10,max的值就是20
int min = 0;
int max = 0;
// for迴圈用於產生表頭,即欄位名
for (int i = 0; i < this.dt.Columns.Count; i++)
{
tdHead = tdHead + "<td>" + this.dt.Columns[i].ColumnName + "</td>";
}
// 判斷當前頁是否最後一頁
if (this.currentpage == this.PageCount)
{
min = (this.currentpage - 1) * this.count;
max = this.dt.Rows.Count;
}
else
{
min = (this.currentpage - 1) * this.count;
max = this.currentpage * this.count;
}
// for迴圈用於產生表主體,即提取記錄
for (int j = min; j < max; j++)
{
tableBody = tableBody + "<tr bgcolor='#FFFFFF'>";
for (int k = 0; k < this.dt.Columns.Count; k++)
{
tableBody = tableBody + "<td>" + this.dt.Rows[j][k].ToString() + "</td>";
}
tableBody = tableBody + "</tr>";
}
tableHead = "<tr bgcolor='#FFFFFF'>" + tdHead + "</tr>";
table = "<table border='0' cellpadding='0' cellspacing='1' width='100%' height='100%' bgcolor='#000000' style='font-size:9pt'>" + tableHead + tableBody + "</table>";
return table;
}
這樣就得到了包含資料的表格的Html字串,跟著就是做分頁部分,最後重寫Render(HtmlTextWriter output)方法將整個組件輸出到用戶端!這裡我不一一詳述步驟,我把代碼帖出來,有興趣的可以將代碼拷貝到本機上運行一下!
組件原始碼如下:(調試通過)
public class MyDataGrid : System.Web.UI.WebControls.WebControl
{
private int currentpage; //當前頁
private int count; //每頁顯示的記錄條數
private int navigcount; //瀏覽連線的個數
private DataTable dt; //資料來源
private const string SCRIPTSTRING = "<script language='javascript'>\n" +
" function go(ctrl,max)\n" +
"{\n" +
"if(ctrl.value >= 1 && ctrl.value <= max)\n" +
"{\n" +
"var url;\n" +
"var index;\n" +
"url = location.href;\n" +
"index = url.indexOf('?');\n" +
"if(index == -1)\n" +
"{\n" +
"}\n" +
"else\n" +
"{\n" +
"url = url.substring(0,index);\n" +
"}\n" +
"location.href = url + '?CurrentPage=' + ctrl.value;\n" +
"}\n" +
"else\n" +
"{\n" +
"alert('您輸入的頁碼必須是符合頁面要求的數字,最大值是:' + max);\n" +
"return false;\n" +
"}\n" +
"}\n" +
"</script>\n";
/// <summary>
/// 當前頁
/// </summary>
public int CurrentPage
{
get
{
return currentpage;
}
set
{
if (value <= 0)
currentpage = 1;
else
currentpage = value;
}
}
/// <summary>
/// 每頁顯示的記錄條數
/// </summary>
public int Count
{
get
{
return count;
}
set
{
if (value <= 0)
count = 10;
else
count = value;
}
}
/// <summary>
/// 瀏覽連線的個數
/// </summary>
public int NavigCount
{
get
{
return navigcount;
}
set
{
if (value <= 0)
navigcount = 10;
else
navigcount = value;
}
}
/// <summary>
/// 總頁數
/// </summary>
public int PageCount
{
get
{
if (this.dt.Rows.Count % count > 0)
return ((int)this.dt.Rows.Count / count) + 1;
else
return ((int)this.dt.Rows.Count / count);
}
}
/// <summary>
/// 資料來源
/// </summary>
public DataTable DataSource
{
get
{
return dt;
}
set
{
if (value == null)
throw new Exception("資料來源不可為空白");
else
dt = value;
}
}
protected override void Render(HtmlTextWriter output)
{
string Table = CreateDataTable();
string PageControl = CreatePageControl();
string Result = string.Format("<table border='0' cellpadding='0' cellspacing='1' width='724' height='93' bgcolor='#000000' style='font-size: 9pt'>\n" +
"<tr bgcolor='#FFFFFF'>\n" + "<td width='724' height='68' valign='top'>{0}</td>\n" + "</tr>\n" +
"<tr bgcolor='#FFFFFF'>\n" + "<td width='724' height='25' valign='top'>{1}</td>\n" + "</tr>\n" + "</table>\n",Table.ToString(),PageControl.ToString());
output.Write(Result.ToString());
}
/// <summary>
/// 建立資料表
/// </summary>
/// <returns>表格的Html表示字串</returns>
protected string CreateDataTable()
{
string table = null; //表格,顯示了所有的欄位和記錄
string tableHead = null; // 表頭用於顯示欄位名的<tr>
string tdHead = null; // 表頭用於顯示欄位名的<td>包含在tableHead中
string tableBody = null; // 表主體用於顯示記錄的<tr>
// 為了實現分頁定義min和max兩個變數
// min代表從那一條記錄開始顯示
// max代表到那一條記錄結束
// 如果當前是第2頁每頁顯示10條記錄的話,那麼min的值就是10,max的值就是20
int min = 0;
int max = 0;
// for迴圈用於產生表頭,即欄位名
for (int i = 0; i < this.dt.Columns.Count; i++)
{
tdHead = tdHead + "<td>" + this.dt.Columns[i].ColumnName + "</td>";
}
// 判斷當前頁是否最後一頁
if (this.currentpage == this.PageCount)
{
min = (this.currentpage - 1) * this.count;
max = this.dt.Rows.Count;
}
else
{
min = (this.currentpage - 1) * this.count;
max = this.currentpage * this.count;
}
// for迴圈用於產生表主體,即提取記錄
for (int j = min; j < max; j++)
{
tableBody = tableBody + "<tr bgcolor='#FFFFFF'>";
for (int k = 0; k < this.dt.Columns.Count; k++)
{
tableBody = tableBody + "<td>" + this.dt.Rows[j][k].ToString() + "</td>";
}
tableBody = tableBody + "</tr>";
}
tableHead = "<tr bgcolor='#FFFFFF'>" + tdHead + "</tr>";
table = "<table border='0' cellpadding='0' cellspacing='1' width='100%' height='100%' bgcolor='#000000' style='font-size:9pt'>" + tableHead + tableBody + "</table>";
return table;
}
/// <summary>
/// 建立分頁控制項
/// </summary>
/// <returns>返回分頁控制項的Html表示字串</returns>
protected string CreatePageControl()
{
string leftInfo = string.Format("頁:{0}/{1}"+" "+"每頁{2}條"+" "+"共{3}條",
this.CurrentPage.ToString(),this.PageCount.ToString(),this.Count.ToString(),this.dt.Rows.Count.ToString());
int min = 0;
int max = 0;
if (this.CurrentPage > this.PageCount)
{
this.CurrentPage = this.PageCount;
}
if (this.CurrentPage % this.Count == 0)
{
min = this.CurrentPage + 1;
max = this.CurrentPage + this.Count;
}
else if (this.CurrentPage % this.Count == 1&& this.CurrentPage > this.Count)
{
min = (((int)this.CurrentPage / this.Count) - 1) * this.Count + 1;
max = this.CurrentPage - 1;
}
else
{
min = ((int)this.CurrentPage / this.Count) * this.Count + 1;
max = (((int)this.CurrentPage / this.Count) + 1) * this.Count;
}
string numberStr = " ";
string url = this.Context.Request.Url.ToString();
if (url.IndexOf("?") == -1)
{
}
else
{
url = url.Substring(0,url.IndexOf("?"));
}
for (int i = min; i <= max; i++)
{
if (i <= this.PageCount)
{
if (i == this.CurrentPage)
{
numberStr = numberStr + "<a href=" + url + "?CurrentPage=" + i.ToString() + ">" + "<I style='color:red'>" + i.ToString() + "</I>" +"</a>" + "\n";
}
else
{
numberStr = numberStr + "<a href=" + url + "?CurrentPage=" + i.ToString() + ">" + i.ToString() +"</a>" + "\n";
}
}
}
string first,prev,next,last;
first = url + "?CurrentPage=" + 1;
if (this.CurrentPage == 1)
{
prev = url + "?CurrentPage=1";
}
else
{
prev = url + "?CurrentPage=" + (this.CurrentPage - 1).ToString();
}
if (this.CurrentPage == this.PageCount)
{
next = url + "?CurrentPage="+ this.PageCount;
}
else
{
next = url + "?CurrentPage=" + (this.CurrentPage + 1).ToString();
}
last = url + "?CurrentPage=" + this.PageCount;
string centerInfo = string.Format("<font face='Webdings' style='font-size:14px'><a href={0}>7</a><a href={1}>3</a></font>{2}<font face='Webdings' style='font-size:14px'><a href={3}>4</a><a href={4}>8</a></font>",first,prev,numberStr,next,last);
string result = string.Format("<table border='0' cellpadding='0' cellspacing='0' width='100%' style='font-size:9pt'>\n" +
"<tr><td width='25%' align='left'>{0}</td>\n" +
"<td width='61%' align='right'>{1}</td>" +
"<td width='14%' align='right'><input type='text' name='T1' size='4' style='border-bottom:solid 1pt gray;border-top :solid 1pt gray; border-left:solid 1pt gray;border-right:solid 1pt gray;'> \n <input type='button' name='B1' size='6' value=go style='border-bottom:solid 1pt gray;border-top :solid 1pt gray; border-left:solid 1pt gray;border-right:solid 1pt gray;' ></td>\n" +
"</tr></table>",leftInfo,centerInfo,this.PageCount);
return result;
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender (e);
if(!Page.IsClientScriptBlockRegistered("WEREW-332DFAF-FDAFDSFDSAFD"))
{
Page.RegisterClientScriptBlock("WEREW-332DFAF-FDAFDSFDSAFD",SCRIPTSTRING);
}
}
}
測試工程代碼:
public class TestMyDataGrid : System.Web.UI.Page
{
protected myControlLibrary.MyDataGrid MyDataGrid1;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此處放置使用者代碼以初始化頁面
int currentpage;
if (this.Request.Params["CurrentPage"] == null)
{
currentpage = 1;
}
else
{
currentpage = Convert.ToInt32(this.Request.Params["CurrentPage"].ToString());
}
this.MyDataGrid1.CurrentPage = currentpage;
this.MyDataGrid1.Count = 10;
this.MyDataGrid1.NavigCount = 10;
SqlConnection conn = new SqlConnection("server=localhost; database=NorthWind; uid=sa");
SqlCommand cmd = new SqlCommand("select * from [Order Details]",conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
conn.Open();
da.Fill(ds,"table");
conn.Close();
this.MyDataGrid1.DataSource = ds.Tables["table"];
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN:該調用是 ASP.NET Web Form設計器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 設計器支援所需的方法 - 不要使用代碼編輯器修改
/// 此方法的內容。
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
頁面版排的不好,只好勞動一下你,呵呵!