(原创)为DataGrid添加自定义DataGridColumn类的例子

该博客为转载内容,转载自https://www.cnblogs.com/lovecherry/archive/2005/05/01/148504.html ,未提及具体信息技术相关关键信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

column.jpg

DataGrid的模板列可以方便的定制所需要的样式,比如上图:
在编辑状态的时候学院是下拉框,选择了当前的学院,但是如果学院很多,下拉框会很长,找起来也会很麻烦,所以可能需要再增加一个查找的功能。这样一个列完全可以通过模板列来实现,可是如果项目中有很多这样的需求,添加这么多复杂的模板列一来很麻烦,二来也有代码冗余,没有重用性,为此,我们可以尝试定制自己的DataGridColumn(类似已经存在的HyperLinkColumn)来为这个列进行小小的封装。

先建立一个类文件:
None.gifusing System;
None.gif
using System.Data;
None.gif
using System.Web.UI;
None.gif
using System.Web.UI.WebControls;
None.gif
None.gif
namespace csdn
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
public class MyColumn:DataGridColumn
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
public string DataTextField;
InBlock.gif        
public string DataValueField;
InBlock.gif        
public DataTable DataSource;
InBlock.gif                        
InBlock.gif        
public override void InitializeCell(TableCell cell,int columnIndex,ListItemType itemType)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
base.InitializeCell(cell,columnIndex,itemType);
InBlock.gif            
switch(itemType)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
case ListItemType.Header:
InBlock.gif                    cell.Text
=this.HeaderText;
InBlock.gif                    
break;
InBlock.gif                
case ListItemType.Item:case ListItemType.AlternatingItem:
InBlock.gif                    cell.DataBinding
+=new EventHandler(this.cell_ItemDataBinding);
InBlock.gif                    
break;
InBlock.gif                
case ListItemType.EditItem:
InBlock.gif                    cell.DataBinding 
+=new EventHandler(cell_EditItemDataBinding);
InBlock.gif                    DropDownList ddl
=new DropDownList();
InBlock.gif                    cell.Controls.Add(ddl);
InBlock.gif                    TextBox t
=new TextBox();
InBlock.gif                    t.Width
=80;
InBlock.gif                    cell.Controls.Add(t);
InBlock.gif                    Button b
=new Button();
InBlock.gif                    b.Text
="查找";
InBlock.gif                    b.Click
+=new EventHandler(this.btn_Click);
InBlock.gif                    cell.Controls.Add(b);
InBlock.gif                    
break;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void cell_ItemDataBinding(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            TableCell cell
=(TableCell)sender;
InBlock.gif            DataGridItem dgi
=(DataGridItem)cell.NamingContainer;
InBlock.gif            cell.Text
=(DataBinder.Eval(dgi.DataItem,this.DataTextField)).ToString();
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void cell_EditItemDataBinding(object sender,EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            TableCell cell
=(TableCell)sender;
InBlock.gif            DropDownList ddl
=(DropDownList)cell.Controls[0];
InBlock.gif            DataGridItem dgi
=(DataGridItem)cell.NamingContainer;
InBlock.gif            
for(int i=0;i<this.DataSource.Rows.Count;i++)
InBlock.gif                ddl.Items.Add(
new ListItem(this.DataSource.Rows[i][this.DataTextField].ToString(),this.DataSource.Rows[i][this.DataValueField].ToString()));
InBlock.gif            ddl.Items.FindByValue((DataBinder.Eval(dgi.DataItem,
this.DataValueField)).ToString()).Selected=true;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void btn_Click(object sender,EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            TableCell cell
=(TableCell)(((Button)sender).Parent);
InBlock.gif            DropDownList ddl
=(DropDownList)cell.Controls[0];
InBlock.gif            TextBox t
=(TextBox)cell.Controls[1];
InBlock.gif            DataGridItem dgi
=(DataGridItem)cell.NamingContainer;
InBlock.gif            ListItem li
=ddl.Items.FindByText(t.Text);
InBlock.gif            
if(li!=null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                ddl.SelectedIndex
=-1;
InBlock.gif                li.Selected
=true;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

然后为页面添加这个自定义列:
ExpandedBlockStart.gifContractedBlock.gif<%dot.gif@ Page language="c#" Codebehind="WebForm67.aspx.cs" AutoEventWireup="false" Inherits="csdn.WebForm67" %>
ExpandedBlockStart.gifContractedBlock.gif
<%dot.gif@ Register TagPrefix="MyDataGridColumn" Assembly="csdn" NameSpace="csdn"%>
None.gif
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
None.gif
<HTML>
None.gif    
<HEAD>
None.gif        
<title>Test</title>
None.gif        
<META http-equiv="Content-Type" content="text/html; charset=gb2312">
None.gif        
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
None.gif        
<meta content="C#" name="CODE_LANGUAGE">
None.gif        
<meta content="JavaScript" name="vs_defaultClientScript">
None.gif        
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
None.gif        
<LINK href="css.css" type="text/css" rel="stylesheet">
None.gif    
</HEAD>
None.gif    
<body>
None.gif        
<form id="Form1" method="post" runat="server">
None.gif            
<asp:datagrid id="DataGrid1" runat="server" DataKeyField="stuid" CellSpacing="1" BorderWidth="0px"
None.gif                OnEditCommand
="edit" OnCancelCommand="cancel" OnUpdateCommand="update" CellPadding="5" CssClass="border"
None.gif                AutoGenerateColumns
="False">
None.gif                
<ItemStyle CssClass="item"></ItemStyle>
None.gif                
<HeaderStyle CssClass="header"></HeaderStyle>
None.gif                
<Columns>
None.gif                    
<asp:BoundColumn HeaderText="姓名" DataField="stuname"></asp:BoundColumn>
None.gif                    
<MyDataGridColumn:MyColumn HeaderText="学院" DataTextField="depname" DataValueField="depid"></MyDataGridColumn:MyColumn>
None.gif                    
<asp:EditCommandColumn ButtonType="PushButton" UpdateText="更新" CancelText="取消" EditText="编辑"></asp:EditCommandColumn>
None.gif                
</Columns>
None.gif            
</asp:datagrid>
None.gif        
</form>
None.gif    
</body>
None.gif
</HTML>
None.gif

后台代码如下:
None.gifusing System;
None.gif
using System.Collections;
None.gif
using System.ComponentModel;
None.gif
using System.Data;
None.gif
using System.Data.SqlClient;
None.gif
using System.Drawing;
None.gif
using System.Web;
None.gif
using System.Web.SessionState;
None.gif
using System.Web.UI;
None.gif
using System.Web.UI.WebControls;
None.gif
using System.Web.UI.HtmlControls;
None.gif
None.gif
namespace csdn
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
/// WebForm67 的摘要说明。
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    public class WebForm67 : System.Web.UI.Page
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
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            
// 在此处放置用户代码以初始化页面
InBlock.gif
            if(!IsPostBack)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                SetBind();
ExpandedSubBlockEnd.gif            }
            
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
protected void SetBind()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            SqlConnection conn
=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
InBlock.gif            SqlDataAdapter da
=new SqlDataAdapter("select * from stu,dep where stu.studepid=dep.depid",conn);
InBlock.gif            DataSet ds
=new DataSet();
InBlock.gif            da.Fill(ds);
InBlock.gif            
this.DataGrid1.DataSource=ds.Tables[0];
InBlock.gif            
this.DataGrid1.DataBind();            
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
protected void edit(object sender,DataGridCommandEventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
this.DataGrid1.EditItemIndex=e.Item.ItemIndex;
InBlock.gif            SetBind();
InBlock.gif            
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
protected void cancel(object sender,DataGridCommandEventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
this.DataGrid1.EditItemIndex=-1;
InBlock.gif            SetBind();
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
protected void update(object sender,DataGridCommandEventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if(e.Item.ItemType==ListItemType.EditItem)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                SqlConnection conn
=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
InBlock.gif                SqlCommand comm
=new SqlCommand("update stu set stuname=@name,studepid=@depid where stuid=@id",conn);
InBlock.gif                SqlParameter parm1
=new SqlParameter("@name",SqlDbType.NVarChar,50);
InBlock.gif                parm1.Value
=((TextBox)e.Item.Cells[0].Controls[0]).Text;
InBlock.gif                SqlParameter parm2
=new SqlParameter("@depid",SqlDbType.Int);
InBlock.gif                parm2.Value
=((DropDownList)e.Item.Cells[1].Controls[0]).SelectedValue;
InBlock.gif                SqlParameter parm3
=new SqlParameter("@id",SqlDbType.Int);
InBlock.gif                parm3.Value
=this.DataGrid1.DataKeys[e.Item.ItemIndex];
InBlock.gif                comm.Parameters.Add(parm1);
InBlock.gif                comm.Parameters.Add(parm2);
InBlock.gif                comm.Parameters.Add(parm3);
InBlock.gif                conn.Open();
InBlock.gif                comm.ExecuteNonQuery();
InBlock.gif                conn.Close();
InBlock.gif                
this.DataGrid1.EditItemIndex=-1;
InBlock.gif                SetBind();
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.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.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemDataBound);
InBlock.gif            
this.Load += new System.EventHandler(this.Page_Load);
InBlock.gif
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
InBlock.gif        
private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            SqlConnection conn
=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
InBlock.gif            SqlDataAdapter da
=new SqlDataAdapter("select * from dep",conn);
InBlock.gif            DataSet ds
=new DataSet();
InBlock.gif            da.Fill(ds);
InBlock.gif            ((MyColumn)
this.DataGrid1.Columns[1]).DataSource=ds.Tables[0];
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

这个例子可能稍微复杂了点(列中放了3个控件),但是原理比较简单,其实简化一下,我们可以封装自己的DropDownListColumn、CheckBoxColumn等单控件列。

转载于:https://www.cnblogs.com/lovecherry/archive/2005/05/01/148504.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值