1. GridView控件
1.1 在不使用數據源控件時(shí),GridView控件的排序和分頁(yè)
1.2 如何顯示空的GridView控件?
1.3 GridView的大小溢出
1.4 在GridView控件中使用CheckBox控件
1.5 綁定自定義頁(yè)面模板
1.6 如何訪(fǎng)問(wèn)頁(yè)碼按鈕,并改變其樣式?
1.7 如何導出GridView到Excel文件?
1.8 如何在e-mail信息中發(fā)送GridView數據?
2. DataList控件
2.1 水平地呈現數據
2.2 DataList控件的分頁(yè)
3. DetailsView控件
3.1 主/詳細場(chǎng)景
4. 常見(jiàn)問(wèn)題
4.1 如何在數據呈現控件中動(dòng)態(tài)創(chuàng )建列?
4.2 連接字符串的設置
4.3 如何在GridView或DataGrid中顯示固定寬度的列?
4.4 何時(shí)使用GridView/DataGrid/DataList/Repeater控件?
1. GridView控件
1.1在不使用數據源控件時(shí),GridView控件的排序和分頁(yè)
有時(shí)你想在不使用數據源控件如SqlDataSource或ObjectDataSource 控件的情況下綁定GridView控件到數據,這意味著(zhù)排序和分頁(yè)將不會(huì )借助數據源控件被自動(dòng)處理,為了實(shí)現排序和分頁(yè),你必須要處理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控件?
當GridView中沒(méi)有數據要顯示時(shí),默認情況控件將不被顯示。如果你想即便在沒(méi)有數據時(shí)也顯示標題行,你可以創(chuàng )建一個(gè)臨時(shí)的包含空記錄的DataTable對象,接著(zhù)在頁(yè)面的Init事件中綁定該GridView控件到這個(gè)DataTable。下例說(shuō)明了如何去做。
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繼承并重寫(xiě)CreateChildControls方法,該方法能自動(dòng)利用現有列布局,并移除使用外在DataTable對象的需求。下例說(shuō)明了如何去做。
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控件試圖顯示超過(guò)頁(yè)面可提供空間的列或行時(shí),這將引起GridView控件溢出并改變整個(gè)頁(yè)面的外觀(guān),你可以通過(guò)添加水平或垂直滾動(dòng)條到該控件去解決這個(gè)問(wèn)題,如下例所示:
<div style="vertical-align:top; height:200px; width:100%; overflow:auto;">
1.4 在Gridview控件中使用CheckBox控件
在基于web的e-mail客戶(hù)端,如Hotmail 或 Yahoo,一個(gè)包含check boxes的列可用于選擇單個(gè)e-mail信息,當前Gridview控件并沒(méi)有提供對此的內置支持,但你自己可以實(shí)現它。關(guān)于如何擴展Gridview控件去實(shí)現check boxes的例子,請參見(jiàn)此論壇:http://msdn.microsoft.com/en-us/magazine/cc163612.ASPx。
1.5 綁定自定義頁(yè)面模板
要在頁(yè)腳顯示如總頁(yè)數的信息,你可以用<PagerTemplate>項,如下例所示:
<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 如何訪(fǎng)問(wèn)頁(yè)碼按鈕,并改變其樣式?
要自定義選中的頁(yè)碼,使其有更大的字體或不同的顏色,需處理GridView控件的RowDataBound事件,并編程性地應用格式。接下來(lái)的例子演示了如何去做。
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 如何導出gridview到Excel文件?
如何導出Gridview數據到Excel文件,請遵循這些步驟:
1. 在包含GridView的頁(yè)面中,重寫(xiě)VerifyRenderingInServerForm方法。這讓你編程地呈現GridView控件而不用呈現完整的頁(yè)面。這個(gè)方法的默認執行阻止你單獨的呈現GridView控件。
2. 確保GridView控件位于包含runat="server"屬性的form元素中。
下面的例子演示了為了呈現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數據?
你可以作為e-mail信息的一部分發(fā)送顯示在Gridview中的數據。這種技術(shù)類(lèi)似于你如何輸出Gridview數據到Excel文件(你從Gridview控件得到展現標記,并添加到e-mail消息中)。確保e-mail消息是HTML格式。下面例子演示了如何去做(這個(gè)例子假設應用程序已經(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 水平地呈現數據
Gridview控件一行接一行地顯示數據,這意味著(zhù)布局是垂直的。要以其它的布局呈現數據,Datalist控件是個(gè)好的選擇。例如,他可以通過(guò)設置RepeatDirection="Horizontal"水平地顯示數據。你同樣可以使用Repeatcolumns屬性去控制在每一行顯示多少列。
2.2 DataList控件的分頁(yè)
不同于Gridview控件,Datalist控件沒(méi)有自動(dòng)分頁(yè)支持。要支持分頁(yè)功能,你必須添加代碼,如下例所示:
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主/詳細情況
如果你想在Griview控件中顯示所有記錄,并且希望能夠顯示一條記錄的細則。你需要使用另一個(gè)顯示控件。一種方發(fā)是在Gridview控件中添加一個(gè)Select按鈕列去顯示選擇的數據記錄,你通常為此使用Detailsview控件。更多信息,參見(jiàn)ASP.NET 網(wǎng)站上的Master-Details。
4. 常見(jiàn)問(wèn)題
4.1 如何在數據呈現控件中動(dòng)態(tài)創(chuà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 連接字符串的設置
你可以在Web.config文件中或在代碼中配置連接字符串,更多信息參見(jiàn)ASP.NET網(wǎng)站Connection Strings Configuration。
4.3 如何在GridView或DataGrid中顯示固定寬度的列?
默認情況下,Gridview和Datagrid控件依據它們的內容自動(dòng)調整列大小。要為列指定固定寬度,設置每個(gè)Tablecell對象的Width屬性并設置Wrap屬性為False。下面的例子顯示了如何通過(guò)使用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)于應該使用哪一個(gè)數據呈現控件的信息,參見(jiàn)MSDN網(wǎng)站上的Deciding when to use the DataGrid, DataList, or Repeater。
聯(lián)系客服