6
votes

Comment accéder à une colonne GridView sur Rowdatabound?

Je voudrais changer la valeur de ma colonne GridView en actif lorsque la valeur est 1. J'ai une colonne GridView comme xxx

et cs code xxx

Ceci fonctionne, mais cela échouerait si je modifie la commande de colonne. Ce dont j'ai besoin, c'est quelque chose comme la fonction de FindControl. Merci.


0 commentaires

3 Réponses :


3
votes

Vous pouvez boucler toutes les colonnes pour obtenir l'index correct ou utiliser ce LINQ:

String colToFind = "status";
int colIndex = ((GridView)sender).Columns.Cast<DataControlField>()
                .Where((c, index) => c.HeaderText.ToLower().Equals(colToFind))
                .Select((c,index)=>index).First();


0 commentaires

18
votes

Voici quelques utilitaires que j'ai écrites il y a des années qui peuvent vous aider:

// ---- GetCellByName ----------------------------------
//
// pass in a GridViewRow and a database column name 
// returns a DataControlFieldCell or null

static public DataControlFieldCell GetCellByName(GridViewRow Row, String CellName)
{
    foreach (DataControlFieldCell Cell in Row.Cells)
    {
        if (Cell.ContainingField.ToString() == CellName)
            return Cell;
    }
    return null;
}

// ---- GetColumnIndexByHeaderText ----------------------------------
//
// pass in a GridView and a Column's Header Text
// returns index of the column if found 
// returns -1 if not found 

static public int GetColumnIndexByHeaderText(GridView aGridView, String ColumnText)
{
    TableCell Cell;
    for (int Index = 0; Index < aGridView.HeaderRow.Cells.Count; Index++)
    {
        Cell = aGridView.HeaderRow.Cells[Index];
        if (Cell.Text.ToString() == ColumnText)
            return Index;
    }
    return -1;
}

// ---- GetColumnIndexByDBName ----------------------------------
//
// pass in a GridView and a database field name
// returns index of the bound column if found 
// returns -1 if not found 

static public int GetColumnIndexByDBName(GridView aGridView, String ColumnText)
{
    System.Web.UI.WebControls.BoundField DataColumn;

    for (int Index = 0; Index < aGridView.Columns.Count; Index++)
    {
        DataColumn = aGridView.Columns[Index] as System.Web.UI.WebControls.BoundField;

        if (DataColumn != null)
        {
            if (DataColumn.DataField == ColumnText)
                return Index;
        }
    }
    return -1;
}


2 commentaires

Pour la première fonction getcellbyname , qui devrait être appelé que lorsque c'est le type de ligne d'en-tête: e.row.rowtype == DataControlrowtType.header


@Davidfreitas ne le pense pas. Il utilise le datacontrolfrolfield d'une cellule donnée.



0
votes

Nettoyant plus facile à lire Linq. Tim n'a pas fonctionné pour moi. XXX


0 commentaires