1. GridView控件
1.1 在不使用數(shù)據(jù)源控件時(shí),GridView控件的排序和分頁
1.2 如何顯示空的GridView控件?
1.3 GridView的大小溢出
1.4 在GridView控件中使用CheckBox控件
1.5 綁定自定義頁面模板
1.6 如何訪問頁碼按鈕,并改變其樣式?
1.7 如何導(dǎo)出GridView到Excel文件?
1.8 如何在e-mail信息中發(fā)送GridView數(shù)據(jù)?
2. DataList控件
2.1 水平地呈現(xiàn)數(shù)據(jù)
2.2 DataList控件的分頁
3. DetailsView控件
3.1 主/詳細(xì)場(chǎng)景
4. 常見問題
4.1 如何在數(shù)據(jù)呈現(xiàn)控件中動(dòng)態(tài)創(chuàng)建列?
4.2 連接字符串的設(shè)置
4.3 如何在GridView或DataGrid中顯示固定寬度的列?
4.4 何時(shí)使用GridView/DataGrid/DataList/Repeater控件?
1. GridView控件
1.1在不使用數(shù)據(jù)源控件時(shí),GridView控件的排序和分頁
有時(shí)你想在不使用數(shù)據(jù)源控件如SqlDataSource或ObjectDataSource 控件的情況下綁定GridView控件到數(shù)據(jù),這意味著排序和分頁將不會(huì)借助數(shù)據(jù)源控件被自動(dòng)處理,為了實(shí)現(xiàn)排序和分頁,你必須要處理GridView 控件的PageIndexChanging 和 Sorting事件,如下例所示:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.DataSource = SortDataTable(GetYourDataSource(), true);
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
private string GridViewSortDirection
{
get { return ViewState["SortDirection"] as string "ASC"; }
set { ViewState["SortDirection"] = value; }
}
private string GridViewSortExpression
{
get { return ViewState["SortExpression"] as string string.Empty; }
set { ViewState["SortExpression"] = value; }
}
private string ToggleSortDirection()
{
switch (GridViewSortDirection)
{
case "ASC":
GridViewSortDirection = "DESC";
break;
case "DESC":
GridViewSortDirection = "ASC";
break;
}
return GridViewSortDirection;
}
protected DataView SortDataTable(DataTable dataTable, bool isPageIndexChanging)
{
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
if (GridViewSortExpression != string.Empty)
{
if (isPageIndexChanging)
{
dataView.Sort = string.Format("{0} {1}", GridViewSortExpression,GridViewSortDirection);
}
else
{
dataView.Sort = string.Format("{0} {1}", GridViewSortExpression,ToggleSortDirection());
}
}
return dataView;
}
else
{
return new DataView();
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
GridViewSortExpression = e.SortExpression;
int pageIndex = GridView1.PageIndex;
GridView1.DataSource = SortDataTable(GetYourDataSource(), false);
GridView1.PageIndex = pageIndex;
GridView1.DataBind();
}
1.2 如何顯示空的GridView控件?
當(dāng)GridView中沒有數(shù)據(jù)要顯示時(shí),默認(rèn)情況控件將不被顯示。如果你想即便在沒有數(shù)據(jù)時(shí)也顯示標(biāo)題行,你可以創(chuàng)建一個(gè)臨時(shí)的包含空記錄的DataTable對(duì)象,接著在頁面的Init事件中綁定該GridView控件到這個(gè)DataTable。下例說明了如何去做。
protected void GridView1_Init(Object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Column1");
dt.Columns.Add("Column2");
DataRow dr = dt.NewRow();
dr["Column1"] = "";
dr["Column2"] = "";
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
}
另一種解決方法是從GridView繼承并重寫CreateChildControls方法,該方法能自動(dòng)利用現(xiàn)有列布局,并移除使用外在DataTable對(duì)象的需求。下例說明了如何去做。
public class EmptyGridView : GridView
{
#region Properties
/// <summary>
/// Enable or Disable generating an empty table if no data rows in source
/// </summary>
[
Description("Enable or disable generating an empty table with headers
when no data rows are available in the data source."),
Category("Misc"),
DefaultValue("true"),
]
public bool ShowEmptyTable
{
get
{
object o = ViewState["ShowEmptyTable"];
return (o != null (bool)o : true);
}
set
{
ViewState["ShowEmptyTable"] = value;
}
}
/// <summary>
/// Get or Set Text to display in empty data row
/// </summary>
[
Description("Text to display in the empty data row."),
Category("Misc"),
DefaultValue(""),
]
public string EmptyTableRowText
{
get
{
object o = ViewState["EmptyTableRowText"];
return (o != null o.ToString() : "");
}
set
{
ViewState["EmptyTableRowText"] = value;
}
}
#endregion
protected override int CreateChildControls(System.Collections.IEnumerable
dataSource, bool dataBinding)
{
int numRows = base.CreateChildControls(dataSource, dataBinding);
// No data rows created, so create an empty table if enabled.
if (numRows == 0 && ShowEmptyTable)
{
//create table
Table table = new Table();
table.ID = this.ID;
//create a new header row
GridViewRow row = base.CreateRow(-1, -1, DataControlRowType.Header,
DataControlRowState.Normal);
//convert the exisiting columns into an array and initialize
DataControlField[] fields = new
DataControlField[this.Columns.Count];
this.Columns.CopyTo(fields, 0);
this.InitializeRow(row, fields);
table.Rows.Add(row);
//create the empty row
row = new GridViewRow(-1, -1, DataControlRowType.DataRow,
DataControlRowState.Normal);
TableCell cell = new TableCell();
cell.ColumnSpan = this.Columns.Count;
cell.Width = Unit.Percentage(100);
cell.Controls.Add(new LiteralControl(EmptyTableRowText));
row.Cells.Add(cell);
table.Rows.Add(row);
this.Controls.Add(table);
}
return numRows;
}
}
1.3 GridView的大小溢出
如果GridView控件試圖顯示超過頁面可提供空間的列或行時(shí),這將引起GridView控件溢出并改變整個(gè)頁面的外觀,你可以通過添加水平或垂直滾動(dòng)條到該控件去解決這個(gè)問題,如下例所示:
<div style="vertical-align:top; height:200px; width:100%; overflow:auto;">
1.4 在Gridview控件中使用CheckBox控件
在基于web的e-mail客戶端,如Hotmail 或 Yahoo,一個(gè)包含check boxes的列可用于選擇單個(gè)e-mail信息,當(dāng)前Gridview控件并沒有提供對(duì)此的內(nèi)置支持,但你自己可以實(shí)現(xiàn)它。關(guān)于如何擴(kuò)展Gridview控件去實(shí)現(xiàn)check boxes的例子,請(qǐng)參見此論壇:http://msdn.microsoft.com/en-us/magazine/cc163612.ASPx。
1.5 綁定自定義頁面模板
要在頁腳顯示如總頁數(shù)的信息,你可以用<PagerTemplate>項(xiàng),如下例所示:
<ASP:GridView ID="GridView1" runat="server"
DataSourceID="SqlDataSource1"
DataKeyNames="ID"
AllowPaging="true"
PageSize="10"
AutoGenerateColumns="true">
<PagerTemplate>
<asp:Label ID="LabelCurrentPage" runat="server"
Text="<%# ((GridView)Container.NamingContainer).PageIndex + 1 %>">
</asp:Label>/
<asp:Label ID="LabelPageCount" runat="server"
Text="<%# ((GridView)Container.NamingContainer).PageCount %>">
</asp:Label>
<asp:LinkButton ID="LinkButtonFirstPage" runat="server"
CommandArgument="First"
CommandName="Page"
enabled="<%# ((GridView)Container.NamingContainer).PageIndex != 0
%>"><<
asp:LinkButton ID="LinkButtonPreviousPage" runat="server"
CommandArgument="Prev" CommandName="Page"
enabled="<%# ((GridView)Container.NamingContainer).PageIndex != 0 %>"><
</asp:LinkButton>
<asp:LinkButton ID="LinkButtonNextPage" runat="server"
CommandArgument="Next"
CommandName="Page"
enabled="<%# ((GridView)Container.NamingContainer).PageIndex !=
((GridView)Container.NamingContainer).PageCount - 1 %>">>
</asp:LinkButton>
<asp:LinkButton ID="LinkButtonLastPage" runat="server"
CommandArgument="Last"
CommandName="Page"
enabled="<%# ((GridView)Container.NamingContainer).PageIndex !=
((GridView)Container.NamingContainer).PageCount - 1 %>">>>
</asp:LinkButton>
</PagerTemplate>
</asp:GridView>
1.6 如何訪問頁碼按鈕,并改變其樣式?
要自定義選中的頁碼,使其有更大的字體或不同的顏色,需處理GridView控件的RowDataBound事件,并編程性地應(yīng)用格式。接下來的例子演示了如何去做。
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
TableRow row = e.Row.Controls[0].Controls[0].Controls[0] as TableRow;
foreach (TableCell cell in row.Cells)
{
Control lb = cell.Controls[0] ;
if (lb is Label)
{
((Label)lb).ForeColor = System.Drawing.Color.Red;
((Label)lb).Font.Size = new FontUnit("40px");
}
else if (lb is LinkButton)
{
//Here is for changing the rest LinkButton page number.
}
}
}
}
1.7 如何導(dǎo)出gridview到Excel文件?
如何導(dǎo)出Gridview數(shù)據(jù)到Excel文件,請(qǐng)遵循這些步驟:
1. 在包含GridView的頁面中,重寫VerifyRenderingInServerForm方法。這讓你編程地呈現(xiàn)GridView控件而不用呈現(xiàn)完整的頁面。這個(gè)方法的默認(rèn)執(zhí)行阻止你單獨(dú)的呈現(xiàn)GridView控件。
2. 確保GridView控件位于包含runat="server"屬性的form元素中。
下面的例子演示了為了呈現(xiàn)GridView 控件為Excel電子表格的必須代碼。
protected void Button1_Click(object sender, System.EventArgs e)
{
// Clear the response.
Response.Clear();
// Set the type and file.name.
Response.AddHeader("content-disposition",
"attachment;filename=FileName.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
// Add the HTML from the GridView control to a StringWriter instance so you
// can write it out later.
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
// Write the data.
Response.Write(sw.ToString);
Response.End();
}
pupublic override void VerifyRenderingInServerForm(Control control)
{
}
1.8 如何在e-mail信息中發(fā)送Gridview數(shù)據(jù)?
你可以作為e-mail信息的一部分發(fā)送顯示在Gridview中的數(shù)據(jù)。這種技術(shù)類似于你如何輸出Gridview數(shù)據(jù)到Excel文件(你從Gridview控件得到展現(xiàn)標(biāo)記,并添加到e-mail消息中)。確保e-mail消息是HTML格式。下面例子演示了如何去做(這個(gè)例子假設(shè)應(yīng)用程序已經(jīng)被配置為發(fā)送e-mail)。
using System.IO;
using System.Text;
using System.Net.Mail;
private string GridViewToHtml(GridView gv)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(sw);
gv.RenderControl(hw);
return sb.ToString();
}
protected void SendMailButton_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
mail.Body = GridViewToHtml(GridView1);
mail.IsBodyHtml = true;
// ...
}
public override void VerifyRenderingInServerForm(Control control)
{
}
2. DataList 控件
2.1 水平地呈現(xiàn)數(shù)據(jù)
Gridview控件一行接一行地顯示數(shù)據(jù),這意味著布局是垂直的。要以其它的布局呈現(xiàn)數(shù)據(jù),Datalist控件是個(gè)好的選擇。例如,他可以通過設(shè)置RepeatDirection="Horizontal"水平地顯示數(shù)據(jù)。你同樣可以使用Repeatcolumns屬性去控制在每一行顯示多少列。
2.2 DataList控件的分頁
不同于Gridview控件,Datalist控件沒有自動(dòng)分頁支持。要支持分頁功能,你必須添加代碼,如下例所示:
int PageSize, RecordCount, PageCount, CurrentPage;
SqlConnection MyConn;
public int IndexOfPage
{
get { return (int)ViewState["_IndexOfPage"]; }
set { ViewState["_IndexOfPage "] = value; }
}
public int CountOfPage
{
get { return (int)ViewState["_CountOfPage"]; }
set { ViewState["_CountOfPage"] = value; }
}
public void Page_Load(Object src, EventArgs e)
{
PageSize = 3;
string MyConnString =
@"Server=(local)\SQLEXPRESS;Integrated Security=SSPI;Database=test;Persist Security Info=True";
MyConn = new SqlConnection(MyConnString);
MyConn.Open();
if (!Page.IsPostBack)
{
ListBind();
CurrentPage = 0;
IndexOfPage = 0;
RecordCount = CalculateRecord();
lblRecordCount.Text = RecordCount.ToString();
PageCount = RecordCount / PageSize;
lblPageCount.Text = PageCount.ToString();
CountOfPage = PageCount;
}
}
public int CalculateRecord()
{
int intCount;
string strCount = "select count(*) as co from student";
SqlCommand MyComm = new SqlCommand(strCount, MyConn);
SqlDataReader dr = MyComm.ExecuteReader();
if (dr.Read())
{
intCount = Int32.Parse(dr["co"].ToString());
}
else
{
intCount = 0;
}
dr.Close();
return intCount;
}
ICollection CreateSource()
{
int StartIndex;
StartIndex = CurrentPage * PageSize;
string strSel = "select * from student";
DataSet ds = new DataSet();
SqlDataAdapter MyAdapter = new SqlDataAdapter(strSel, MyConn);
MyAdapter.Fill(ds, StartIndex, PageSize, "Score");
return ds.Tables["Score"].DefaultView;
}
public void ListBind()
{
DataList1.DataSource = CreateSource();
DataList1.DataBind();
lbnNextPage.Enabled = true;
lbnPrevPage.Enabled = true;
if (CurrentPage == (PageCount - 1)) lbnNextPage.Enabled = false;
if (CurrentPage == 0) lbnPrevPage.Enabled = false;
lblCurrentPage.Text = (CurrentPage + 1).ToString();
}
public void Page_OnClick(Object sender, CommandEventArgs e)
{
CurrentPage = (int)IndexOfPage;
PageCount = (int)CountOfPage;
string cmd = e.CommandName;
switch (cmd)
{
case "next":
if (CurrentPage < (PageCount - 1)) CurrentPage++;
break;
case "prev":
if (CurrentPage > 0) CurrentPage--;
break;
}
IndexPage = CurrentPage;
ListBind();
}
3. DetailsView 控件
3.1主/詳細(xì)情況
如果你想在Griview控件中顯示所有記錄,并且希望能夠顯示一條記錄的細(xì)則。你需要使用另一個(gè)顯示控件。一種方發(fā)是在Gridview控件中添加一個(gè)Select按鈕列去顯示選擇的數(shù)據(jù)記錄,你通常為此使用Detailsview控件。更多信息,參見ASP.NET 網(wǎng)站上的Master-Details。
4. 常見問題
4.1 如何在數(shù)據(jù)呈現(xiàn)控件中動(dòng)態(tài)創(chuàng)建列?
當(dāng)你不確定你應(yīng)該添加多少列到Gridview控件時(shí),你可以使用自定義模板控件動(dòng)態(tài)創(chuàng)建列,如下例所示:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TemplateField customField1 = new TemplateField();
customField1.ShowHeader = true;
customField1.HeaderTemplate =
new GridViewTemplate(DataControlRowType.Header, "ID", "");
customField1.ItemTemplate =
new GridViewTemplate(DataControlRowType.DataRow, "", "Contract");
GridView1.Columns.Add(customField1);
GridView1.DataSource = GetDataSource();
GridView1.DataBind();
}
}
public class GridViewTemplate : ITemplate
{
private DataControlRowType templateType;
private string columnName;
private string columnNameBinding;
public GridViewTemplate(DataControlRowType type, string colname,
string colNameBinding)
{
templateType = type;
columnName = colname;
columnNameBinding = colNameBinding;
}
public void InstantiateIn( System.Web.UI.Control container )
{
switch (templateType)
{
case DataControlRowType.Header:
Literal lc = new Literal();
lc.Text = columnName;
container.Controls.Add(lc);
break;
case DataControlRowType.DataRow:
CheckBox cb = new CheckBox();
cb.ID = "cb1";
cb.DataBinding += new EventHandler(this.cb_OnDataBinding);
container.Controls.Add(cb);
break;
default:
break;
}
}
public void cb_OnDataBinding(object sender, EventArgs e)
{
CheckBox cb = (CheckBox)sender;
GridViewRow container = (GridViewRow)cb.NamingContainer;
cb.Checked = Convert.ToBoolean(
((DataRowView)container.DataItem)[columnNameBinding].ToString());
}
}
4.2 連接字符串的設(shè)置
你可以在Web.config文件中或在代碼中配置連接字符串,更多信息參見ASP.NET網(wǎng)站Connection Strings Configuration。
4.3 如何在GridView或DataGrid中顯示固定寬度的列?
默認(rèn)情況下,Gridview和Datagrid控件依據(jù)它們的內(nèi)容自動(dòng)調(diào)整列大小。要為列指定固定寬度,設(shè)置每個(gè)Tablecell對(duì)象的Width屬性并設(shè)置Wrap屬性為False。下面的例子顯示了如何通過使用DataGrid控件去做。
protected void DataGrid1_ItemCreated(object sender, DataGridItemEventArgs e)
{
ListItemType lit = e.Item.ItemType;
if (lit == ListItemType.Header)
{
for (int i = 0; i < e.Item.Cells.Count; i++)
{
e.Item.Cells[i].Width = Unit.Pixel(50);
e.Item.Cells[i].Wrap = false;
}
}
}
4.4 何時(shí)使用GridView/DataGrid/DataList/Repeater控件?
關(guān)于應(yīng)該使用哪一個(gè)數(shù)據(jù)呈現(xiàn)控件的信息,參見MSDN網(wǎng)站上的Deciding when to use the DataGrid, DataList, or Repeater。
聯(lián)系客服