Data-bound controls that you do yourself

Source: Internet
Author: User
Tags definition count header min variables prev tostring
Control | Data It's been a long time since I've been studying. NET, two days ago to see the coconut forest written an ASP. NET paging component learning and use ", so he did it again, a success, here to thank him, but also to his share of the spirit of salute!" But then I found that this component to use a bit of trouble, in the Page_Load not only to get the recordset, but also to write the SQL statement pagination, and finally to write their own code will contain data <table></table> output to the client, So I think if it can be like the DataGrid just a simple binding can be used, pagination, display data ah these are given to the components to complete, it is this epiphany, I began to impulse, no way program is so great charm! As a result, I had insomnia last night, hey! The Impulsive punishment! This morning, I came into the room with red and red eyes, began to realize I dreamt of that East last night, fortunately-I realized, hehe, a word cool! Forgot to tell everyone, I am still a student, made to I am very happy, the skill is not, the master has seen Mo strange. Below I put the basic practice to say!

How to do custom controls and how to implement pagination here I will not say more, we can look at the related articles of coconut wood, I would like to talk about my approach:

First, define a DataSource property, as follows:

Private DataTable DT; Data source

<summary>
Data source
</summary>
Public DataTable DataSource
{
Get
{
return DT;
}
Set
{
if (value = = null)
throw new Exception ("Data source is not nullable");
Else
DT = value;
}
}
This property is used to accept the DataTable object that is passed in the front-end. We can use Ado.net to get the data and populate it in a DataTable, and then assign the DataTable containing the data to the DataSource properties of the component, and the next step is to output the data from the component to the client <table> </table> tags, how easy it is! In fact, did not do much improvement, but simply expanded a bit, as follows:

<summary>
Creating data Tables
</summary>
<returns> HTML representation string for table </returns>
Protected string createdatatable ()
{
string table = null; Table that shows all the fields and records
string tablehead = null; The header is used to display the field name <tr>
string tdhead = null; Header used to display field names <td> included in Tablehead
string tablebody = null; The table body is used to display the <tr> of the record

To implement a paging definition of min and max two variables
The Min representative starts from that record.
Max represents the end of the record.
If the current is the 2nd page display 10 records each page, then min's value is the 10,max value is 20
int min = 0;
int max = 0;

The For loop is used to generate the header, which is the field name
for (int i = 0; i < This.dt.Columns.Count; i++)
{
Tdhead = Tdhead + "<td>" + this.dt.columns[i]. ColumnName + "</td>";
}

Determines whether the current page is the last page
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;
}

The For loop is used to produce the table body, which is the fetch record
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;
}

This gets the HTML string of the table containing the data, followed by the pagination section, and finally rewrites the render (HtmlTextWriter output) method to output the entire component to the client! Here I do not detail the steps, I post the code, interested in the code can be copied to the computer to run it!

The component source code is as follows: (Debug pass)

public class MyDataGrid:System.Web.UI.WebControls.WebControl
{
private int currentpage; Current page
private int count; The number of record bars displayed per page
private int navigcount; Number of navigation connections
Private DataTable DT; Data source

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 (' You must enter a number that matches the page requirement, the maximum is: ' + max '); \ n" +
"Return false;\n" +
"}\n" +
"}\n" +
"</script>\n";

<summary>
Current page
</summary>
public int CurrentPage
{
Get
{
return currentpage;
}
Set
{
if (value <= 0)
CurrentPage = 1;
Else
CurrentPage = value;
}
}

<summary>
The number of record bars displayed per page
</summary>
public int Count
{
Get
{
return count;
}
Set
{
if (value <= 0)
Count = 10;
Else
Count = value;
}
}

<summary>
Number of navigation connections
</summary>
public int Navigcount
{
Get
{
return navigcount;
}
Set
{
if (value <= 0)
Navigcount = 10;
Else
Navigcount = value;
}
}

<summary>
Total pages
</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>
Data source
</summary>
Public DataTable DataSource
{
Get
{
return DT;
}
Set
{
if (value = = null)
throw new Exception ("Data source is not nullable");
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= ') ' bgcolor= '" #000000 ' style= ' Font-size:9pt ' >\n ' +
"<tr bgcolor= ' #FFFFFF ' >\n" + "<td width= ' 724 ' height= '" valign= ' "Top ' >{0}</td>\n" + "</tr>\n" +
"<tr bgcolor= ' #FFFFFF ' >\n" + "<td width= ' 724 ' height= '" valign= ' top ' >{1}</td>\n ' + "</tr>\n" + "</table>\n", table.tostring (), pagecontrol.tostring ());

Output. Write (Result.tostring ());
}

<summary>
Creating data Tables
</summary>
<returns> HTML representation string for table </returns>
Protected string createdatatable ()
{
string table = null; Table that shows all the fields and records
string tablehead = null; The header is used to display the field name <tr>
string tdhead = null; Header used to display field names <td> included in Tablehead
string tablebody = null; The table body is used to display the <tr> of the record

To implement a paging definition of min and max two variables
The Min representative starts from that record.
Max represents the end of the record.
If the current is the 2nd page display 10 records each page, then min's value is the 10,max value is 20
int min = 0;
int max = 0;

The For loop is used to generate the header, which is the field name
for (int i = 0; i < This.dt.Columns.Count; i++)
{
Tdhead = Tdhead + "<td>" + this.dt.columns[i]. ColumnName + "</td>";
}

Determines whether the current page is the last page
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;
}

The For loop is used to produce the table body, which is the fetch record
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>
To create a paging control
</summary>
<returns> returns the HTML representation string for the paging control </returns>
Protected string Createpagecontrol ()
{
String leftinfo = String. Format ("page: {0}/{1}" + "+" per page {2} "+" + "total {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;
A-A-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} >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; ' > \ <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);
}
}
}

Test Engineering Code:

public class TestMyDataGrid:System.Web.UI.Page
{
protected Mycontrollibrary.mydatagrid MyDataGrid1;

private void Page_Load (object sender, System.EventArgs e)
{
Place user code here to initialize page
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: This call is required for the ASP.net Web forms Designer.
//
InitializeComponent ();
Base. OnInit (e);
}

<summary>
Designer supports required methods-do not use the Code editor to modify
The contents of this method.
</summary>
private void InitializeComponent ()
{
This. Load + = new System.EventHandler (this. Page_Load);

}
#endregion
}


Page version of the row is not good, had to work you, hehe!



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.