Pregunta
Cuando hago clic en una fila en mi GridView, quiero ir a otra página con el ID que obtengo de la base de datos.
En mi evento RowCreated tengo la siguiente línea:
e.Row.Attributes.Add(
"onClick",
ClientScript.GetPostBackClientHyperlink(
this.grdSearchResults, "Selectprotected 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<*>quot; + i.ToString()));
}
// Do the standard rendering stuff
base.Render(writer);
}
quot; + e.Row.RowIndex));
Para evitar mensajes de error, tengo este código:
<*>¿Cómo puedo dar a una fila una ID única (desde el DB) y cuando hago clic en la fila, se abre otra página (como hacer clic en un href) y esa página puede leer la ID?
Solución
Tengo la solución.
Esto es lo que he hecho:
if(e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onClick"] = "location.href='view.aspx?id=" + DataBinder.Eval(e.Row.DataItem, "id") + "'";
}
He puesto el código anterior en el evento RowDataBound.
Otros consejos
Martijn,
Aquí hay otro ejemplo con un ingenioso resaltado de filas y un cursor de estilo 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 + "'");
}
}
El código anterior funciona en .NET 3.5. Sin embargo, no puede establecer su columna de identificación en Visible = " false " porque obtendrá un valor de cadena de consulta en blanco para su clave de identificación:
<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>
Entonces cambie la primera columna a esto en su lugar:
<asp:BoundField DataField="id" ItemStyle-CssClass="hide" />
Agregue este CSS a la parte superior de su página:
<head>
<style type="text/css">
.hide{
display:none;
}
</style>
<head>
Pero para ocultar la primera celda de su fila de encabezado, agregue esto a su gvSearch_RowDataBound () en el código subyacente:
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].CssClass = "hide";
}
Obviamente, también podría haber ocultado la columna de identificación en el código subyacente, pero esto dará como resultado más texto en su marcado que una clase css:
e.Row.Cells[0].Attributes.Add("style", "display:none;");
e.Row.Attributes.Add("style", "cursor:pointer;");
protected void gvSearch_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string abc = ((GridView)sender).DataKeys[e.Row.RowIndex].Value.ToString();
e.Row.Attributes["onClick"] = "location.href='Default.aspx?id=" + abc + "'";
}
}
protected void gvSearch_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string abc = ((GridView)sender).DataKeys[e.Row.RowIndex].Value.ToString();
e.Row.Attributes["onClick"] = "location.href='Default.aspx?id=" + abc + "'";
}
}
protected void gvSearch_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridViewRow gvr = e.Row;
string abc = ((GridView)sender).DataKeys[e.Row.RowIndex].Value.ToString();
gvr.Attributes.Add("OnClick", "javascript:location.href='Default.aspx?id=" + abc + "'");
}
}
}
¿Puede su ID estar relacionada con el elemento de datos que se muestra en la vista de cuadrícula?
Si es así, puede usar e.Row.DataItem y convertirlo al tipo que sea.
Puede usar el evento RowCommand de la vista de cuadrícula para ello. En el botón / enlace en el que desea establecer el clic, configure CommandName y CommandArgument, a los que puede acceder en el parámetro EventArgs del método de evento.
clic en la fila en la vista de cuadrícula redirigir a otra página
protected void gvSearch_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string abc = ((GridView)sender).DataKeys[e.Row.RowIndex].Value.ToString();
e.Row.Attributes["onClick"] = "location.href='Default.aspx?id=" + abc + "'";
}
}
funciona absolutamente bien
JohnB, tu código funciona muy bien, agregué solo un pequeño truco para evitar alternar el arruinado de RowStyle después del mouseout.
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=''");
Cambiado a:
e.Row.Attributes.Add("onmouseout", "if(" + e.Row.RowIndex + "% 2 == 0) { this.style.backgroundColor=''; } else { this.style.backgroundColor = '#E8F7EA'; }");
Si hay una mejor manera de hacerlo, hágamelo saber, pero está funcionando perfecto para mí.
Saludos.