This is a migrated thread and some comments may be shown as answers.

Filter and edit in place

4 Answers 91 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Pau
Top achievements
Rank 1
Pau asked on 27 May 2011, 10:05 AM
Hello I'm trying to implement an editable grid in place and some filters but it fails. When i filter i need to do Radgri1.Databind() and if i to the binding the update command of the sqldatasorce don't work property. I reed that i have to implemented with advanced databindign but if I do it I don't know how to do the updates without the sqldatasource. Please could you help me.
Thanks in advance

4 Answers, 1 is accepted

Sort by
0
Princy
Top achievements
Rank 2
answered on 27 May 2011, 10:57 AM
Hello Pau,

There is no need to explicitly bind the grid each time after filtering. Since you are using advanced data binding, use the function RadGrid1.Rebind() instead of Radgrid1.Databind(). Hope this information helps you.

Thanks,
Princy.
0
Pau
Top achievements
Rank 1
answered on 27 May 2011, 12:23 PM
Thanks, I tried with Rebind() but not luck.
I tried many things, now i'm completely lost any help will be grateful.
Thanks in advance.
0
Pau
Top achievements
Rank 1
answered on 27 May 2011, 12:52 PM
 Here you have the code, please take a look. Thanks
<h1>Gestión de Usuarios</h1><hr />
    
  <form runat="server" id="mainForm" method="post" action="Usuarios.aspx">
      
    <asp:Literal ID="Filtros" runat="server"/><asp:Button class="sbttn"  Text="Exportar a Excel" runat="server" ID="excel" onclick="excel_Click" ClientIDMode="Static"/><br /><br />
        <telerik:RadScriptManager ID="RadScriptManager1" runat="server"/>
        <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
        <script type="text/javascript">
          
            var hasChanges, inputs, dropdowns, editedRow;
  
            function RowClick(sender, eventArgs) {
                 
                if (editedRow && hasChanges) {
                    hasChanges = false;
                    if (confirm("Aplicar Cambios?")) {
                        $find("<%= RadGrid1.MasterTableView.ClientID %>").updateItem(editedRow);
                    }
                }
                 
            }
  
            function RowDblClick(sender, eventArgs) {
               // $("#excel").attr('disabled', true);
                editedRow = eventArgs.get_itemIndexHierarchical();
                $find("<%= RadGrid1.MasterTableView.ClientID %>").editItem(editedRow);
            }
  
            function GridCommand(sender, args) {
                if (args.get_commandName() != "Edit") {
                    editedRow = null;
                }
            }
  
            function GridCreated(sender, eventArgs) {
                var gridElement = sender.get_element();
                var elementsToUse = [];
                inputs = gridElement.getElementsByTagName("input");
                for (var i = 0; i < inputs.length; i++) {
                    var lowerType = inputs[i].type.toLowerCase();
                    if (lowerType == "hidden" || lowerType == "button") {
                        continue;
                    }
  
                    Array.add(elementsToUse, inputs[i]);
                    inputs[i].onchange = TrackChanges;
                }
  
                dropdowns = gridElement.getElementsByTagName("select");
                for (var i = 0; i < dropdowns.length; i++) {
                    dropdowns[i].onchange = TrackChanges;
                }
  
               //setTimeout(function () { if (elementsToUse[0]) elementsToUse[0].focus(); }, 100);
                  
            }
  
            function TrackChanges(e) {
                hasChanges = true;
            }
         
    </script>
    </telerik:RadCodeBlock>
  
         <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
            <AjaxSettings>
                <telerik:AjaxSetting AjaxControlID="RadGrid1">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="RadGrid1" />
                        <telerik:AjaxUpdatedControl ControlID="Label1" />
                          
                    </UpdatedControls>
                </telerik:AjaxSetting>
            </AjaxSettings>
        </telerik:RadAjaxManager>
        <telerik:RadGrid ID="RadGrid1"  DataSourceID="SqlDataSourceUsuarios" Width="100%"  ShowStatusBar="True" AllowSorting="True" PageSize="14" GridLines="None" AllowPaging="True" runat="server" AllowAutomaticUpdates="True" AutoGenerateColumns="False" OnItemUpdated="RadGrid1_ItemUpdated" >
            <MasterTableView TableLayout="Fixed" DataKeyNames="nusuario" EditMode="InPlace" EnableColumnsViewState="False">
              <Columns>
                <telerik:GridBoundColumn UniqueName="nusuario" DataField="nusuario" HeaderText="Nusuario" ReadOnly="True"  />
                <telerik:GridBoundColumn UniqueName="pass" DataField="pass" HeaderText="Pass" ColumnEditorID="EditText" />
                <telerik:GridBoundColumn UniqueName="nombre" DataField="nombre" HeaderText="Nombre" ColumnEditorID="EditText" />
                <telerik:GridBoundColumn UniqueName="apellidos" DataField="apellidos" HeaderText="Apellidos" ColumnEditorID="EditText" />
                <telerik:GridBoundColumn UniqueName="centro" DataField="centro" HeaderText="Centro" ColumnEditorID="EditText" />
                <telerik:GridBoundColumn UniqueName="codcentro" DataField="codcentro" HeaderText="Codcentro" ColumnEditorID="EditTextPeque" />
                <telerik:GridDropDownColumn UniqueName="tipo" HeaderText="Tipo"  DataField="tipo" ListTextField="tipo" ListValueField="tipo"  DataSourceID="SqlDataSourceTipo" DropDownControlType="RadComboBox"  ColumnEditorID="EditSelect" />
                  
  
              </Columns>
            </MasterTableView>
            <ClientSettings>
                <ClientEvents OnRowClick="RowClick" OnRowDblClick="RowDblClick" OnGridCreated="GridCreated" OnCommand="GridCommand" />
            </ClientSettings>
        </telerik:RadGrid>
            
          <telerik:GridTextBoxColumnEditor ID="EditText" runat="server" TextBoxStyle-Width="100px" />
          <telerik:GridTextBoxColumnEditor ID="EditTextPeque" runat="server" TextBoxStyle-Width="50px" />
          <telerik:GridDropDownListColumnEditor ID="EditSelect" runat="server" DropDownStyle-Width="100px" />
            
        <br />
        <asp:Label ID="Label1" runat="server" EnableViewState="false" />
        <br />
        <asp:SqlDataSource ID="SqlDataSourceUsuarios" runat="server" />
          
        <asp:SqlDataSource ID="SqlDataSourceTipo" runat="server" /> 
          
          
    </form>
    <i>*Haga doble clic sobre el registro que desee modificar</i>
protected void Page_Load(object sender, EventArgs e)
        {
              
  
                Filtros.Text = DibujaFiltros();
                string where = GetFilterText();
                  
  
                SqlDataSourceUsuarios.ConnectionString = Dynamic.Comun.DyConfig.ConnectionString;
                  SqlDataSourceUsuarios.SelectCommand = "SELECT * from usuarios where tipo<>'Finanzas' and tipo<>'Gestion' and " + Dynamic.Comun.DyConfig.NoDemos() + where + " order by nusuario";
                  
      
                SqlDataSourceTipo.ConnectionString = Dynamic.Comun.DyConfig.ConnectionString;
                SqlDataSourceTipo.SelectCommand = "SELECT DISTINCT tipo FROM [usuarios]";
  
                  
                //Columnas RedVentas
                if (DyConfig.SelCodNac) AddColumn("codnac");
                if (DyConfig.SelCodArea) AddColumn("codarea");
                if (DyConfig.SelCodDel) AddColumn("coddel");
                if (DyConfig.SelCodMonitor) AddColumn("codmonitor");
                 
             string sql = string.Empty;
             foreach (GridColumn column in RadGrid1.MasterTableView.Columns)
             {
                    if (column.UniqueName != "nusuario") sql += "," + column.UniqueName + "=@" + column.UniqueName;
                    SqlDataSourceUsuarios.UpdateParameters.Add(column.UniqueName,System.Data.DbType.String,string.Empty);
                    
             }
             SqlDataSourceUsuarios.UpdateCommand = "UPDATE usuarios SET " + sql.Substring(1) + " WHERE nusuario=@nusuario";
  
             if (where != string.Empty) RadGrid1.Rebind();
             
        }
  
        private string DibujaFiltros()
        {
            StringBuilder str = new StringBuilder();
  
            str.Append("<input type='text' name='filtro' size='50' value='" + Request.Form["filtro"] + "'/> ");
            str.Append("<select name='campo'>");
            string req = Request.Form["campo"];
  
            str.Append(FilterField("nusuario", req));
            str.Append(FilterField("pass", req));
            str.Append(FilterField("nombre", req));
            str.Append(FilterField("apellidos", req));
            str.Append(FilterField("centro", req));
            str.Append(FilterField("codcentro", req));
            str.Append(FilterField("tipo", req));
  
            str.Append("</select> <input type='submit' name='fi' value='Filtrar' class='sbttn' /> "); 
            return str.ToString();
        }
  
    
          
        protected void RadGrid1_ItemUpdated(object source, Telerik.Web.UI.GridUpdatedEventArgs e)
        {
            if (e.Exception != null){
                e.KeepInEditMode = true;
                e.ExceptionHandled = true;
                SetMessage(Server.HtmlEncode("Error al actualizar: " + e.Exception.Message).Replace("'", "'").Replace("\r\n", "<br />"));
            }else{
                GridDataItem dataItem = (GridDataItem)e.Item;
                SetMessage(" Nusuario " + dataItem.GetDataKeyValue("nusuario") + " updated");
            }
              
        }
  
  
          
        protected void AddColumn(string campo)
        {
            
            GridBoundColumn boundColumn = new GridBoundColumn();
            boundColumn.HeaderText = campo.Substring(0, 1).ToUpper() + campo.Substring(1); ;
            boundColumn.DataField = campo;
            boundColumn.UniqueName = campo;
            boundColumn.ColumnEditorID = "EditText";
            RadGrid1.MasterTableView.Columns.Add(boundColumn);
        }
  
  
        private void DisplayMessage(string text)
        {
            Label1.Text = string.Format("<span>{0}</span>", text);
        }
  
        private void SetMessage(string message)
        {
            gridMessage = message;
        }
  
        protected void RadGrid1_DataBound(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(gridMessage)) DisplayMessage(gridMessage);
        }
  
        protected void excel_Click(object sender, EventArgs e)
        {
            Dynamic.Logica.Gestion.DyExportExcel xls = new Dynamic.Logica.Gestion.DyExportExcel();
  
            xls.Campos = "*"; //nusuario,pass,nombre,apellidos,coddel
            xls.CamposExcluir = "pass";
            xls.Tabla = "Usuarios";
            xls.Where = "Where " + Dynamic.Comun.DyConfig.NoDemos() + GetFilterText();
            xls.Exportar(Server.MapPath("."));
            Response.ContentType = "text/plain";
            Response.AppendHeader("Content-Disposition", "attachment; filename=usuarios.xls");
            Response.TransmitFile(xls.Ruta);
            Response.End();
        }
  
  
        private string GetFilterText()
        {
              
            string where = string.Empty;
            if (!string.IsNullOrEmpty(Request.Form["filtro"]))
            {
                //Para el excel
                where = " and " + Request.Form["campo"] + " like '" + Request.Form["filtro"] + "%'";
                 
            }
            return where;
              
        }
  
        private string FilterField(string campo, string req)
        {
            string sel = string.Empty;
            if (req == campo) sel = " selected='selected'";
            return "<option value='"+ campo +"' " + sel +">" + campo +"</option>";
        }

0
Pau
Top achievements
Rank 1
answered on 07 Jun 2011, 03:36 PM
I still waiting for a solutions, any help will be appreciated.
Thanks in advance
Tags
Grid
Asked by
Pau
Top achievements
Rank 1
Answers by
Princy
Top achievements
Rank 2
Pau
Top achievements
Rank 1
Share this question
or