20/4/09

Grids en asp.net

En el pageload

if (!IsPostBack) {
PrepararGrid();
}
private void PrepararGrid() {
this.GridView1.DataKeyNames = { "Codigo" };//lista de campos que forman la clave primaria

this.SqlDataSource.SelectCommand = “Select Codigo, nombre from tabla”;// Consulta para rellenar el grid

//Añadir las columnas y botones
UtilWeb.AnadirColumnaText(this.GridView1, "nombre", "NOMBRE");
UtilWeb.AnadirColumnaBoton(this.GridView1, “AnadirAGenerarDat”, "Generar Fichero Dat");
UtilWeb.AnadirColumnaBoton(this.GridView1, “VerEquiposServidor”, "Ver Equipos");
}

public static void AnadirColumnaBoton(GridView gv, string Comando, string TextoBoton) {
ButtonField btnf;
btnf = new ButtonField();
btnf.ButtonType = ButtonType.Button;
btnf.CommandName = Comando;
btnf.HeaderText = "";
btnf.Text = TextoBoton;
gv.Columns.Add(btnf);
}

public static void AnadirColumnaText(GridView gv, string Campo, string Cabecera, bool visible) {
BoundField bf;
bf = new BoundField();
bf.DataField = Campo;
bf.HeaderText = Cabecera;
bf.ReadOnly = true;
bf.Visible = visible;
gv.Columns.Add(bf);
}
public static void AnadirColumnaText(GridView gv, string Campo, string Cabecera) {
AnadirColumnaText(gv, Campo, Cabecera, true);
}

Al pulsar los botones que hemos añadido al grid se ejecuta el “RowCommand”.

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) {
// el e tiene:
//e.CommandArgument : La posicion en la que se ha pulsado el botón
//e.CommandName : El nombre del comando ”Lo hemos dado al crear el botón”
//e.CommandSource

int position = Convert.ToInt32(e.CommandArgument);
DataKey dk = this.GridView1.DataKeys[position];
decimal ServidorId = Convert.ToDecimal(dk.Value);// Si es una clave con varios campos dk.Values[X]

switch (e.CommandName) {
case “AnadirAGenerarDat”: {
//Acción con el botón correspondiente
break;
}
case “VerEquiposServidor”: {
//Acción con el botón correspondiente
break;
}
}
}