/// DataGrid相鄰行有相同內容時對指定列合併
/// </summary>
/// <param name="spangrid">格式化的DataGrid的ID</param>
/// <param name="spancell">要合併的列</param>
/// <param name="spanby">合併所依據數據的列</param>
public void FormatGrid(DataGrid spangrid,int spancell,int spanby)
{
if(spanby<0 || spanby>spangrid.Items.Count)
return;
int rowspan = 1;
for(int i = 1;i<spangrid.Items.Count;i++)
{
if(spangrid.Items[i].Cells[spanby].Text == spangrid.Items[i-1].Cells[spanby].Text)
{
rowspan +=1;
spangrid.Items[i].Cells[spancell].Visible = false;
spangrid.Items[i-rowspan+1].Cells[spancell].RowSpan = rowspan;
}
else
{
string str = spangrid.Items[i].Cells[spanby].Text;
string str1 = spangrid.Items[i-1].Cells[spanby].Text;
rowspan = 1;
}
}
}
datagrid加checkbox實現分頁不丟失選擇的記錄
{
/**//// <summary>
/// WebForm1 的摘要說明。
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.WebControls.DataGrid DataGrid1;
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
show();
}
}
private void show()
{
string conn = ConfigurationSettings.AppSettings.Get("Connstring");
DataSet ds = new DataSet();
using( SqlConnection con = new SqlConnection(conn))
{
con.Open();
SqlCommand comm = new SqlCommand();
SqlDataAdapter da =new SqlDataAdapter();
da.SelectCommand = new SqlCommand();
da.SelectCommand.Connection = con;
da.SelectCommand.CommandText = "select * from Orders";
da.SelectCommand.CommandType = CommandType.Text;
da.Fill(ds);
}
this.DataGrid1.DataSource = ds.Tables[0];
this.DataGrid1.DataBind();
if(Session["userlist"]!=null)
{
Hashtable ht =(Hashtable) Session["userlist"];
if(ht!=null)
{
for(int i = 0 ;i<DataGrid1.Items.Count ;i++)
{
if (ht.ContainsKey(DataGrid1.Items[i].Cells[0].Text.ToString().Trim()))
(DataGrid1.Items[i].Cells[2].FindControl("CheckBox1") as CheckBox).Checked = true;
}
}
}
}
private void check()
{
Hashtable ht = new Hashtable();
if(Session["userlist"]!=null)
{
ht =(Hashtable) Session["userlist"];
if(ht!=null)
{
for(int i = 0 ;i<DataGrid1.Items.Count ;i++)
{
if ( (DataGrid1.Items[i].Cells[2].FindControl("CheckBox1") as CheckBox).Checked)
{
if (! ht.ContainsKey(DataGrid1.Items[i].Cells[0].Text.ToString().Trim()))
{
ht.Add(DataGrid1.Items[i].Cells[0].Text.ToString().Trim(),DataGrid1.Items[i].Cells[1].Text.ToString().Trim());
}
}
else
{
if ( ht.ContainsKey(DataGrid1.Items[i].Cells[0].Text.ToString().Trim()))
{
ht.Remove(DataGrid1.Items[i].Cells[0].Text.ToString().Trim());
}
}
}
}
}
else
{
for(int i = 0 ;i<DataGrid1.Items.Count ;i++)
{
if ( (DataGrid1.Items[i].Cells[2].FindControl("CheckBox1") as CheckBox).Checked)
{
ht.Add(DataGrid1.Items[i].Cells[0].Text.ToString().Trim(),DataGrid1.Items[i].Cells[1].Text.ToString().Trim());
}
}
}
Session["userlist"] = ht;
}
Web 窗體設計器生成的代碼#region Web 窗體設計器生成的代碼
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 該調用是 ASP.NET Web 窗體設計器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/**//// <summary>
/// 設計器支持所需的方法 - 不要使用代碼編輯器修改
/// 此方法的內容。
/// </summary>
private void InitializeComponent()
{
this.DataGrid1.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.DataGrid1_PageIndexChanged);
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void DataGrid1_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
check();
DataGrid1.CurrentPageIndex = e.NewPageIndex;
show();
}
private void Button1_Click(object sender, System.EventArgs e)
{
check();
Hashtable ht = (Hashtable)Session["userlist"];
foreach (DictionaryEntry objDE in ht)
{
Response.Write(objDE.Value.ToString());
}
}
}
}
DataGrid中添加刪除確認對話框 多種實現
方法一:
當爲DataGrid控件添加刪除按紐後,爲DataGrid控件添加ItemDataBound事件處理程序,代碼如下:
//添加刪除確認對話框。
switch(e.Item.ItemType)
{
case ListItemType.Item:
case ListItemType.EditItem:
case ListItemType.AlternatingItem:
((LinkButton)e.Item.Cells[4].Controls[0]).Attributes.Add("onclick","return confirm('你真的要刪除第"+(e.Item.ItemIndex+1).ToString()+"行嗎?');");
break;
}
其中,e.Item.Cells[4]說明你添加的刪除按紐在DataGrid控件中位於第五列,列號從0開始。
方法二:使用模板列
1.爲DataGrid添加一個模板列,名爲“自定義刪除”,在這個模板列中添加一個按紐,將按紐的CommandName屬性設爲UserDelete;
2.爲DataGrid添加ItemCreated事件,添加客戶端腳本程序,代碼如下:
switch(e.Item.ItemType)
{
case ListItemType.Item:
case ListItemType.EditItem:
case ListItemType.AlternatingItem:
Button myDelButton = (Button)e.Item.FindControl("btnDelete");
myDelButton.Attributes.Add("onclick","return confirm('你真的要刪除第"+(e.Item.ItemIndex+1).ToString()+"行嗎?');");
break;
}
3.爲DataGrid添加ItemCommand事件,處理刪除事件,代碼如下:
if(e.CommandName == "UserDelete")
{
//執行刪除。
}
方法三:
這種方法很少見到人用,但卻是最簡單的方法,方法如下:
將DataGrid的刪除按紐的文本屬性設爲如下代碼:
<div id=d onclick="JavaScript:return confirm('你真的要刪除這一行嗎?');">刪除</div>
使用RenderMethod 委託實現DataGrid表頭合併
2using System.Collections;
3using System.ComponentModel;
4using System.Data;
5using System.Drawing;
6using System.Web;
7using System.Web.SessionState;
8using System.Web.UI;
9using System.Web.UI.WebControls;
10using System.Web.UI.HtmlControls;
11using System.Data.SqlClient;
12
13namespace WebDataGridHeader
14{
15 /**//**//**//// <summary>
16 /**////DataGrid表頭合併問題
17 /**//// </summary>
18 public class WebForm1 : System.Web.UI.Page
19 {
20 protected System.Web.UI.WebControls.DataGrid DataGrid1;
21 protected System.Web.UI.WebControls.Label Label1;
22
23 private void Page_Load(object sender, System.EventArgs e)
24 {
25 // 在此處放置用戶代碼以初始化頁面
26 string m_strConn = "server=.;uid=sa;pwd=sa;database=Northwind";
27 SqlConnection conn = new SqlConnection(m_strConn);
28
29 try
30 {
31 conn.Open();
32
33 SqlCommand cmd = new SqlCommand("SELECT * FROM Employees",conn);
34
35 SqlDataAdapter adp = new SqlDataAdapter(cmd);
36
37 DataTable dt = new DataTable();
38 adp.Fill(dt);
39
40 this.DataGrid1.DataSource = dt;
41 this.DataGrid1.DataBind();
42 }
43 catch(Exception ex)
44 {
45 throw ex;
46 }
47 finally
48 {
49 conn.Close();
50 }
51 }
52
53 Web 窗體設計器生成的代碼Web 窗體設計器生成的代碼#region Web 窗體設計器生成的代碼
54 override protected void OnInit(EventArgs e)
55 {
56 //
57 // CODEGEN: 該調用是 ASP.NET Web 窗體設計器所必需的。
58 //
59 InitializeComponent();
60 base.OnInit(e);
61 }
62
63 /**//**//**//// <summary>
64 /**//// 設計器支持所需的方法 - 不要使用代碼編輯器修改
65 /**//// 此方法的內容。
66 /**//// </summary>
67 private void InitializeComponent()
68 {
69 this.DataGrid1.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemCreated);
70 this.Load += new System.EventHandler(this.Page_Load);
71
72 }
73 #endregion
74
75 /**//**//**//// <summary>
76 /**//// 創建Item
77 /**//// </summary>
78 /**//// <param name="sender"></param>
79 /**//// <param name="e"></param>
80 private void DataGrid1_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
81 {
82 //將Item的呈現方法定向到自定義的呈現方法上
83 ListItemType lit = e.Item.ItemType;
84 if(ListItemType.Header == lit)
85 {
86 e.Item.SetRenderMethodDelegate(new RenderMethod(NewRenderMethod));
87 }
88 }
89
90 /**//**//**//// <summary>
91 /**//// 自定義的Item呈現方法
92 /**//// </summary>
93 /**//// <param name="writer"></param>
94 /**//// <param name="ctl"></param>
95 private void NewRenderMethod(HtmlTextWriter writer,Control ctl)
96 {
97 //不需要從<TR>標籤開始
98 //輸出“聯繫電話”列
99 writer.Write("<TD colspan=/"3/" align=/"center/">聯繫電話</TD>/n");
100
101 //“地址”列必須有rowspan屬性且必須在第一列呈現
102 TableCell cell = (TableCell)ctl.Controls[ctl.Controls.Count - 1];
103 cell.Attributes.Add("rowspan","2");
104 cell.RenderControl(writer);
105
106 //現在關閉第一行
107 writer.Write("</TR>/n");
108
109 //將設計時的樣式屬性添加到第二行使得兩行的外觀相似
110 this.DataGrid1.HeaderStyle.AddAttributesToRender(writer);
111
112 //插入第二行
113 writer.RenderBeginTag("TR");
114
115 //呈現除了最後一列(剛纔已經呈現過了)外的所有在設計時定義的cells
116 for(int i=0;i<=ctl.Controls.Count-2;i++)
117 {
118 ctl.Controls[i].RenderControl(writer);
119 }
120
121 //不需要以</TR>結束
122 }
123 }
124}
代碼如下:
<asp:DataGrid id="DataGrid1" runat="server" Width="793px" Height="296px" AutoGenerateColumns="False"
BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" BackColor="White" CellPadding="4">
<SelectedItemStyle Font-Bold="True" ForeColor="#663399" BackColor="#FFCC66"></SelectedItemStyle>
<ItemStyle ForeColor="#330099" BackColor="White"></ItemStyle>
<HeaderStyle Font-Bold="True" ForeColor="#FFFFCC" BackColor="#990000"></HeaderStyle>
<FooterStyle ForeColor="#330099" BackColor="#FFFFCC"></FooterStyle>
<Columns>
<asp:BoundColumn DataField="LastName" HeaderText="辦公電話"></asp:BoundColumn>
<asp:BoundColumn DataField="FirstName" HeaderText="住宅電話"></asp:BoundColumn>
<asp:BoundColumn DataField="HomePhone" HeaderText="移動電話"></asp:BoundColumn>
<asp:BoundColumn DataField="Address" HeaderText="聯繫地址"></asp:BoundColumn>
</Columns>
<PagerStyle HorizontalAlign="Center" ForeColor="#330099" BackColor="#FFFFCC"></PagerStyle>
</asp:DataGrid>
1、CheckBox控件需要設置AutoPostBack="true"
<asp:CheckBox id="chbIsActive" runat="server" AutoPostBack="true"></asp:CheckBox>
2、CheckBox控件的事件須在DataGrid的ItemCreated定義才能生效
private void grdStructure_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
CheckBox chbIsActive = e.Item.FindControl("chbIsActive") as CheckBox;
chbIsActive.CheckedChanged += new EventHandler(chbIsActive_CheckedChanged);
}
}
3、編寫事件代碼
private void chbIsActive_CheckedChanged(object sender, EventArgs e)
{
CheckBox chbIsActive = (CheckBox)sender;
Guid structureUID = new Guid(chbIsActive.Attributes["StructureUID"]);
bool isActive = chbIsActive.Checked;
IPMStructureManager manager = PMStructureManagerFactory.GetInstance();
manager.SetActive(structureUID, isActive);
this.Binding();
}
在DataGrid中添加一個合計字段
http://www.asp.net/ 或 http://www.asplists.com/asplists/aspngevery.asp。最近的最常見的一個問題是:“ 我怎樣在 DataGrid 中顯示列合計?”。 我親自多次爲這個問題提供了示例代碼,因此,我想在DotNetJunkies 的標題中提供這麼一份指南。 在這份指南中你將會學到怎樣在 DataGrid 中編程實現對某一列的值進行統計,並在 DataGrid 的頁腳中顯示其合計值。這份指南中供下載的示例中包括了 C# 和 Visual Basic.NET 兩種代碼。
上面所用到的屏幕圖片中的 DataGrid 是一個非常典型的 DataGrid 。有許多控制 DataGrid 外觀的屬性,它使用兩個 BoundColumns 來操作數據,但這並不是最重要的。做好這項工作真正重要的是使用 DataGrid.OnItemDataBound 事件。這個事件將會觸發每次綁定一條記錄到 DataGrid。你可以爲這個事件創建一個事件處理,以操作數據記錄。在這種情況下,你將會得到運行時 Price 列的合計值。
頁腳指的是數據範圍的最後一行。當這行被限定時,在事件句處理你可以得到 Price 列的運行時統計值。
實施:
首先讓我們找到一種方法來操作 Web 窗體輸出。 這份指南中,你將使用一個 Web 窗體 (calcTotals.aspx) 以及一個類代碼文件 (calcTotals.aspx.cs)。這份指南的意圖是, 類代碼將會使用 Just-In-Time 編譯器來編譯。 這裏是 calcTotals.aspx 的代碼:
<%@ Page Inherits="myApp.calcTotals" Src="20010731T0101.aspx.cs" %>
<html>
<body bgcolor="white">
<asp:DataGrid id="MyGrid" runat="server"
AutoGenerateColumns="False"
CellPadding="4" CellSpacing="0"
BorderStyle="Solid" BorderWidth="1"
Gridlines="None" BorderColor="Black"
ItemStyle-Font-Name="Verdana"
ItemStyle-Font-Size="9pt"
HeaderStyle-Font-Name="Verdana"
HeaderStyle-Font-Size="10pt"
HeaderStyle-Font-Bold="True"
HeaderStyle-ForeColor="White"
HeaderStyle-BackColor="Blue"
FooterStyle-Font-Name="Verdana"
FooterStyle-Font-Size="10pt"
FooterStyle-Font-Bold="True"
FooterStyle-ForeColor="White"
FooterStyle-BackColor="Blue"
OnItemDataBound="MyDataGrid_ItemDataBound"
ShowFooter="True">
<Columns>
<asp:BoundColumn HeaderText="Title" DataField="title" />
<asp:BoundColumn HeaderText="Price" DataField="price"
ItemStyle-HorizontalAlign="Right"
HeaderStyle-HorizontalAlign="Center" />
</Columns>
</asp:DataGrid>
</body>
</html>
在 Web 窗體中你使用 @ Page 來直接聲明這個頁所繼承的類代碼。SRC 屬性指明瞭類代碼將使用 JIT 編譯器來編譯。 Web 窗體中的大部分代碼樣式聲明用來使 DataGrid 外觀變得更好看。
最後指定的屬性之一是 OnItemDataBound 屬性。這個事件將會在 OnItemDataBound 事件發生時被觸發。
Web 窗體中的 DataGrid (MyGrid) 包含有兩個 BoundColumns,一個是 Title ,另一個是Price。 這裏將顯示 Pubs 數據庫(SQL Server)中 Titles 表的 title 及 price 列。
忽略代碼的定義
類代碼在所有的地方都將使用。在類代碼中,你可以操作兩個事件:Page_Load 事件以及 MyGrid_OnItemDataBound 事件。還有一個私有方法 CalcTotal, 用它來簡單的完成運行時統計的數學運算。
類代碼基本結構塊的起始部分:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Data.SqlClient;
namespace myApp
{
public class calcTotals : Page
{
protected DataGrid MyGrid;
private double runningTotal = 0;
}
}
在類代碼的基本結構中,你必須使用相關語句導入名字空間(namespace)。在類聲明中,你聲明瞭兩個變量,一個是類代碼中映射 Web 窗體的 DataGrid(MyGrid)控件的變量;一個是用來操作 DataGrid 的 Price 列中運行時統計的雙精度值。
Page_Load 事件
在 Page_Load 事件中,你所要做的就是連接到 SQL Server 並執行一個簡單的 SqlCommand。 你取得了所有 Price 值>0 的 title 和 price 數據。你使用 SqlCommand.ExecuteReader 方法返回一個 SqlDataReader 並將其直接綁定到 DataGrid (MyGrid)。
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("server=Localhost;database=pubs;uid=sa;pwd=;");//創建SQL連接
SqlCommand myCommand = new SqlCommand("SELECT title, price FROM Titles WHERE price > 0", myConnection);//創建SQL命令
try
{
myConnection.Open();//打開數據庫連接
MyGrid.DataSource = myCommand.ExecuteReader();//指定 DataGrid 的數據源
MyGrid.DataBind();//綁定數據到 DataGrid
myConnection.Close();//關閉數據連接
}
catch(Exception ex)
{
//捕獲錯誤
HttpContext.Current.Response.Write(ex.ToString());
}
}
CalcTotals 方法
CalcTotals 方法用來處理 runningTotal 變量。這個值將以字符串形式來傳遞。 你需要將它解析爲雙精度型,然後 runningTotal 變量就成了雙精度類型。
private void CalcTotal(string _price)
{
try
{
runningTotal += Double.Parse(_price);
}
catch
{
//捕獲錯誤
}
}
MyGrid_ItemDataBound 事件
MyGrid_ItemDataBound 事件在數據源中每行綁定到 DataGrid 時被調用。在這個事件處理中,你可以處理每一行數據。 這裏你的目的是,你將需要調用 CalcTotals 方法並從 Price 列傳遞文本,並用金額型格式化每一行的 Price 列, 並在頁腳行中顯示 runningTotal 的值。
public void MyDataGrid_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
CalcTotal( e.Item.Cells[1].Text );
e.Item.Cells[1].Text = string.Format("{0:c}", Convert.ToDouble(e.Item.Cells[1].Text));
}
else if(e.Item.ItemType == ListItemType.Footer )
{
e.Item.Cells[0].Text="Total";
e.Item.Cells[1].Text = string.Format("{0:c}", runningTotal);
}
}
在 MyGrid_ItemDataBound 事件句柄中,首先你得使用 ListItemType 判斷當前的 DataGridItem 是一個數據項還是AlternatingItem 行。如果是數據項,你調用 CalcTotals,並將 Price 列的值作爲參數傳遞給它;然後你以金額格式對 Price 列進行格式化及着色。
如果 DataGridItem 是頁腳,可以用金額格式顯示 runningTotal。
總結
在這份指南中,你學到了怎樣使用 DataGrid.OnItemDataBound 事件來實現運行時對DataGrid 的某一列進行統計。使用這個事件,你可以創建一個列的合計並可對DataGrid行的頁腳進行着色。
使用DataGrid動態綁定DropDownList
//檢索數據庫的函數public DataSet GetZcbd()
{
try
{
DataSet ds=new DataSet();
string searchString="select id,yy,bj from zc";
da=new OleDbDataAdapter(searchString,conn);
da.Fill(ds,"yy");
return ds;
}
catch
{
return null;
}
}
//綁定DataGrid
private void BindGrid()
{
DataSet ds = new DataSet();
ds = us.GetZcbd();
if (ds!=null)
{
this.DataGrid1.DataSource = ds;
this.DataGrid1.DataBind();
}
else
{
msg.Alert("加載數據錯誤!",Page);
}
}
綁定好DataGrid以後,設定模板列,讓其正常顯示下爲Label,並綁定爲數據庫中一ID值,在編輯狀態下爲DropDownList,並綁定爲數據庫中一Name值,我們現在要做的就是當我們選擇編輯時根據Label的值自動從數據庫中取出編號爲ID值的姓名,並用DropDownList默認選中。(註釋:爲了方便大家學習,我給出一個簡單代碼的例子,供大家參考)
private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.EditItem)
{
DataRowView drv = (DataRowView)e.Item.DataItem;
string current = drv["label1"].ToString();
DropDownList ddl = (DropDownList)e.Item.FindControl("ddl");
ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue(current));
}
if ((e.Item.ItemType == ListItemType.Item)||(e.Item.ItemType == ListItemType.AlternatingItem))
{
Label t = (System.Web.UI.WebControls.Label)e.Item.FindControl("label1");
string current = this.BindDDL(int.Parse(t.Text));
e.Item.Cells[1].Text = current;
}
}
private string BindDDL(int ddd)
{
string sss = "";
if (ddd==1)
{
sss="張三";
return sss;
}
else
{
sss="李四";
return sss;
}
}
註釋:msg爲一個類似WinForm的messagebox對話框,不必理會。可以使用label.Text代替
function Show(sea, comment)
{
//獲得鼠標的X軸的座標
x = event.clientX + document.body.scrollLeft ;
//獲得鼠標的Y軸的座標
y = event.clientY + document.body.scrollTop ;
//顯示彈出窗體
Popup.style.display="block";
//設置窗體的X,Y軸的座標
Popup.style.left = x;
Popup.style.top = y;
document.getElementById("td1").innerText="缺勤人員及原因:"+sea;
document.getElementById("td2").innerText="會議主要內容:"+comment;
}
//隱藏彈出窗體
function Hide()
{
Popup.style.display="none";
}
數據綁定事件
private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
e.Item.Attributes.Add("onmouseover", "this.oldcolor=this.style.backgroundColor;this.style.backgroundColor='#C8F7FF';");
e.Item.Attributes.Add("onmousemove", "Show('"+dtab.Rows[e.Item.ItemIndex+(DataGrid1.CurrentPageIndex*DataGrid1.PageSize)]["TeamMeet_AbsentName"].ToString()+"','"
+dtab.Rows[e.Item.ItemIndex+(DataGrid1.CurrentPageIndex*DataGrid1.PageSize)]["TeamMeet_Content"].ToString()+"');");
e.Item.Attributes.Add("onmouseout",
"this.style.backgroundColor=this.oldcolor;Hide();");
}
}
Popup是層
td1,td2是層裏一個table的單元格
<%@ Page EnableViewState="true" CodeBehind="SelectMultiPages.aspx.cs" Language="c#"
AutoEventWireup="false" Inherits="eMeng.Exam.SelectMultiPages" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>跨頁面實現多選</title>
<META http-equiv="content-type" content="text/html; charset=gb2312">
<style>
* {}{FONT-SIZE:12PX}
#Status {}{text-align:left}
</style>
<script language="JAVASCRIPT">
function AddRemoveValues(oChk) {
//在處理這個地方需要注意的是:你保存的值應該具有唯一性,這樣才能不會替換錯誤的項。
if(oChk.checked)
SelectMultiPage.HdnSelectedValues.value += "," + oChk.value;
else
SelectMultiPage.HdnSelectedValues.value = SelectMultiPage.HdnSelectedValues.value.replace("," + oChk.value,"");
}
</script>
</HEAD>
<BODY>
<form id="SelectMultiPage" runat="server">
<asp:datagrid id="DataGrid1" HorizontalAlign="Center" AutoGenerateColumns="False" Width="600px"
AllowPaging="True" runat="server">
<AlternatingItemStyle BackColor="#EEEEEE"></AlternatingItemStyle>
<HeaderStyle BackColor="#AAAADD" Font-Bold="True" HorizontalAlign="Center"></HeaderStyle>
<PagerStyle HorizontalAlign="Right" Mode="NumericPages" Visible="True"></PagerStyle>
<Columns>
<asp:TemplateColumn HeaderText="選擇">
<ItemTemplate>
<input type="checkbox" runat="server" id="chkSelect" onclick="AddRemoveValues(this)"
value='<%#DataBinder.Eval(Container.DataItem,"Title")%>'/>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="文章標題">
<ItemTemplate>
<asp:Literal Text='<%# DataBinder.Eval(Container.DataItem, "Title") %>' runat="server" ID="TitleShow"/>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="發佈時間">
<ItemTemplate>
<asp:Literal Text='<%# DataBinder.Eval(Container.DataItem, "CreateDate").ToString() %>' runat="server"/>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid>
<div align=center>
<asp:button id="Button1" runat="server" Text="得到所選的值"></asp:button>
<div id="Status">
<asp:label id="Label1" runat="server"></asp:label>
</div>
<INPUT id="HdnSelectedValues" type="hidden" name="HdnSelectedValues" runat="server">
</div>
</form>
</BODY>
</HTML>
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace eMeng.Exam
{
/**//// <summary>
/// SelectMultiPages 的摘要說明。
/// </summary>
public class SelectMultiPages : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.WebControls.Label Label1;
protected System.Web.UI.HtmlControls.HtmlInputHidden HdnSelectedValues;
protected System.Web.UI.WebControls.DataGrid DataGrid1;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此處放置用戶代碼以初始化頁面
if(!Page.IsPostBack)
BindData();
}
private void DataGrid1_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
DataGrid1.CurrentPageIndex = e.NewPageIndex;
BindData();
}
void BindData()
{
OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ HttpContext.Current.Server.MapPath("aspx.mdb"));
OleDbDataAdapter da = new OleDbDataAdapter("Select Title, CreateDate from Document",cn);
DataSet ds = new DataSet();
da.Fill(ds);
DataGrid1.DataSource= ds;
DataGrid1.DataBind();
}
private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
//重新顯示所選擇的項目
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
if(HdnSelectedValues.Value.IndexOf(((Literal)e.Item.Cells[1].FindControl("TitleShow")).Text) >= 0 )
{
HtmlInputCheckBox ChkSelected = (HtmlInputCheckBox)(e.Item.Cells[0].FindControl("ChkSelect"));
ChkSelected.Checked = true;
}
}
}
private void Button1_Click(object sender, System.EventArgs e)
{
//爲了顯示的方便進行替換的
Label1.Text = HdnSelectedValues.Value.Replace(",","<li>");
}
Web 窗體設計器生成的代碼#region Web 窗體設計器生成的代碼
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 該調用是 ASP.NET Web 窗體設計器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/**//// <summary>
/// 設計器支持所需的方法 - 不要使用代碼編輯器修改
/// 此方法的內容。
/// </summary>
private void InitializeComponent()
{
this.DataGrid1.ItemDataBound +=
new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemDataBound);
this.DataGrid1.PageIndexChanged +=
new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.DataGrid1_PageIndexChanged);
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}
html頁面的DataGrid如下所示:
<asp:datagrid id="grdTest" runat="server" Height="228px" Width="262px" AutoGenerateColumns="False" AllowPaging="True">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<!-- 這裏是關鍵-->
<SPAN>
<%# Container.ItemIndex+1 %></SPAN>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="CategoryName"></asp:BoundColumn>
<asp:BoundColumn DataField="Description"></asp:BoundColumn>
</Columns>
</asp:datagrid>
下面我們可以寫他的後臺代碼cs的文件了我們在它的Page_Load裏面添加綁定方法如下所示:
private void Page_Load(object sender, System.EventArgs e)
{
// 在此處放置用戶代碼以初始化頁面
strConnection = ConfigurationSettings.AppSettings["sa"].ToString();
myConnection = new SqlConnection(strConnection);
SqlDataAdapter myAdapter = new SqlDataAdapter("SELECT CategoryName, Description FROM Categories",myConnection);
// 爲了分頁方便ds是一個全局的變量
myAdapter.Fill(ds);
this.grdTest.DataSource = ds.Tables[0].DefaultView;
this.grdTest.DataBind();
}
從上面的過程可以看出我們使用的是表Categories,這樣我們就可以產生一列自增長的列,此列是從1開始的。如果我們想要一個從0開始的列有該怎麼辦呢?我們可以把<!-- 這裏是關鍵-->下面的<span>裏面的東西換成<asp:Label id=lblRowNumber runat="server" Text='<%# DataBinder.Eval(Container, "ItemIndex", "{0}") %>'>就可以了。
如果我們想要實現分頁也顯示的方法我們將使用DataTable的方法來實現,首先我們將DataGrid的列全部變成綁定列(爲了方便演示,不是必須)。如下所示:
<asp:table id="tbData" runat="server" BackColor="LightSteelBlue" Height="13px" Width="16px" Font-Names="宋體" Font-Name="宋體" Font-Size="8pt" CellPadding="1" CellSpacing="0" BorderColor="black" BorderWidth="1" Gridlines="Both"></asp:table><br/>
<asp:datagrid id="grdTest" runat="server" Height="228px" Width="262px" AutoGenerateColumns="False" PageSize="2" AllowPaging="True">
<Columns>
<asp:BoundColumn DataField="RowNumber" HeaderText="RowNumber"></asp:BoundColumn>
<asp:BoundColumn DataField="CategoryName"></asp:BoundColumn>
<asp:BoundColumn DataField="Description"></asp:BoundColumn>
</Columns>
</asp:datagrid>
在後臺我們添加一個函數:
private DataTable GetRowNumberTable(DataTable dt){
DataColumn col = new DataColumn("RowNumber",Type.GetType("System.Int32"));
dt.Columns.Add(col);
for(int i = 0;i<=dt.Rows.Count-1;i++){
if(0 == i)
dt.Rows[i][col] = 1;
else
dt.Rows[i][col] = Convert.ToInt32(dt.Rows[i-1][col]) +1;
}
return dt;
}
然後我們將原來數據源改成如下:
this.grdTest.DataSource = this.GetRowNumberTable(ds.Tables[0]).DefaultView;
這樣一來即使分頁,數字也是連續的,並且將編號應用於所有的行而不是當前這一頁的行。
可是當在線程裏面執行到 this.dataGridDF.DataSource=dt.DefaultView;填充數據
時卻提示報錯,說什麼該線程不能調用主線程創建的控件等等。
後來查了許多資料,終於搞定。可以在查詢數據庫時操作別的了,“正在查詢”的提示也顯示了。
//或者在前面用一個線程查詢,在線程裏調用dataGrid.BeginInvoke(異步方法)來單獨填充
public delegate void myDelegate();
DataTable dt;
private void btnDianJia_Click(object sender, System.EventArgs e)
{
try
{
mythread = new Thread(new ThreadStart(ThreadWork));
mythread.Start();
}
catch(System.Exception ex)
{
MessageBox.Show(this,ex.Message,"提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
}
void ThreadWork()
{
this.dataGridDJ.CaptionText="正在查詢電價數據";
mf.statusBarPanel1.Text="正在查詢電價數據";
this.Cursor=Cursors.WaitCursor;
string shijian=this.dateTimeDianJia.DateValue;
DateTime today=DateTime.Today;
string mingcheng=this.txtMingCheng.Text;
string leibie=this.cmbBoxLiebie_DJ.SelectedValue.ToString();
PowerWeb.BLL.DianFeiDianJia.DianJia dj=new PowerWeb.BLL.DianFeiDianJia.DianJia();
if(shijian==today.ToString("yyyyMM"))
{
dt=dj.GetList(leibie,mingcheng).Tables[0];
}
else
{
dt=dj.GetListOld(leibie,mingcheng,shijian).Tables[0];
}
this.dataGridDJ.CaptionText=shijian+"電價信息 (共計條"+dt.Rows.Count.ToString()+"記錄)";
dataGridDJ.BeginInvoke(new myDelegate(FillData));//異步調用(來填充)
this.Cursor=Cursors.Default;
mf.statusBarPanel1.Text="查詢結束";
}
private void FillData()
{
this.dataGridDJ.DataSource=dt.DefaultView;
}