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

DataGrid相邻行有相同内容时对指定列合并
/// <summary>
/// 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实现分页不丢失选择的记录
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 窗体设计器生成的代码

  
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控件添加删除按纽后,为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表头合并
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 窗体设计器生成的代码Web 窗体设计器生成的代码
 
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}
 

测试例子中的DataGrid选择了Employees表中的四个字段 
代码如下: 
<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>
DataGrid中使用CheckBox的CheckedChanged事件
使用DataGrid的过程中常会用到CheckBox控件,并使用它的CheckedChanged事件。使用如下:

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中添加一个合计字段
你是否花了很时间来阅读 ASPNG 列表?如果不是的话,我非常推荐它。你可以访问
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
简单的使用模板列绑定DropDownList,初学者想必都会了,但有时候,我们要做的就是在编辑的时候想让某一列定制为DropDownList,并且根据正常情况下显示的值自动变换DropDownList中所选的值,然后保存选择后的值到数据库或XML文件,其实要做到这样的功能并不难,只要我们学会使用DataGrid的DataGrid1_ItemDataBound事件就行了,跟我来做个例子。

//检索数据库的函数
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代替
原文地址:https://www.cnblogs.com/xh831213/p/329451.html