Mar*_*ijn 19 c# gridview click
当我点击GridView中的一行时,我想转到另一个页面,其中包含我从数据库中获取的ID.
在我的RowCreated事件中,我有以下行:
e.Row.Attributes.Add(
"onClick",
ClientScript.GetPostBackClientHyperlink(
this.grdSearchResults, "Select$" + e.Row.RowIndex));
Run Code Online (Sandbox Code Playgroud)
为了防止错误消息我有这个代码:
protected override void Render(HtmlTextWriter writer)
{
// .NET will refuse to accept "unknown" postbacks for security reasons.
// Because of this we have to register all possible callbacks
// This must be done in Render, hence the override
for (int i = 0; i < grdSearchResults.Rows.Count; i++)
{
Page.ClientScript.RegisterForEventValidation(
new System.Web.UI.PostBackOptions(
grdSearchResults, "Select$" + i.ToString()));
}
// Do the standard rendering stuff
base.Render(writer);
}
Run Code Online (Sandbox Code Playgroud)
如何为行添加一个唯一的ID(来自数据库),当我单击该行时,将打开另一个页面(如单击某个href),该页面可以读取该ID.
Joh*_*hnB 20
马亭,
这是另一个带有一些漂亮的行突出显示和一个href样式游标的例子:
protected void gvSearch_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#ceedfc'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=''");
e.Row.Attributes.Add("style", "cursor:pointer;");
e.Row.Attributes.Add("onclick", "location='patron_detail.aspx?id=" + e.Row.Cells[0].Text + "'");
}
}
上面的代码适用于.NET 3.5.但是,您不能将您的id列设置为Visible ="false",因为您将获得id键的空白查询字符串值:
<asp:GridView ID="gvSearch" runat="server" OnRowDataBound="gvSearch_RowDataBound" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="id" Visible="false" />
<asp:BoundField DataField="first_name" HeaderText="First" />
<asp:BoundField DataField="last_name" HeaderText="Last" />
<asp:BoundField DataField="email" HeaderText="Email" />
<asp:BoundField DataField="state_name" HeaderText="State" />
</Columns>
</asp:GridView>
因此,将第一列更改为:
<asp:BoundField DataField="id" ItemStyle-CssClass="hide" />
将此css添加到页面顶部:
<head>
<style type="text/css">
.hide{
display:none;
}
</style>
<head>
但要隐藏标题行的第一个单元格,请将其添加到代码隐藏中的gvSearch_RowDataBound():
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].CssClass = "hide";
}
显然,您也可以在代码隐藏中隐藏id列,但这会导致标记中的文本比css类更多:
e.Row.Cells[0].Attributes.Add("style", "display:none;");
e.Row.Attributes.Add("style", "cursor:pointer;");
小智 19
我有解决方案.
这就是我所做的:
if(e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onClick"] = "location.href='view.aspx?id=" + DataBinder.Eval(e.Row.DataItem, "id") + "'";
}
Run Code Online (Sandbox Code Playgroud)
我已将前面的代码放在RowDataBound事件中.