我一直在嘗試使用下面的代碼來創建一個可點擊的GridView:在ASP.NET創建一個可點擊的GridView控件使用C#
using System;
using System.ComponentModel;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CustomGridView
{
/// <summary>
/// Summary description for ClickableGridView
/// </summary>
public class ClickableGridView : GridView
{
public string RowCssClass
{
get
{
string rowClass = (string)ViewState["rowClass"];
if (!string.IsNullOrEmpty(rowClass))
return rowClass;
else
return string.Empty;
}
set
{
ViewState["rowClass"] = value;
}
}
public string HoverRowCssClass
{
get
{
string hoverRowClass = (string)ViewState["hoverRowClass"];
if (!string.IsNullOrEmpty(hoverRowClass))
return hoverRowClass;
else
return string.Empty;
}
set
{
ViewState["hoverRowClass"] = value;
}
}
private static readonly object RowClickedEventKey = new object();
public event GridViewRowClicked RowClicked;
protected virtual void OnRowClicked(GridViewRowClickedEventArgs e)
{
if (RowClicked != null)
RowClicked(this, e);
}
protected override void RaisePostBackEvent(string eventArgument)
{
if (eventArgument.StartsWith("rc"))
{
int index = Int32.Parse(eventArgument.Substring(2));
GridViewRowClickedEventArgs args = new GridViewRowClickedEventArgs(Rows[index]);
OnRowClicked(args);
}
else
base.RaisePostBackEvent(eventArgument);
}
protected override void PrepareControlHierarchy()
{
base.PrepareControlHierarchy();
for (int i = 0; i < Rows.Count; i++)
{
string argsData = "rc" + Rows[i].RowIndex.ToString();
Rows[i].Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(this, argsData));
if (RowCssClass != string.Empty)
Rows[i].Attributes.Add("onmouseout", "this.className='" + RowCssClass + "';");
if (HoverRowCssClass != string.Empty)
Rows[i].Attributes.Add("onmouseover", "this.className='" + HoverRowCssClass + "';");
}
}
}
public class GridViewRowClickedEventArgs : EventArgs
{
private GridViewRow _row;
public GridViewRowClickedEventArgs(GridViewRow aRow)
: base()
{
_row = aRow;
}
public GridViewRow Row
{
get
{ return _row; }
}
}
public delegate void GridViewRowClicked(object sender, GridViewRowClickedEventArgs args);
}
來自:http://aspadvice.com/blogs/joteke/archive/2006/01/07/14576.aspx
我已經把代碼放到一個自定義服務器控件以創建我在主項目中引用的.dll文件。作爲一個簡單的測試,我只是用線
<cgv:ClickableGridView ID = "MyGridView" runat = "server" />
和
MyGridView.DataSource = reader;
MyGridView.DataBind();
才能看到該表將如何樣子了。但是,當我編譯主頁時,我無法顯示任何內容。
這個自定義控件與默認的gridview有什麼不同嗎?上面的代碼顯示了默認的gridview沒有問題,但是當使用clickablegridview時,沒有任何東西顯示出來(沒有編譯錯誤)。
雖然此鏈接可以回答這個問題,最好是在這裏有答案的主要部件,並提供鏈接以供參考。僅鏈接的答案可能會失效,如果鏈接的頁面發生變化,[在meta上閱讀此問題](http://meta.stackexchange.com/questions/143663/why-do-i-get-exactly-the-same-comment逐不同用戶換我的鏈接,只回答) – Vamsi