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代替

DataGrid实现过多信息鼠标移动到记录上显示,可分页
脚本代码
        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的单元格
 datagrid中打开新窗体
DataGrid1.Attributes.Add("onclick","window.open('Print_GoodsMove.aspx?GoodsMove_ID=" + Apply_ID + "','newwindow', 'height=600, width=745, top=100, left=100, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no');"); 
跨页面实现多选
SelectMultiPages.aspx

<%@ 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>

SelectMultiPages.aspx.cs

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 窗体设计器生成的代码    

}

}


如何给DataGrid添加自动增长列
我们用Northwind数据库做例子:
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;
这样一来即使分页,数字也是连续的,并且将编号应用于所有的行而不是当前这一页的行。

在多线程里查询数据库并填充dataGrid
 在查询大数据量时,窗体界面会不动,“正在查询”的提示也不能显示。所以打算用多线程来实现,
可是当在线程里面执行到 
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;
  }


发布了46 篇原创文章 · 获赞 1 · 访问量 11万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章