日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

DataGrid 功能实现收集(转)保留做参考

發(fā)布時(shí)間:2025/3/15 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 DataGrid 功能实现收集(转)保留做参考 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
DataGrid相鄰行有相同內(nèi)容時(shí)對(duì)指定列合并 /**////?<summary>
///?DataGrid相鄰行有相同內(nèi)容時(shí)對(duì)指定列合并
///?</summary>
///?<param?name="spangrid">格式化的DataGrid的ID</param>
///?<param?name="spancell">要合并的列</param>????????
///?<param?name="spanby">合并所依據(jù)數(shù)據(jù)的列</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實(shí)現(xiàn)分頁不丟失選擇的記錄 namespace?checkboc_page
{
?
/**////?<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?窗體設(shè)計(jì)器生成的代碼#region?Web?窗體設(shè)計(jì)器生成的代碼
??
override?protected?void?OnInit(EventArgs?e)
??
{
???
//
???
//?CODEGEN:?該調(diào)用是?ASP.NET?Web?窗體設(shè)計(jì)器所必需的。
???
//
???InitializeComponent();
???
base.OnInit(e);
??}

??
??
/**////?<summary>
??
///?設(shè)計(jì)器支持所需的方法?-?不要使用代碼編輯器修改
??
///?此方法的內(nèi)容。
??
///?</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中添加刪除確認(rèn)對(duì)話框 多種實(shí)現(xiàn) 在DataGrid的使用中,經(jīng)常需要為刪除按紐添加確認(rèn)對(duì)話框,根據(jù)我的學(xué)習(xí)經(jīng)驗(yàn),總結(jié)了三種方法,原理都是在客戶端為刪除按紐添加腳本代碼來實(shí)現(xiàn)刪除前彈出確認(rèn)對(duì)話框。
方法一:
當(dāng)為DataGrid控件添加刪除按紐后,為DataGrid控件添加ItemDataBound事件處理程序,代碼如下:
//添加刪除確認(rèn)對(duì)話框。
???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('你真的要?jiǎng)h除第"+(e.Item.ItemIndex+1).ToString()+"行嗎?');");
?????
break;
???}

其中,e.Item.Cells[
4]說明你添加的刪除按紐在DataGrid控件中位于第五列,列號(hào)從0開始。
方法二:使用模板列
1.為DataGrid添加一個(gè)模板列,名為“自定義刪除”,在這個(gè)模板列中添加一個(gè)按紐,將按紐的CommandName屬性設(shè)為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('你真的要?jiǎng)h除第"+(e.Item.ItemIndex+1).ToString()+"行嗎?');");
?????
break;
???}

3.為DataGrid添加ItemCommand事件,處理刪除事件,代碼如下:
if(e.CommandName?==?"UserDelete")
???
{
????  
//執(zhí)行刪除。
???}

方法三:
這種方法很少見到人用,但卻是最簡(jiǎn)單的方法,方法如下:
將DataGrid的刪除按紐的文本屬性設(shè)為如下代碼:
<div?id=d?onclick="JavaScript:return?confirm('你真的要?jiǎng)h除這一行嗎?');">刪除</div>

使用RenderMethod 委托實(shí)現(xiàn)DataGrid表頭合并
1using?System;
??2
using?System.Collections;
??3
using?System.ComponentModel;
??4
using?System.Data;
??5
using?System.Drawing;
??6
using?System.Web;
??7
using?System.Web.SessionState;
??8
using?System.Web.UI;
??9
using?System.Web.UI.WebControls;
?10
using?System.Web.UI.HtmlControls;
?11
using?System.Data.SqlClient;
?
12
?13
namespace?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?窗體設(shè)計(jì)器生成的代碼Web?窗體設(shè)計(jì)器生成的代碼#region?Web?窗體設(shè)計(jì)器生成的代碼
?
54????????override?protected?void?OnInit(EventArgs?e)
?
55????????{
?
56????????????//
?57????????????//?CODEGEN:?該調(diào)用是?ASP.NET?Web?窗體設(shè)計(jì)器所必需的。
?58????????????//
?59????????????InitializeComponent();
?
60????????????base.OnInit(e);
?
61????????}

?
62????????
?
63????????/**//**//**////?<summary>
?64????????/**////?設(shè)計(jì)器支持所需的方法?-?不要使用代碼編輯器修改
?65????????/**////?此方法的內(nèi)容。
?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????????/**////?創(chuàng)建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的呈現(xiàn)方法定向到自定義的呈現(xiàn)方法上
?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呈現(xiàn)方法
?92????????/**////?</summary>
?93????????/**////?<param?name="writer"></param>
?94????????/**////?<param?name="ctl"></param>
?95????????private?void?NewRenderMethod(HtmlTextWriter?writer,Control?ctl)
?
96????????{
?
97????????????//不需要從<TR>標(biāo)簽開始
?98????????????//輸出“聯(lián)系電話”列
?99????????????writer.Write("<TD?colspan=\"3\"?align=\"center\">聯(lián)系電話</TD>\n");
100
101????????????//“地址”列必須有rowspan屬性且必須在第一列呈現(xiàn)
102????????????TableCell?cell?=?(TableCell)ctl.Controls[ctl.Controls.Count?-?1];
103????????????cell.Attributes.Add("rowspan","2");
104????????????cell.RenderControl(writer);
105
106????????????//現(xiàn)在關(guān)閉第一行
107????????????writer.Write("</TR>\n");
108
109????????????//將設(shè)計(jì)時(shí)的樣式屬性添加到第二行使得兩行的外觀相似
110????????????this.DataGrid1.HeaderStyle.AddAttributesToRender(writer);
111
112????????????//插入第二行
113????????????writer.RenderBeginTag("TR");
114
115????????????//呈現(xiàn)除了最后一列(剛才已經(jīng)呈現(xiàn)過了)外的所有在設(shè)計(jì)時(shí)定義的cells
116????????????for(int?i=0;i<=ctl.Controls.Count-2;i++)
117????????????{
118????????????????ctl.Controls[i].RenderControl(writer);
119????????????}

120
121????????????//不需要以</TR>結(jié)束
122????????}

123????}

124}
?

測(cè)試?yán)又械腄ataGrid選擇了Employees表中的四個(gè)字段?
代碼如下:?
<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="移動(dòng)電話"></asp:BoundColumn>?
<asp:BoundColumn?DataField="Address"?HeaderText="聯(lián)系地址"></asp:BoundColumn>?
</Columns>?
<PagerStyle?HorizontalAlign="Center"?ForeColor="#330099"?BackColor="#FFFFCC"></PagerStyle>?
</asp:DataGrid>DataGrid中使用CheckBox的CheckedChanged事件
使用DataGrid的過程中常會(huì)用到CheckBox控件,并使用它的CheckedChanged事件。使用如下:

1、CheckBox控件需要設(shè)置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中添加一個(gè)合計(jì)字段 你是否花了很時(shí)間來閱讀?ASPNG?列表?如果不是的話,我非常推薦它。你可以訪問
http:
//www.asp.net/?或?http://www.asplists.com/asplists/aspngevery.asp。最近的最常見的一個(gè)問題是:“?我怎樣在?DataGrid?中顯示列合計(jì)?”。?我親自多次為這個(gè)問題提供了示例代碼,因此,我想在DotNetJunkies?的標(biāo)題中提供這么一份指南。?在這份指南中你將會(huì)學(xué)到怎樣在?DataGrid?中編程實(shí)現(xiàn)對(duì)某一列的值進(jìn)行統(tǒng)計(jì),并在?DataGrid?的頁腳中顯示其合計(jì)值。這份指南中供下載的示例中包括了?C#?和?Visual?Basic.NET?兩種代碼。

?

上面所用到的屏幕圖片中的?DataGrid?是一個(gè)非常典型的?DataGrid?。有許多控制?DataGrid?外觀的屬性,它使用兩個(gè)?BoundColumns?來操作數(shù)據(jù),但這并不是最重要的。做好這項(xiàng)工作真正重要的是使用?DataGrid.OnItemDataBound?事件。這個(gè)事件將會(huì)觸發(fā)每次綁定一條記錄到?DataGrid。你可以為這個(gè)事件創(chuàng)建一個(gè)事件處理,以操作數(shù)據(jù)記錄。在這種情況下,你將會(huì)得到運(yùn)行時(shí)?Price?列的合計(jì)值。

頁腳指的是數(shù)據(jù)范圍的最后一行。當(dāng)這行被限定時(shí),在事件句處理你可以得到?Price?列的運(yùn)行時(shí)統(tǒng)計(jì)值。

實(shí)施:

首先讓我們找到一種方法來操作?Web?窗體輸出。?這份指南中,你將使用一個(gè)?Web?窗體?(calcTotals.aspx)?以及一個(gè)類代碼文件?(calcTotals.aspx.cs)。這份指南的意圖是,?類代碼將會(huì)使用?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?來直接聲明這個(gè)頁所繼承的類代碼。SRC?屬性指明了類代碼將使用?JIT?編譯器來編譯。?Web?窗體中的大部分代碼樣式聲明用來使?DataGrid?外觀變得更好看。

最后指定的屬性之一是?OnItemDataBound?屬性。這個(gè)事件將會(huì)在?OnItemDataBound?事件發(fā)生時(shí)被觸發(fā)。

Web?窗體中的?DataGrid?(MyGrid)?包含有兩個(gè)?BoundColumns,一個(gè)是?Title?,另一個(gè)是Price。?這里將顯示?Pubs?數(shù)據(jù)庫(SQL?Server)中?Titles?表的?title?及?price?列。

忽略代碼的定義

類代碼在所有的地方都將使用。在類代碼中,你可以操作兩個(gè)事件:Page_Load?事件以及?MyGrid_OnItemDataBound?事件。還有一個(gè)私有方法?CalcTotal,?用它來簡(jiǎn)單的完成運(yùn)行時(shí)統(tǒng)計(jì)的數(shù)學(xué)運(yùn)算。

類代碼基本結(jié)構(gòu)塊的起始部分:

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;
??}

}
?

在類代碼的基本結(jié)構(gòu)中,你必須使用相關(guān)語句導(dǎo)入名字空間(
namespace)。在類聲明中,你聲明了兩個(gè)變量,一個(gè)是類代碼中映射?Web?窗體的?DataGrid(MyGrid)控件的變量;一個(gè)是用來操作?DataGrid?的?Price?列中運(yùn)行時(shí)統(tǒng)計(jì)的雙精度值。?

Page_Load?事件

在?Page_Load?事件中,你所要做的就是連接到?SQL?Server?并執(zhí)行一個(gè)簡(jiǎn)單的?SqlCommand。?你取得了所有?Price?值>
0?的?title?和?price?數(shù)據(jù)。你使用?SqlCommand.ExecuteReader?方法返回一個(gè)?SqlDataReader?并將其直接綁定到?DataGrid?(MyGrid)。

protected?void?Page_Load(object?sender,?EventArgs?e)
{
??SqlConnection?myConnection?
=?new?SqlConnection("server=Localhost;database=pubs;uid=sa;pwd=;");//創(chuàng)建SQL連接
??SqlCommand?myCommand?=?new?SqlCommand("SELECT?title,?price?FROM?Titles?WHERE?price?>?0",?myConnection);//創(chuàng)建SQL命令

??
try
??
{
????myConnection.Open();
//打開數(shù)據(jù)庫連接
????MyGrid.DataSource?=?myCommand.ExecuteReader();//指定?DataGrid?的數(shù)據(jù)源
????MyGrid.DataBind();//綁定數(shù)據(jù)到?DataGrid
????myConnection.Close();//關(guān)閉數(shù)據(jù)連接
??}

??
catch(Exception?ex)
??
{
????
//捕獲錯(cuò)誤
????HttpContext.Current.Response.Write(ex.ToString());
??}

}

?

CalcTotals?方法

CalcTotals?方法用來處理?runningTotal?變量。這個(gè)值將以字符串形式來傳遞。?你需要將它解析為雙精度型,然后?runningTotal?變量就成了雙精度類型。

private?void?CalcTotal(string?_price)
{
??
try
??
{
????runningTotal?
+=?Double.Parse(_price);
??}

??
catch
??
{
?????
//捕獲錯(cuò)誤
??}

}

?

MyGrid_ItemDataBound?事件

MyGrid_ItemDataBound?事件在數(shù)據(jù)源中每行綁定到?DataGrid?時(shí)被調(diào)用。在這個(gè)事件處理中,你可以處理每一行數(shù)據(jù)。?這里你的目的是,你將需要調(diào)用?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?判斷當(dāng)前的?DataGridItem?是一個(gè)數(shù)據(jù)項(xiàng)還是AlternatingItem?行。如果是數(shù)據(jù)項(xiàng),你調(diào)用?CalcTotals,并將?Price?列的值作為參數(shù)傳遞給它;然后你以金額格式對(duì)?Price?列進(jìn)行格式化及著色。

如果?DataGridItem?是頁腳,可以用金額格式顯示?runningTotal。

總結(jié)

在這份指南中,你學(xué)到了怎樣使用?DataGrid.OnItemDataBound?事件來實(shí)現(xiàn)運(yùn)行時(shí)對(duì)DataGrid?的某一列進(jìn)行統(tǒng)計(jì)。使用這個(gè)事件,你可以創(chuàng)建一個(gè)列的合計(jì)并可對(duì)DataGrid行的頁腳進(jìn)行著色。?


使用DataGrid動(dòng)態(tài)綁定DropDownList 簡(jiǎn)單的使用模板列綁定DropDownList,初學(xué)者想必都會(huì)了,但有時(shí)候,我們要做的就是在編輯的時(shí)候想讓某一列定制為DropDownList,并且根據(jù)正常情況下顯示的值自動(dòng)變換DropDownList中所選的值,然后保存選擇后的值到數(shù)據(jù)庫或XML文件,其實(shí)要做到這樣的功能并不難,只要我們學(xué)會(huì)使用DataGrid的DataGrid1_ItemDataBound事件就行了,跟我來做個(gè)例子。

//檢索數(shù)據(jù)庫的函數(shù)
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(
"加載數(shù)據(jù)錯(cuò)誤!",Page);
}

}


綁定好DataGrid以后,設(shè)定模板列,讓其正常顯示下為Label,并綁定為數(shù)據(jù)庫中一ID值,在編輯狀態(tài)下為DropDownList,并綁定為數(shù)據(jù)庫中一Name值,我們現(xiàn)在要做的就是當(dāng)我們選擇編輯時(shí)根據(jù)Label的值自動(dòng)從數(shù)據(jù)庫中取出編號(hào)為ID值的姓名,并用DropDownList默認(rèn)選中。(注釋:為了方便大家學(xué)習(xí),我給出一個(gè)簡(jiǎn)單代碼的例子,供大家參考)

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為一個(gè)類似WinForm的messagebox對(duì)話框,不必理會(huì)。可以使用label.Text代替

轉(zhuǎn)載于:https://www.cnblogs.com/xh831213/archive/2006/02/13/329451.html

總結(jié)

以上是生活随笔為你收集整理的DataGrid 功能实现收集(转)保留做参考的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。