skinid net example editar editable bootstrap asp asp.net gridview

example - gridview asp.net vb



ASP.Net Gridview, Cómo activar el modo de edición basado en ID(DataKey) (2)

Tengo una página, vamos a llamarla SourceTypes.aspx, que tiene una GridView que muestra una lista de tipos de fuentes. Parte de GridView es un DataKey, SourceTypeID. Si SourceID TypeID se pasa a la página a través de una interrogación, ¿cómo pongo el Gridview en el modo de edición para la fila apropiada basada en SourceTypeID?

El GridView está vinculado a un objeto SQlDataSource.

¡Tengo la sensación de que voy a patearme cuando aparezca la respuesta!

He visto poner una fila gridview en modo de edición programáticamente, pero es algo que carece de detalles


Es un poco más complicado cuando quiere ponerlo en modo de edición basado en datos. Le dice a la cuadrícula de datos cuál de las filas que se muestran es editable, no qué datos desea que sean editables, por lo que deberá recorrer cada una de las filas de la grilla, ver si coincide con la identificación, y establecer EditItemIndex en el valor apropiado y rebind.

Puede ver los datos de origen y obtener el número de fila de eso antes de vincular, pero luego puede tener problemas con paginación, clasificación, etc.

Es un poco complicado tener que volver a enlazar la cuadrícula, pero no puedo pensar en una mejor manera de salir de mi cabeza.

public partial class _Default : System.Web.UI.Page { private DataTable GetData() { DataTable tTable = new DataTable(); tTable.Columns.Add(new DataColumn("Column1", typeof(int))); tTable.Columns.Add(new DataColumn("Column2", typeof(string))); DataRow tRow = tTable.NewRow(); tRow["Column1"] = 1; tRow["Column2"] = "Test1"; tTable.Rows.Add(tRow); tRow = tTable.NewRow(); tRow["Column1"] = 2; tRow["Column2"] = "Test2"; tTable.Rows.Add(tRow); tRow = tTable.NewRow(); tRow["Column1"] = 3; tRow["Column2"] = "Test3"; tTable.Rows.Add(tRow); tRow = tTable.NewRow(); tRow["Column1"] = 4; tRow["Column2"] = "Test4"; tTable.Rows.Add(tRow); tRow = tTable.NewRow(); tRow["Column1"] = 5; tRow["Column2"] = "Test5"; tTable.Rows.Add(tRow); return tTable; } private void BindData() { DataTable tTable = GetData(); TestGrid.DataSource = tTable; TestGrid.DataBind(); if (!String.IsNullOrEmpty(Request.QueryString["edit"])) { foreach (DataGridItem tRow in TestGrid.Items) { if (tRow.Cells[0].Text == Request.QueryString["edit"]) TestGrid.EditItemIndex = tRow.ItemIndex; } TestGrid.DataBind(); } } protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) BindData(); } }

Debería poder activarlo (con una cuadrícula de datos añadida a ASPX obviamente) luego colocar? Edit = en el final de la URL para que abra la entrada relevante en el modo de edición.


Antes que nada, muchas gracias a Steve Robins por ayudarme a comenzar por el camino correcto. Mi enfoque fue ligeramente diferente, parcial debido al hecho de que no estaba usando un método DataBind.

Uso una combinación de los eventos OnRowDataBound y OnDataBound de DataView. El evento OnRowDataBound para determinar el índice de la fila que se colocará en el modo de edición. El evento OnDataBound establece el índice y vuelve a enlazar el DataView.

Se usa una variable para asegurar que la Vista no rebote continuamente.

Aquí está el quid de la página aspx editada para abreviar.

<asp:GridView ID="GridView1" runat="server" DataSourceID="CreativeTypeDS" AutoGenerateColumns="False" DataKeyNames="SourceCreativeTypeID" EmptyDataText="No Cretive Types at this time." CellPadding="3" CellSpacing="1" OnRowDataBound="GridView1_RowDataBound" OnDataBound="GridView1_DataBound" > <Columns> [Template Columns Here] </Columns> </asp:GridView> <asp:SqlDataSource ID="CreativeTypeDS" runat="server" SelectCommand="cmsSourceCreativeTypeSel" SelectCommandType="StoredProcedure" UpdateCommand="cmsSourceCreativeTypeUpd" UpdateCommandType="StoredProcedure"> <SelectParameters> <asp:Parameter Name="Active" DefaultValue="0" /> </SelectParameters> <UpdateParameters> <asp:Parameter Name="SourceCreativeTypeID" Type="Int32" /> <asp:Parameter Name="SourceCategoryID" Type="Int32"/> <asp:Parameter Name="Name" Type="String" /> <asp:Parameter Name="Active" Type="Boolean" /> </UpdateParameters> </asp:SqlDataSource>

Y ahora para el código detrás.

public partial class SourceCreativeTypes : System.Web.UI.Page { private int? EditIndex = null; private bool GridRebound = false; protected override void OnPreInit(EventArgs e) { CreativeTypeDS.ConnectionString = "[CONNECTION STRING MAGIC HERE]"; } protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { //Dont Want to set edit row manualy if post back GridRebound = true; } } //Use the Row Databound Event to find the row to put into edit mode protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (!String.IsNullOrEmpty(Request.QueryString["ID"])) { //Get Target ID from Query String string sSourceCreativeTypeID = Request.QueryString["ID"]; //Get data for row being bound DataRowView rowView = (DataRowView)e.Row.DataItem; // Set index if we are in a "normal row", the row data // has been retrieved // and the Supplied ID matches that of this row if ((e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate) && (rowView != null && rowView["SourceCreativeTypeID"].ToString() == sSourceCreativeTypeID) ) { EditIndex = e.Row.RowIndex; } } } /* Use the Datbound Event to set the required row to index mode * Then Rebind the grid. Rebinding in Row Databound does not work * for Reasons unknown */ protected void GridView1_DataBound(object sender, EventArgs e) { //Set Gridview edit index if one is supplied and page is not a post back if (!GridRebound && EditIndex != null) { //Setting GridRebound ensures this only happens once GridRebound = true; GridView1.EditIndex = (int)EditIndex; GridView1.DataBind(); } } } }

Con suerte, entre Steve y yo ayudamos a algunos de ustedes allá afuera