Question

Lorsque je clique sur une ligne de mon GridView, je souhaite accéder à une autre page avec l'ID obtenu dans la base de données.

Dans mon événement RowCreated, j'ai la ligne suivante:

e.Row.Attributes.Add(
     "onClick",
     ClientScript.GetPostBackClientHyperlink(
          this.grdSearchResults, "Select
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<*>quot; + i.ToString()));
    }
    // Do the standard rendering stuff
    base.Render(writer);
}
quot; + e.Row.RowIndex));

Pour éviter les messages d'erreur, j'ai ce code:

<*>

Comment puis-je attribuer un ID unique à une ligne (à partir de la base de données) et lorsque je clique sur cette ligne, une autre page est ouverte (par exemple, un clic sur un href) et cette page peut lire l'ID.

Était-ce utile?

La solution

J'ai la solution.

C’est ce que j’ai fait:

if(e.Row.RowType == DataControlRowType.DataRow)
{
    e.Row.Attributes["onClick"] = "location.href='view.aspx?id=" + DataBinder.Eval(e.Row.DataItem, "id") + "'";
}

J'ai mis le code précédent dans l'événement RowDataBound.

Autres conseils

Martijn,

Voici un autre exemple avec quelques jolies lignes en surbrillance et un curseur de style 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 + "'");
  }
}

Le code ci-dessus fonctionne dans .NET 3.5. Toutefois, vous ne pouvez pas définir votre colonne id sur Visible = " false " parce que vous obtiendrez une valeur de chaîne de requête vide pour votre clé d'identification:

<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>

Changez donc la première colonne en ceci:

<asp:BoundField DataField="id" ItemStyle-CssClass="hide" />

Ajoutez ce css en haut de votre page:

<head>
  <style type="text/css">
    .hide{
      display:none;
    }
  </style>
<head>

Mais pour masquer la première cellule de votre ligne d'en-tête, ajoutez ceci à votre gvSearch_RowDataBound () dans code-behind:

if (e.Row.RowType == DataControlRowType.Header)
{
  e.Row.Cells[0].CssClass = "hide";
}

Évidemment, vous auriez également pu masquer la colonne id dans code-behind, mais cela entraînera plus de texte dans votre balisage qu'une classe 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 + "'");
        }         

   }  
}  

Votre identifiant peut-il être associé à l'élément de données affiché dans la vue en grille?

Si c'est le cas, vous pouvez utiliser e.Row.DataItem et le convertir en n'importe quel type.

Vous pouvez utiliser l'événement RowCommand de la vue en grille. Dans votre bouton / lien où vous souhaitez définir le clic, définissez CommandName et CommandArgument, que vous pouvez accéder au paramètre EventArgs de la méthode de l'événement.

la ligne en cliquant sur la grille redirige vers une autre page fonctionne tout à fait bien

JohnB, votre code fonctionne très bien, j’ai ajouté juste un petit bidouillage pour éviter que AlternatingRowStyle ne ruine après mouseout.

e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=''");

changé en:

e.Row.Attributes.Add("onmouseout", "if(" + e.Row.RowIndex + "% 2 == 0) { this.style.backgroundColor=''; } else { this.style.backgroundColor = '#E8F7EA'; }");

S'il existe un meilleur moyen de le faire, faites-le-moi savoir, mais cela fonctionne parfaitement pour moi.

Salutations.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top