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

 
DataGrid相邻行有相同内容时对指定列合并
ExpandedBlockStart.gif ContractedBlock.gif /**/ /// <summary>
InBlock.gif
/// DataGrid相邻行有相同内容时对指定列合并
InBlock.gif
/// </summary>
InBlock.gif
/// <param name="spangrid">格式化的DataGrid的ID</param>
InBlock.gif
/// <param name="spancell">要合并的列</param>        
ExpandedBlockEnd.gif
/// <param name="spanby">合并所依据数据的列</param>

None.gif      public   void  FormatGrid(DataGrid spangrid, int  spancell, int  spanby)
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif {
InBlock.gif      
if(spanby<0 || spanby>spangrid.Items.Count)
InBlock.gif          
return;
InBlock.gif          
int rowspan = 1;
InBlock.gif          
for(int i = 1;i<spangrid.Items.Count;i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif         
dot.gif{
InBlock.gif        
if(spangrid.Items[i].Cells[spanby].Text == spangrid.Items[i-1].Cells[spanby].Text)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
InBlock.gif               rowspan 
+=1;
InBlock.gif               spangrid.Items[i].Cells[spancell].Visible 
= false;
InBlock.gif               spangrid.Items[i
-rowspan+1].Cells[spancell].RowSpan = rowspan;
ExpandedSubBlockEnd.gif            }

InBlock.gif        
else
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{    
InBlock.gif           
string str = spangrid.Items[i].Cells[spanby].Text;
InBlock.gif           
string str1 = spangrid.Items[i-1].Cells[spanby].Text;
InBlock.gif           rowspan 
= 1;
ExpandedSubBlockEnd.gif        }
    
ExpandedSubBlockEnd.gif              }

ExpandedBlockEnd.gif    }
 
None.gif
None.gif

datagrid加checkbox实现分页不丢失选择的记录
None.gif namespace  checkboc_page
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
ExpandedSubBlockStart.gifContractedSubBlock.gif 
/**//// <summary>
InBlock.gif 
/// WebForm1 的摘要说明。
ExpandedSubBlockEnd.gif 
/// </summary>

InBlock.gif public class WebForm1 : System.Web.UI.Page
ExpandedSubBlockStart.gifContractedSubBlock.gif 
dot.gif{
InBlock.gif  
protected System.Web.UI.WebControls.Button Button1;
InBlock.gif  
protected System.Web.UI.WebControls.DataGrid DataGrid1;
InBlock.gif 
InBlock.gif  
private void Page_Load(object sender, System.EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif   
if(!Page.IsPostBack)
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{
InBlock.gif    show();
ExpandedSubBlockEnd.gif   }

ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
private void show()
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif   
string conn =  ConfigurationSettings.AppSettings.Get("Connstring");
InBlock.gif   DataSet ds 
= new DataSet();
InBlock.gif   
using(  SqlConnection con = new SqlConnection(conn))
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{
InBlock.gif    con.Open();
InBlock.gif    SqlCommand comm 
= new SqlCommand();
InBlock.gif    SqlDataAdapter da 
=new SqlDataAdapter();
InBlock.gif     
InBlock.gif    da.SelectCommand 
= new SqlCommand();
InBlock.gif    da.SelectCommand.Connection 
= con;
InBlock.gif    da.SelectCommand.CommandText 
= "select * from Orders";
InBlock.gif    da.SelectCommand.CommandType 
= CommandType.Text;
InBlock.gif     
InBlock.gif    da.Fill(ds);
InBlock.gif            
InBlock.gif   
InBlock.gif     
ExpandedSubBlockEnd.gif   }

InBlock.gif   
this.DataGrid1.DataSource = ds.Tables[0];
InBlock.gif   
InBlock.gif   
this.DataGrid1.DataBind();
InBlock.gif             
InBlock.gif   
if(Session["userlist"]!=null)
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{
InBlock.gif    Hashtable ht 
=(Hashtable) Session["userlist"];
InBlock.gif    
if(ht!=null)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif     
for(int i = 0 ;i<DataGrid1.Items.Count ;i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif     
dot.gif{
InBlock.gif      
if (ht.ContainsKey(DataGrid1.Items[i].Cells[0].Text.ToString().Trim()))
InBlock.gif       (DataGrid1.Items[i].Cells[
2].FindControl("CheckBox1"as CheckBox).Checked = true;
InBlock.gif
ExpandedSubBlockEnd.gif     }

ExpandedSubBlockEnd.gif    }

ExpandedSubBlockEnd.gif   }

ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
private void check()
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif   Hashtable ht 
= new Hashtable();
InBlock.gif   
if(Session["userlist"]!=null)
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{
InBlock.gif    ht 
=(Hashtable) Session["userlist"];
InBlock.gif    
if(ht!=null)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif     
for(int i = 0 ;i<DataGrid1.Items.Count ;i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif     
dot.gif{
InBlock.gif      
if ( (DataGrid1.Items[i].Cells[2].FindControl("CheckBox1"as CheckBox).Checked)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif       
if (! ht.ContainsKey(DataGrid1.Items[i].Cells[0].Text.ToString().Trim()))
ExpandedSubBlockStart.gifContractedSubBlock.gif       
dot.gif{
InBlock.gif        ht.Add(DataGrid1.Items[i].Cells[
0].Text.ToString().Trim(),DataGrid1.Items[i].Cells[1].Text.ToString().Trim());
ExpandedSubBlockEnd.gif       }

ExpandedSubBlockEnd.gif      }

InBlock.gif      
else
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif       
if ( ht.ContainsKey(DataGrid1.Items[i].Cells[0].Text.ToString().Trim()))
ExpandedSubBlockStart.gifContractedSubBlock.gif       
dot.gif{
InBlock.gif        ht.Remove(DataGrid1.Items[i].Cells[
0].Text.ToString().Trim());
ExpandedSubBlockEnd.gif       }

ExpandedSubBlockEnd.gif      }

ExpandedSubBlockEnd.gif     }

ExpandedSubBlockEnd.gif    }

ExpandedSubBlockEnd.gif   }

InBlock.gif   
else
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{
InBlock.gif    
for(int i = 0 ;i<DataGrid1.Items.Count ;i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif     
if ( (DataGrid1.Items[i].Cells[2].FindControl("CheckBox1"as CheckBox).Checked)
ExpandedSubBlockStart.gifContractedSubBlock.gif     
dot.gif{
InBlock.gif      ht.Add(DataGrid1.Items[i].Cells[
0].Text.ToString().Trim(),DataGrid1.Items[i].Cells[1].Text.ToString().Trim());
ExpandedSubBlockEnd.gif     }

ExpandedSubBlockEnd.gif    }

ExpandedSubBlockEnd.gif   }

InBlock.gif
InBlock.gif   Session[
"userlist"= ht;
ExpandedSubBlockEnd.gif  }

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif  
Web 窗体设计器生成的代码#region Web 窗体设计器生成的代码
InBlock.gif  
override protected void OnInit(EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif   
//
InBlock.gif   
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
InBlock.gif   
//
InBlock.gif
   InitializeComponent();
InBlock.gif   
base.OnInit(e);
ExpandedSubBlockEnd.gif  }

InBlock.gif  
ExpandedSubBlockStart.gifContractedSubBlock.gif  
/**//// <summary>
InBlock.gif  
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
InBlock.gif  
/// 此方法的内容。
ExpandedSubBlockEnd.gif  
/// </summary>

InBlock.gif  private void InitializeComponent()
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{    
InBlock.gif   
this.DataGrid1.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.DataGrid1_PageIndexChanged);
InBlock.gif   
this.Button1.Click += new System.EventHandler(this.Button1_Click);
InBlock.gif   
this.Load += new System.EventHandler(this.Page_Load);
InBlock.gif
ExpandedSubBlockEnd.gif  }

ExpandedSubBlockEnd.gif  
#endregion

InBlock.gif
InBlock.gif  
private void DataGrid1_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif   check();
InBlock.gif   
InBlock.gif   DataGrid1.CurrentPageIndex 
= e.NewPageIndex;
InBlock.gif   show();
ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
private void Button1_Click(object sender, System.EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif    
InBlock.gif   
InBlock.gif             check();
InBlock.gif   Hashtable ht 
= (Hashtable)Session["userlist"];
InBlock.gif    
InBlock.gif    
foreach (DictionaryEntry objDE in ht)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif     Response.Write(objDE.Value.ToString());
InBlock.gif      
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif
InBlock.gif    
ExpandedSubBlockEnd.gif  }

ExpandedSubBlockEnd.gif }

ExpandedBlockEnd.gif}

None.gif
None.gif

DataGrid中添加删除确认对话框 多种实现
None.gif 在DataGrid的使用中,经常需要为删除按纽添加确认对话框,根据我的学习经验,总结了三种方法,原理都是在客户端为删除按纽添加脚本代码来实现删除前弹出确认对话框。
None.gif方法一:
None.gif当为DataGrid控件添加删除按纽后,为DataGrid控件添加ItemDataBound事件处理程序,代码如下:
None.gif
// 添加删除确认对话框。
None.gif
    switch (e.Item.ItemType)
ExpandedBlockStart.gifContractedBlock.gif   
dot.gif {
InBlock.gif    
case ListItemType.Item:
InBlock.gif    
case ListItemType.EditItem:
InBlock.gif    
case ListItemType.AlternatingItem:
InBlock.gif     ((LinkButton)e.Item.Cells[
4].Controls[0]).Attributes.Add("onclick","return confirm('你真的要删除第"+(e.Item.ItemIndex+1).ToString()+"行吗?');");
InBlock.gif     
break;
ExpandedBlockEnd.gif   }

None.gif其中,e.Item.Cells[
4 ]说明你添加的删除按纽在DataGrid控件中位于第五列,列号从0开始。
None.gif方法二:使用模板列
None.gif
1 .为DataGrid添加一个模板列,名为“自定义删除”,在这个模板列中添加一个按纽,将按纽的CommandName属性设为UserDelete;
None.gif
2 .为DataGrid添加ItemCreated事件,添加客户端脚本程序,代码如下:
None.gif
switch (e.Item.ItemType)
ExpandedBlockStart.gifContractedBlock.gif   
dot.gif {
InBlock.gif    
case ListItemType.Item:
InBlock.gif    
case ListItemType.EditItem:
InBlock.gif    
case ListItemType.AlternatingItem:
InBlock.gif     Button myDelButton 
= (Button)e.Item.FindControl("btnDelete");
InBlock.gif     myDelButton.Attributes.Add(
"onclick","return confirm('你真的要删除第"+(e.Item.ItemIndex+1).ToString()+"行吗?');");
InBlock.gif     
break;
ExpandedBlockEnd.gif   }

None.gif
3 .为DataGrid添加ItemCommand事件,处理删除事件,代码如下:
None.gif
if (e.CommandName  ==   " UserDelete " )
ExpandedBlockStart.gifContractedBlock.gif   
dot.gif {
InBlock.gif      
//执行删除。
ExpandedBlockEnd.gif
   }

None.gif方法三:
None.gif这种方法很少见到人用,但却是最简单的方法,方法如下:
None.gif将DataGrid的删除按纽的文本属性设为如下代码:
None.gif
< div id = d onclick = " JavaScript:return confirm('你真的要删除这一行吗?'); " > 删除 </ div >
None.gif

使用RenderMethod 委托实现DataGrid表头合并
None.gif 1 using  System;
None.gif  2
using  System.Collections;
None.gif  3
using  System.ComponentModel;
None.gif  4
using  System.Data;
None.gif  5
using  System.Drawing;
None.gif  6
using  System.Web;
None.gif  7
using  System.Web.SessionState;
None.gif  8
using  System.Web.UI;
None.gif  9
using  System.Web.UI.WebControls;
None.gif 10
using  System.Web.UI.HtmlControls;
None.gif 11
using  System.Data.SqlClient;
None.gif 
12
None.gif 13
namespace  WebDataGridHeader
ExpandedBlockStart.gifContractedBlock.gif 
14 dot.gif {
ExpandedSubBlockStart.gifContractedSubBlock.gif 
15    /**//**//**//// <summary>
ExpandedSubBlockStart.gifContractedSubBlock.gif 16    /**////DataGrid表头合并问题
ExpandedSubBlockStart.gifContractedSubBlock.gif 17    /**//// </summary>
InBlock.gif 18    public class WebForm1 : System.Web.UI.Page
ExpandedSubBlockStart.gifContractedSubBlock.gif 
19    dot.gif{
InBlock.gif 
20        protected System.Web.UI.WebControls.DataGrid DataGrid1;
InBlock.gif 
21        protected System.Web.UI.WebControls.Label Label1;
InBlock.gif 
22    
InBlock.gif 
23        private void Page_Load(object sender, System.EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif 
24        dot.gif{
InBlock.gif 
25            // 在此处放置用户代码以初始化页面
InBlock.gif
 26            string m_strConn = "server=.;uid=sa;pwd=sa;database=Northwind";
InBlock.gif 
27            SqlConnection conn = new SqlConnection(m_strConn);
InBlock.gif 
28            
InBlock.gif 
29            try
ExpandedSubBlockStart.gifContractedSubBlock.gif 
30            dot.gif{
InBlock.gif 
31                conn.Open();
InBlock.gif 
32
InBlock.gif 
33                SqlCommand cmd = new SqlCommand("SELECT * FROM Employees",conn);
InBlock.gif 
34            
InBlock.gif 
35                SqlDataAdapter adp = new SqlDataAdapter(cmd);
InBlock.gif 
36
InBlock.gif 
37                DataTable dt = new DataTable();
InBlock.gif 
38                adp.Fill(dt);
InBlock.gif 
39
InBlock.gif 
40                this.DataGrid1.DataSource = dt;
InBlock.gif 
41                this.DataGrid1.DataBind();
ExpandedSubBlockEnd.gif 
42            }

InBlock.gif 
43            catch(Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif 
44            dot.gif{
InBlock.gif 
45                throw ex;
ExpandedSubBlockEnd.gif 
46            }

InBlock.gif 
47            finally
ExpandedSubBlockStart.gifContractedSubBlock.gif 
48            dot.gif{
InBlock.gif 
49                conn.Close();
ExpandedSubBlockEnd.gif 
50            }

ExpandedSubBlockEnd.gif 
51        }

InBlock.gif 
52
ContractedSubBlock.gifExpandedSubBlockStart.gif 
53        Web 窗体设计器生成的代码Web 窗体设计器生成的代码#region Web 窗体设计器生成的代码
InBlock.gif 
54        override protected void OnInit(EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif 
55        dot.gif{
InBlock.gif 
56            //
InBlock.gif
 57            // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
InBlock.gif
 58            //
InBlock.gif
 59            InitializeComponent();
InBlock.gif 
60            base.OnInit(e);
ExpandedSubBlockEnd.gif 
61        }

InBlock.gif 
62        
ExpandedSubBlockStart.gifContractedSubBlock.gif 
63        /**//**//**//// <summary>
ExpandedSubBlockStart.gifContractedSubBlock.gif 64        /**//// 设计器支持所需的方法 - 不要使用代码编辑器修改
ExpandedSubBlockStart.gifContractedSubBlock.gif 65        /**//// 此方法的内容。
ExpandedSubBlockStart.gifContractedSubBlock.gif 66        /**//// </summary>
InBlock.gif 67        private void InitializeComponent()
ExpandedSubBlockStart.gifContractedSubBlock.gif 
68        dot.gif{    
InBlock.gif 
69            this.DataGrid1.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemCreated);
InBlock.gif 
70            this.Load += new System.EventHandler(this.Page_Load);
InBlock.gif 
71
ExpandedSubBlockEnd.gif 
72        }

ExpandedSubBlockEnd.gif 
73        #endregion

InBlock.gif 
74        
ExpandedSubBlockStart.gifContractedSubBlock.gif 
75        /**//**//**//// <summary>
ExpandedSubBlockStart.gifContractedSubBlock.gif 76        /**//// 创建Item
ExpandedSubBlockStart.gifContractedSubBlock.gif 77        /**//// </summary>
ExpandedSubBlockStart.gifContractedSubBlock.gif 78        /**//// <param name="sender"></param>
ExpandedSubBlockStart.gifContractedSubBlock.gif 79        /**//// <param name="e"></param>
InBlock.gif 80        private void DataGrid1_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif 
81        dot.gif{
InBlock.gif 
82            //将Item的呈现方法定向到自定义的呈现方法上
InBlock.gif
 83            ListItemType lit = e.Item.ItemType;
InBlock.gif 
84            if(ListItemType.Header == lit)
ExpandedSubBlockStart.gifContractedSubBlock.gif 
85            dot.gif{
InBlock.gif 
86                e.Item.SetRenderMethodDelegate(new RenderMethod(NewRenderMethod));
ExpandedSubBlockEnd.gif 
87            }

ExpandedSubBlockEnd.gif 
88        }

InBlock.gif 
89        
ExpandedSubBlockStart.gifContractedSubBlock.gif 
90        /**//**//**//// <summary>
ExpandedSubBlockStart.gifContractedSubBlock.gif 91        /**//// 自定义的Item呈现方法
ExpandedSubBlockStart.gifContractedSubBlock.gif 92        /**//// </summary>
ExpandedSubBlockStart.gifContractedSubBlock.gif 93        /**//// <param name="writer"></param>
ExpandedSubBlockStart.gifContractedSubBlock.gif 94        /**//// <param name="ctl"></param>
InBlock.gif 95        private void NewRenderMethod(HtmlTextWriter writer,Control ctl)
ExpandedSubBlockStart.gifContractedSubBlock.gif 
96        dot.gif{
InBlock.gif 
97            //不需要从<TR>标签开始
InBlock.gif
 98            //输出“联系电话”列
InBlock.gif
 99            writer.Write("<TD colspan=\"3\" align=\"center\">联系电话</TD>\n");
InBlock.gif
100
InBlock.gif
101            //“地址”列必须有rowspan属性且必须在第一列呈现
InBlock.gif
102            TableCell cell = (TableCell)ctl.Controls[ctl.Controls.Count - 1];
InBlock.gif
103            cell.Attributes.Add("rowspan","2");
InBlock.gif
104            cell.RenderControl(writer);
InBlock.gif
105
InBlock.gif
106            //现在关闭第一行
InBlock.gif
107            writer.Write("</TR>\n");
InBlock.gif
108
InBlock.gif
109            //将设计时的样式属性添加到第二行使得两行的外观相似
InBlock.gif
110            this.DataGrid1.HeaderStyle.AddAttributesToRender(writer);
InBlock.gif
111
InBlock.gif
112            //插入第二行
InBlock.gif
113            writer.RenderBeginTag("TR");
InBlock.gif
114
InBlock.gif
115            //呈现除了最后一列(刚才已经呈现过了)外的所有在设计时定义的cells
InBlock.gif
116            for(int i=0;i<=ctl.Controls.Count-2;i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif
117            dot.gif{
InBlock.gif
118                ctl.Controls[i].RenderControl(writer);
ExpandedSubBlockEnd.gif
119            }

InBlock.gif
120
InBlock.gif
121            //不需要以</TR>结束
ExpandedSubBlockEnd.gif
122        }

ExpandedSubBlockEnd.gif
123    }

ExpandedBlockEnd.gif
124}
 
None.gif

None.gif 测试例子中的DataGrid选择了Employees表中的四个字段 
None.gif代码如下: 
None.gif
< asp:DataGrid  id ="DataGrid1"  runat ="server"  Width ="793px"  Height ="296px"  AutoGenerateColumns ="False"  
None.gifBorderColor
="#CC9966"  BorderStyle ="None"  BorderWidth ="1px"  BackColor ="White"  CellPadding ="4" >  
None.gif
< SelectedItemStyle  Font-Bold ="True"  ForeColor ="#663399"  BackColor ="#FFCC66" ></ SelectedItemStyle >  
None.gif
< ItemStyle  ForeColor ="#330099"  BackColor ="White" ></ ItemStyle >  
None.gif
< HeaderStyle  Font-Bold ="True"  ForeColor ="#FFFFCC"  BackColor ="#990000" ></ HeaderStyle >  
None.gif
< FooterStyle  ForeColor ="#330099"  BackColor ="#FFFFCC" ></ FooterStyle >  
None.gif
< Columns >  
None.gif
< asp:BoundColumn  DataField ="LastName"  HeaderText ="办公电话" ></ asp:BoundColumn >  
None.gif
< asp:BoundColumn  DataField ="FirstName"  HeaderText ="住宅电话" ></ asp:BoundColumn >  
None.gif
< asp:BoundColumn  DataField ="HomePhone"  HeaderText ="移动电话" ></ asp:BoundColumn >  
None.gif
< asp:BoundColumn  DataField ="Address"  HeaderText ="联系地址" ></ asp:BoundColumn >  
None.gif
</ Columns >  
None.gif
< PagerStyle  HorizontalAlign ="Center"  ForeColor ="#330099"  BackColor ="#FFFFCC" ></ PagerStyle >  
None.gif
</ asp:DataGrid >
DataGrid中使用CheckBox的CheckedChanged事件
None.gif 使用DataGrid的过程中常会用到CheckBox控件,并使用它的CheckedChanged事件。使用如下:
None.gif
None.gif
1 、CheckBox控件需要设置AutoPostBack = " true "
None.gif
< asp:CheckBox id = " chbIsActive "  runat = " server "  AutoPostBack = " true " ></ asp:CheckBox >
None.gif
2 、CheckBox控件的事件须在DataGrid的ItemCreated定义才能生效
None.gif        
private   void  grdStructure_ItemCreated( object  sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif {
InBlock.gif            
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
InBlock.gif                CheckBox chbIsActive 
= e.Item.FindControl("chbIsActive"as CheckBox;
InBlock.gif                chbIsActive.CheckedChanged 
+= new EventHandler(chbIsActive_CheckedChanged);
ExpandedSubBlockEnd.gif            }

ExpandedBlockEnd.gif        }

None.gif
3 、编写事件代码
None.gif        
private   void  chbIsActive_CheckedChanged( object  sender, EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif {
InBlock.gif            CheckBox chbIsActive 
= (CheckBox)sender;
InBlock.gif
InBlock.gif            Guid structureUID 
= new Guid(chbIsActive.Attributes["StructureUID"]);
InBlock.gif            
bool isActive = chbIsActive.Checked;
InBlock.gif
InBlock.gif            IPMStructureManager manager 
= PMStructureManagerFactory.GetInstance();
InBlock.gif            manager.SetActive(structureUID, isActive);
InBlock.gif
InBlock.gif            
this.Binding();
ExpandedBlockEnd.gif        }

None.gif

在DataGrid中添加一个合计字段
None.gif 你是否花了很时间来阅读 ASPNG 列表?如果不是的话,我非常推荐它。你可以访问
None.gifhttp:
// www.asp.net/ 或  http://www.asplists.com/asplists/aspngevery.asp 。最近的最常见的一个问题是:“ 我怎样在 DataGrid 中显示列合计?”。 我亲自多次为这个问题提供了示例代码,因此,我想在DotNetJunkies 的标题中提供这么一份指南。 在这份指南中你将会学到怎样在 DataGrid 中编程实现对某一列的值进行统计,并在 DataGrid 的页脚中显示其合计值。这份指南中供下载的示例中包括了 C# 和 Visual Basic.NET 两种代码。
None.gif

None.gif 
None.gif
None.gif上面所用到的屏幕图片中的 DataGrid 是一个非常典型的 DataGrid 。有许多控制 DataGrid 外观的属性,它使用两个 BoundColumns 来操作数据,但这并不是最重要的。做好这项工作真正重要的是使用 DataGrid.OnItemDataBound 事件。这个事件将会触发每次绑定一条记录到 DataGrid。你可以为这个事件创建一个事件处理,以操作数据记录。在这种情况下,你将会得到运行时 Price 列的合计值。
None.gif
None.gif页脚指的是数据范围的最后一行。当这行被限定时,在事件句处理你可以得到 Price 列的运行时统计值。
None.gif
None.gif实施:
None.gif
None.gif首先让我们找到一种方法来操作 Web 窗体输出。 这份指南中,你将使用一个 Web 窗体 (calcTotals.aspx) 以及一个类代码文件 (calcTotals.aspx.cs)。这份指南的意图是, 类代码将会使用 Just
- In - Time 编译器来编译。 这里是 calcTotals.aspx 的代码:
None.gif
None.gif
<% @ Page Inherits = " myApp.calcTotals "  Src = " 20010731T0101.aspx.cs "   %>
None.gif
< html >
None.gif
< body bgcolor = " white " >
None.gif
< asp:DataGrid id = " MyGrid "  runat = " server "
None.gif  AutoGenerateColumns
= " False "
None.gif  CellPadding
= " 4 "  CellSpacing = " 0 "
None.gif  BorderStyle
= " Solid "  BorderWidth = " 1 "
None.gif  Gridlines
= " None "  BorderColor = " Black "
None.gif  ItemStyle
- Font - Name = " Verdana "
None.gif  ItemStyle
- Font - Size = " 9pt "
None.gif  HeaderStyle
- Font - Name = " Verdana "
None.gif  HeaderStyle
- Font - Size = " 10pt "
None.gif  HeaderStyle
- Font - Bold = " True "
None.gif  HeaderStyle
- ForeColor = " White "
None.gif  HeaderStyle
- BackColor = " Blue "
None.gif  FooterStyle
- Font - Name = " Verdana "
None.gif  FooterStyle
- Font - Size = " 10pt "
None.gif  FooterStyle
- Font - Bold = " True "
None.gif  FooterStyle
- ForeColor = " White "
None.gif  FooterStyle
- BackColor = " Blue "
None.gif  OnItemDataBound
= " MyDataGrid_ItemDataBound "
None.gif  ShowFooter
= " True " >
None.gif  
< Columns >
None.gif    
< asp:BoundColumn HeaderText = " Title "  DataField = " title "   />
None.gif    
< asp:BoundColumn HeaderText = " Price "  DataField = " price "
None.gif      ItemStyle
- HorizontalAlign = " Right "
None.gif      HeaderStyle
- HorizontalAlign = " Center "   />
None.gif   
</ Columns >
None.gif
</ asp:DataGrid >
None.gif
</ body >
None.gif
</ html >  
None.gif
None.gif在 Web 窗体中你使用 @ Page 来直接声明这个页所继承的类代码。SRC 属性指明了类代码将使用 JIT 编译器来编译。 Web 窗体中的大部分代码样式声明用来使 DataGrid 外观变得更好看。
None.gif
None.gif最后指定的属性之一是 OnItemDataBound 属性。这个事件将会在 OnItemDataBound 事件发生时被触发。
None.gif
None.gifWeb 窗体中的 DataGrid (MyGrid) 包含有两个 BoundColumns,一个是 Title ,另一个是Price。 这里将显示 Pubs 数据库(SQL Server)中 Titles 表的 title 及 price 列。
None.gif
None.gif忽略代码的定义
None.gif
None.gif类代码在所有的地方都将使用。在类代码中,你可以操作两个事件:Page_Load 事件以及 MyGrid_OnItemDataBound 事件。还有一个私有方法 CalcTotal, 用它来简单的完成运行时统计的数学运算。
None.gif
None.gif类代码基本结构块的起始部分:
None.gif
None.gif
using  System;
None.gif
using  System.Web;
None.gif
using  System.Web.UI;
None.gif
using  System.Web.UI.WebControls;
None.gif
using  System.Web.UI.HtmlControls;
None.gif
using  System.Data;
None.gif
using  System.Data.SqlClient;
None.gif
None.gif
namespace  myApp
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif  
public class calcTotals : Page
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif    
protected DataGrid MyGrid;
InBlock.gif    
private double runningTotal = 0;
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}
 
None.gif
None.gif在类代码的基本结构中,你必须使用相关语句导入名字空间(
namespace )。在类声明中,你声明了两个变量,一个是类代码中映射 Web 窗体的 DataGrid(MyGrid)控件的变量;一个是用来操作 DataGrid 的 Price 列中运行时统计的双精度值。 
None.gif
None.gifPage_Load 事件
None.gif
None.gif在 Page_Load 事件中,你所要做的就是连接到 SQL Server 并执行一个简单的 SqlCommand。 你取得了所有 Price 值>
0  的 title 和 price 数据。你使用 SqlCommand.ExecuteReader 方法返回一个 SqlDataReader 并将其直接绑定到 DataGrid (MyGrid)。
None.gif
None.gif
protected   void  Page_Load( object  sender, EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif  SqlConnection myConnection 
= new SqlConnection("server=Localhost;database=pubs;uid=sa;pwd=;");//创建SQL连接
InBlock.gif
  SqlCommand myCommand = new SqlCommand("SELECT title, price FROM Titles WHERE price > 0", myConnection);//创建SQL命令
InBlock.gif

InBlock.gif  
try
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif    myConnection.Open();
//打开数据库连接
InBlock.gif
    MyGrid.DataSource = myCommand.ExecuteReader();//指定 DataGrid 的数据源
InBlock.gif
    MyGrid.DataBind();//绑定数据到 DataGrid
InBlock.gif
    myConnection.Close();//关闭数据连接
ExpandedSubBlockEnd.gif
  }

InBlock.gif  
catch(Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif    
//捕获错误
InBlock.gif
    HttpContext.Current.Response.Write(ex.ToString());
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

None.gif 
None.gif
None.gifCalcTotals 方法
None.gif
None.gifCalcTotals 方法用来处理 runningTotal 变量。这个值将以字符串形式来传递。 你需要将它解析为双精度型,然后 runningTotal 变量就成了双精度类型。
None.gif
None.gif
private   void  CalcTotal( string  _price)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif  
try
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif    runningTotal 
+= Double.Parse(_price);
ExpandedSubBlockEnd.gif  }

InBlock.gif  
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif     
//捕获错误
ExpandedSubBlockEnd.gif
  }

ExpandedBlockEnd.gif}

None.gif 
None.gif
None.gifMyGrid_ItemDataBound 事件
None.gif
None.gifMyGrid_ItemDataBound 事件在数据源中每行绑定到 DataGrid 时被调用。在这个事件处理中,你可以处理每一行数据。 这里你的目的是,你将需要调用 CalcTotals 方法并从 Price 列传递文本,并用金额型格式化每一行的 Price 列, 并在页脚行中显示 runningTotal 的值。
None.gif
None.gif
public   void  MyDataGrid_ItemDataBound( object  sender, DataGridItemEventArgs e)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif  
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif    CalcTotal( e.Item.Cells[
1].Text );
InBlock.gif    e.Item.Cells[
1].Text = string.Format("{0:c}", Convert.ToDouble(e.Item.Cells[1].Text));
ExpandedSubBlockEnd.gif  }

InBlock.gif  
else if(e.Item.ItemType == ListItemType.Footer )
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif    e.Item.Cells[
0].Text="Total";
InBlock.gif    e.Item.Cells[
1].Text = string.Format("{0:c}", runningTotal);
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

None.gif 
None.gif
None.gif在 MyGrid_ItemDataBound 事件句柄中,首先你得使用 ListItemType 判断当前的 DataGridItem 是一个数据项还是AlternatingItem 行。如果是数据项,你调用 CalcTotals,并将 Price 列的值作为参数传递给它;然后你以金额格式对 Price 列进行格式化及着色。
None.gif
None.gif如果 DataGridItem 是页脚,可以用金额格式显示 runningTotal。
None.gif
None.gif总结
None.gif
None.gif在这份指南中,你学到了怎样使用 DataGrid.OnItemDataBound 事件来实现运行时对DataGrid 的某一列进行统计。使用这个事件,你可以创建一个列的合计并可对DataGrid行的页脚进行着色。 
None.gif
None.gif

使用DataGrid动态绑定DropDownList
None.gif 简单的使用模板列绑定DropDownList,初学者想必都会了,但有时候,我们要做的就是在编辑的时候想让某一列定制为DropDownList,并且根据正常情况下显示的值自动变换DropDownList中所选的值,然后保存选择后的值到数据库或XML文件,其实要做到这样的功能并不难,只要我们学会使用DataGrid的DataGrid1_ItemDataBound事件就行了,跟我来做个例子。
None.gif
None.gif
// 检索数据库的函数
None.gif
public  DataSet GetZcbd()
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif
try
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gifDataSet ds
=new DataSet(); 
InBlock.gif
string searchString="select id,yy,bj from zc";
InBlock.gifda
=new OleDbDataAdapter(searchString,conn);
InBlock.gifda.Fill(ds,
"yy"); 
InBlock.gif
return ds;
ExpandedSubBlockEnd.gif}

InBlock.gif
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
return null
ExpandedSubBlockEnd.gif}
 
ExpandedBlockEnd.gif}

None.gif
None.gif
// 绑定DataGrid 
None.gif
private   void  BindGrid()
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gifDataSet ds 
= new DataSet();
InBlock.gifds 
= us.GetZcbd();
InBlock.gif
if (ds!=null)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
this.DataGrid1.DataSource = ds;
InBlock.gif
this.DataGrid1.DataBind();
ExpandedSubBlockEnd.gif}

InBlock.gif
else
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gifmsg.Alert(
"加载数据错误!",Page);
ExpandedSubBlockEnd.gif}

ExpandedBlockEnd.gif}

None.gif
None.gif绑定好DataGrid以后,设定模板列,让其正常显示下为Label,并绑定为数据库中一ID值,在编辑状态下为DropDownList,并绑定为数据库中一Name值,我们现在要做的就是当我们选择编辑时根据Label的值自动从数据库中取出编号为ID值的姓名,并用DropDownList默认选中。(注释:为了方便大家学习,我给出一个简单代码的例子,供大家参考)
None.gif
None.gif
private   void  DataGrid1_ItemDataBound( object  sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif
if (e.Item.ItemType == ListItemType.EditItem)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gifDataRowView drv 
= (DataRowView)e.Item.DataItem;
InBlock.gif
string current = drv["label1"].ToString();
InBlock.gifDropDownList ddl 
= (DropDownList)e.Item.FindControl("ddl");
InBlock.gifddl.SelectedIndex 
= ddl.Items.IndexOf(ddl.Items.FindByValue(current));
ExpandedSubBlockEnd.gif}

InBlock.gif
if ((e.Item.ItemType == ListItemType.Item)||(e.Item.ItemType == ListItemType.AlternatingItem)) 
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gifLabel t 
= (System.Web.UI.WebControls.Label)e.Item.FindControl("label1");
InBlock.gif
string current = this.BindDDL(int.Parse(t.Text));
InBlock.gife.Item.Cells[
1].Text = current;
ExpandedSubBlockEnd.gif}

ExpandedBlockEnd.gif}

None.gif
None.gif
private   string  BindDDL( int  ddd)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif
string sss = "";
InBlock.gif
if (ddd==1)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gifsss
="张三";
InBlock.gif
return sss;
ExpandedSubBlockEnd.gif}

InBlock.gif
else
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gifsss
="李四";
InBlock.gif
return sss;
ExpandedSubBlockEnd.gif}

ExpandedBlockEnd.gif}

None.gif
None.gif注释:msg为一个类似WinForm的messagebox对话框,不必理会。可以使用label.Text代替
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值