我有一个继承GridView的自定义控件。 我又写了一个继承BoundField的类来创建一个将图像显示到ButtonClick控件中的列。 当我点击它时,这个“图像列”会引发一个事件。 在第一个GridView自定义控件中,我绑定了“图像列单击”事件。它永远不会被解雇。
图片列代码:
using System.Web.UI;
using System.Web.UI.WebControls;
using WebControls.Infrastructure;
namespace WebControls
{
public class DataSearchGridImageColumn : BoundField
{
public event StringDelegate ImageClicked;
public string ImageUrl
{
get
{
return (string)ViewState["ImageUrl"] ?? string.Empty;
}
set
{
ViewState["ImageUrl"] = value;
}
}
protected override void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState)
{
var img = new ImageButton
{
ID = "ImgSelectRecord",
ImageUrl = ImageUrl,
};
cell.Controls.Add(img);
img.Click += ImgClick;
}
void ImgClick(object sender, ImageClickEventArgs e)
{
var img = sender as ImageButton;
if (img == null) return;
var row = (GridViewRow)img.NamingContainer;
if (row == null) return;
// get the id
var id = row.Cells[1].Text;
// raise an event
OnClick(id);
}
protected virtual void OnClick(string id)
{
if (ImageClicked != null)
{
ImageClicked(this, id);
}
}
}
}
我绑定事件的数据视图自定义控制代码:
protected override void OnDataBinding(EventArgs e)
{
// create a new page because the Page object is null in this context
var pg = new Page();
var selectionColumn = new DataSearchGridImageColumn
{
ImageUrl = string.Format(
"url({0})",
pg.ClientScript.GetWebResourceUrl(GetType(), "WebControls.Images.search.png"))
};
Columns.Clear();
Columns.Add(selectionColumn);
Columns.Add(CreateColumn(ValueFieldName, ValueFieldName));
Columns.Add(CreateColumn(TextFieldName, TextFieldName));
AutoGenerateColumns = false;
selectionColumn.ImageClicked += SelectionColumnImageClicked;
base.OnDataBinding(e);
}
void SelectionColumnImageClicked(object sender, string value)
{
if (RowSelected != null)
RowSelected(this, value);
}