locked
Adding TemplateField To SPGridView RRS feed

  • Question

  • Hello, I have a problems to add radio button to spgridview (in a webpart). I have seen all sites that explaining using TemplateField but I don't found what I like to do.
    In my webpart, I have a first spgridview which displaying data from List. After, I added radio button to each row of my grid with only one selection. After user selecting one radio, I generate a second spgridview which depends of seleted radio button value's.

    I can see my spgridviews and I can filtering data depending of the value of radio button. But, I found some problems :

    1- When there is a post back (sort, pagination) : I lost the last selected value of my first grid. I don't understand why!
        When there is a post back (selecting radio) : I can see the last selected value.

    My question how can I persist all time the last selected radio ?

    2 - Another problem : the value of my radios buttons in don't change after sorting my spgrid !!!! I have written a databound method but the values don't change :
    for example I have a first a column displaying radio and the second column displaying the noun of the project. I bind the value of project in radio (value after implementing a new class extending RadioButton, and I added a new property "value").
    We suppose that I have 3 rows : project 1, project 2, project 3. When I make a sort : project 3, project 2, project 1 the first radio value's is project 1 !!!

    Sincerly, I hope that you can help me because I spent much time to code this solution and I don't have finished yet.

    This is the code of the Itemplate Class :
    using System;
    using System.Runtime.InteropServices;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    
    using System.Xml.Serialization;
    using System.Data;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.WebControls;
    using Microsoft.SharePoint.WebPartPages;
    
    namespace ProjetSPGridView
    {
    
        public class RadioButtonTemplateField : ITemplate
        {
            private DataControlRowType templateType;
            private string columnName;
            private ProjetSPGridView form;
            public RadioButtonTemplateField(DataControlRowType type, string colname,ProjetSPGridView po)
            {
                templateType = type;
                columnName = colname;
                form = po;
            }
    
            public void InstantiateIn(System.Web.UI.Control container)
            {
                // Create the content for the different row types.
                switch (templateType)
                {
                    case DataControlRowType.Header:
                        // Create the controls to put in the header
                        // section and set their properties.
                        Literal lc = new Literal();
                        lc.Text = "<b>" + columnName + "</b>";
    
                        // Add the controls to the Controls collection
                        // of the container.
                        container.Controls.Add(lc);
                        break;
                    case DataControlRowType.DataRow:
                        // Create the controls to put in a data row
                        // section and set their properties.
                        CustomRadioButton m_rb = new CustomRadioButton();
    
                        // To support data binding, register the event-handling methods
                        // to perform the data binding. Each control needs its own event
                        // handler.
                        m_rb.EnableViewState = true;
                        m_rb.ID = "rb1";
                        m_rb.AutoPostBack = true;
                        m_rb.CheckedChanged += new EventHandler(m_rb_CheckedChanged);
                        m_rb.DataBinding += new EventHandler(m_br_DataBinding);
                       // m_rb.DataBind();
    
                        // Add the controls to the Controls collection
                        // of the container.
                        container.Controls.Add(m_rb);
                       
                        break;
    
                    // Insert cases to create the content for the other 
                    // row types, if desired.
    
                    default:
                        // Insert code to handle unexpected values.
                        break;
                }
            }
    
            void m_br_DataBinding(object sender, EventArgs e)
            {
                
                CustomRadioButton l = (CustomRadioButton)sender;
               
                // Get the GridViewRow object that contains the Label control. 
                GridViewRow row = (GridViewRow)l.NamingContainer;
    
                // Get the field value from the GridViewRow object and 
                // assign it to the Text property of the Label control.
                l.Value = DataBinder.Eval(row.DataItem, "Nom_x0020_Projet").ToString();
               
            }
    
           
            private void m_rb_CheckedChanged(object sender, EventArgs e)
            {
                CustomRadioButton rb = (CustomRadioButton)sender;
                rb.DataBind();
                SPGridViewRow container = (SPGridViewRow)rb.NamingContainer;
                SPGridView dg = (SPGridView)container.Parent.Parent;
                Page Page = dg.Parent.Page;
    
                CustomRadioButton rbgrid;
                Page.Response.Write(" RB Value "+rb.Value);
                string str = rb.Value;
                for (int i = 0; i < dg.Rows.Count; i++)
                {
                    rbgrid = (CustomRadioButton)dg.Rows[i].FindControl("rb1");
                    rbgrid.Checked = false;
                    if (str == rbgrid.Value)
                    {
                        rbgrid.Checked = true;
                        TextBox tt = new TextBox();
                        tt.Text = rbgrid.Value;
                        form.globalProjet = tt.Text;
    
                        form.objSPGridViewInter.Columns.Clear();
    
                        DataTable dt1 = new DataTable();
    
                        form.GetDataTable1(ref dt1);
    
                        form.oView1 = new DataView(dt1);
                        form.objSPGridViewInter.DataSource = form.oView1;
                        
                        BoundField colTitle;
                        
                        if (dt1 != null)
                        {
                            
                            for (int j = 0; j < dt1.Columns.Count; j++)
                            {
                                if ((!dt1.Columns[j].ColumnName.Equals("ID")) && (!dt1.Columns[j].ColumnName.Equals("Created")))
                                {
                                    colTitle = new BoundField();
                                    colTitle.DataField = dt1.Columns[j].ColumnName;
                                    colTitle.HeaderText = dt1.Columns[j].Caption;
                                    colTitle.SortExpression = dt1.Columns[j].ColumnName;
                                    form.objSPGridViewInter.Columns.Add(colTitle);
                                }
                            }
                            
                        }
                        //form.objSPGridViewInter.DataSource = form.oView1;
                        form.objSPGridViewInter.DataBind();
                       
                    }
                }
    
            }
           
        }
    
    
    }
    
    
    
    The code of my webpart :
    
    using System;
    using System.Runtime.InteropServices;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Serialization;
    using System.Data;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.WebControls;
    using Microsoft.SharePoint.WebPartPages;
    
    
    
    namespace ProjetSPGridView
    {
        public class ProjetSPGridView : System.Web.UI.WebControls.WebParts.WebPart
        {
            public DataView oView;
            public DataView oView1;
    
            public SPGridView objSPGridView;
            public SPGridView objSPGridViewInter;
    
            public Panel vueProjet;
            public Panel vueIntervention;
    
            public  string globalProjet=null;
    
            protected override void OnInit(EventArgs e)
            {
                base.OnInit(e);
                vueProjet = new Panel();
                vueIntervention = new Panel();
    
                //this.EnableViewState = false;
    
                #region Vue des projets
                objSPGridView = new SPGridView();
                objSPGridView.ID = "SPGridViewWP";
                objSPGridView.AutoGenerateColumns = false;
                objSPGridView.EmptyDataText = "Aucun élément disponible à afficher";
                objSPGridView.AllowSorting = true;
    
                //objSPGridView.PageSize = 2;
                //objSPGridView.AllowPaging = true;
                //objSPGridView.PageIndexChanging += new GridViewPageEventHandler(objSPGridView_PageIndexChanging);
                //objSPGridView.PagerTemplate = null; // Must be called after Controls.Add(oGrid) 
    
                
                objSPGridView.Sorting += new GridViewSortEventHandler(OnSPGridView_Sorting);
                objSPGridView.RowDataBound += new GridViewRowEventHandler(objSPGridView_RowDataBound);
                this.objSPGridView.Columns.Clear();
    
                TemplateField customField = new TemplateField();
                customField.ShowHeader = true;
                customField.HeaderTemplate = new RadioButtonTemplateField(DataControlRowType.Header, "",this);
                customField.ItemTemplate = new RadioButtonTemplateField(DataControlRowType.DataRow, " ",this);
                //customField.SortExpression = "Nom_x0020_Projet";
                objSPGridView.Columns.Add(customField);
    
    
                //Faire attention aux noms des champs lors de l'intégration
                SPBoundField field = new SPBoundField();
                field.DataField = "Nom_x0020_Projet";
                field.HeaderText = "Projet";
                field.SortExpression = "Nom_x0020_Projet";
                this.objSPGridView.Columns.Add(field);
    
                //Faire attentioux à la façon de sauvegarde des urls sans ou avec http
                HyperLinkField hlf = new HyperLinkField();
                hlf.HeaderText = "Espace Projet";
                hlf.SortExpression = "Site";
                hlf.DataNavigateUrlFields = new string[] { "Site" };
                hlf.DataTextField = "Site";
                hlf.DataNavigateUrlFormatString = "http://{0}";
                objSPGridView.Columns.Add(hlf);
    
    
                DataTable dt = new DataTable();
                this.GetDataTable(ref dt);
                oView = dt.DefaultView;
                this.objSPGridView.DataSource = oView;
                this.objSPGridView.DataBind(); 
                #endregion
    
                #region Vue des interventions
    
               
                    objSPGridViewInter = new SPGridView();
                    objSPGridViewInter.ID = "SPGridViewInterWP";
                    objSPGridViewInter.AutoGenerateColumns = false;
                    objSPGridViewInter.EmptyDataText = "Aucun élément disponible à afficher";
                    objSPGridViewInter.AllowSorting = true;
    
                    objSPGridViewInter.AllowPaging = true;
                    objSPGridViewInter.PageIndexChanging += new GridViewPageEventHandler(objSPGridViewInter_PageIndexChanging);
                    objSPGridViewInter.PagerTemplate = null;
                    objSPGridViewInter.Sorting += new GridViewSortEventHandler(objSPGridViewInter_Sorting);
                    this.objSPGridViewInter.Columns.Clear();
    
    
    
                    if (globalProjet == null)
                    {
                        DataTable dt1 = new DataTable();
                        this.GetDataTable1(ref dt1);
                        oView1 = dt1.DefaultView;
                        BoundField colTitle;
    
                        for (int i = 0; i < dt1.Columns.Count; i++)
                        {
                            if ((!dt1.Columns[i].ColumnName.Equals("ID")) && (!dt1.Columns[i].ColumnName.Equals("Created")))
                            {
                                colTitle = new BoundField();
                                colTitle.DataField = dt1.Columns[i].ColumnName;
                                colTitle.HeaderText = dt1.Columns[i].Caption;
                                colTitle.SortExpression = dt1.Columns[i].ColumnName;
                                this.objSPGridViewInter.Columns.Add(colTitle);
                            }
                        }
                        
                    }
    
                    this.objSPGridViewInter.DataSource = oView1;
                    this.objSPGridViewInter.DataBind();
    
                
                #endregion
    
            }
    
            void objSPGridView_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                DataRowView drv = e.Row.DataItem as DataRowView;
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
    
                    CustomRadioButton rbtnl = (CustomRadioButton)e.Row.FindControl("rb1");
                    rbtnl.Value = DataBinder.Eval(drv, "Nom_x0020_Projet").ToString();
                    rbtnl.DataBind();
                    Page.Response.Write(" Radio Bound " + rbtnl.Value);
                }
    
                
            }
    
            protected override void OnLoad(EventArgs e)
            {
              
            }
    
            void objSPGridViewInter_Sorting(object sender, GridViewSortEventArgs e)
            {
                this.Page.Response.Write("Sort");
                string lastExpression = "";
    
                if (ViewState["SortExpression"] != null)
    
                    lastExpression = ViewState["SortExpression"].ToString();
    
    
    
                string lastDirection = "asc";
    
                if (ViewState["SortDirection"] != null)
    
                    lastDirection = ViewState["SortDirection"].ToString();
    
    
    
                string newDirection = "asc";
    
                if (e.SortExpression == lastExpression)
    
                    newDirection = (lastDirection == "asc") ? "desc" : "asc";
    
    
    
                ViewState["SortExpression"] = e.SortExpression;
    
                ViewState["SortDirection"] = newDirection;
    
    
    
                oView1.Sort = e.SortExpression + " " + newDirection;
    
    
                //Output the sort expression in Outpu Window
    
                System.Diagnostics.Trace.WriteLine(oView1.Sort);
    
                this.objSPGridViewInter.DataBind();
    
            }
    
            void objSPGridViewInter_PageIndexChanging(object sender, GridViewPageEventArgs e)
            {
                objSPGridViewInter.PageIndex = e.NewPageIndex;
                objSPGridViewInter.DataBind();
            }
    
            protected override void CreateChildControls()
            {
                //this.Page.Response.Write("CreateChildControls");
                base.CreateChildControls();
    
                vueProjet.Controls.Add(new LiteralControl("Vue des projets :"));
                vueProjet.Controls.Add(new LiteralControl("<br>"));
                vueProjet.Controls.Add(objSPGridView);
                //Turn on Paging and add event handler 
                
    
                this.Controls.Add(vueProjet);
                
    
                vueIntervention.Controls.Add(new LiteralControl("Vue des interventions :"));
                vueIntervention.Controls.Add(new LiteralControl("<br>"));
                vueIntervention.Controls.Add(objSPGridViewInter);
                this.Controls.Add(vueIntervention);
    
                
            }
    
            private void GetDataTable(ref DataTable dt)
            {
    
                dt.Clear();
    
    
    
                dt = SPContext.Current.Web.Lists["Projet"].GetItems(SPContext.Current.Web.Lists["Projet"].DefaultView).GetDataTable();
    
            }
    
            void OnSPGridView_Sorting(object sender, GridViewSortEventArgs e)
            {
                this.Page.Response.Write("Sort");
                string lastExpression = "";
    
                if (ViewState["SortExpression"] != null)
    
                    lastExpression = ViewState["SortExpression"].ToString();
    
    
    
                string lastDirection = "asc";
    
                if (ViewState["SortDirection"] != null)
    
                    lastDirection = ViewState["SortDirection"].ToString();
    
    
    
                string newDirection = "asc";
    
                if (e.SortExpression == lastExpression)
    
                    newDirection = (lastDirection == "asc") ? "desc" : "asc";
    
    
    
                ViewState["SortExpression"] = e.SortExpression;
    
                ViewState["SortDirection"] = newDirection;
    
    
    
                oView.Sort = e.SortExpression + " " + newDirection;
    
    
                //Output the sort expression in Outpu Window
    
                System.Diagnostics.Trace.WriteLine(oView.Sort);
    
    
    
                this.objSPGridView.DataBind();
    
    
    
            }
    
            private void objSPGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
             {
                 objSPGridView.PageIndex = e.NewPageIndex;
                 objSPGridView.DataBind();
             }
    
            public void GetDataTable1(ref DataTable dt)
            {
    
                dt.Clear();
    
                if (globalProjet != null)                
                {
                    //Page.Response.Write("  GB Not Null  " + globalProjet);
                    SPList objSPList = SPContext.Current.Web.Lists["Intervention"];
                    SPListItemCollection objSPListItemCollection;
    
                    #region Requête CAML sur la liste des interventions
                    SPQuery objSPQuery = new SPQuery();
                    objSPQuery.ViewFields =
                              @"
                           
                           <FieldRef Name='Client' />
                           <FieldRef Name='Date_x0020_D_x00e9_but' />
                           <FieldRef Name='Date_x0020_Fin' />
                           <FieldRef Name='Consultant' />
                           <FieldRef Name='Type_x0020_Profil' />
                          ";
                    objSPQuery.Query =
                        @" 
                               <Where>
                                  <And>
                                     <And>
                                        <Geq>
                                           <FieldRef Name='Date_x0020_D_x00e9_but' />
                                           <Value Type='DateTime'>" + DateTime.Today.Date.AddDays(-10).ToString("s") + @"</Value>
                                        </Geq>
                                        <Leq>
                                           <FieldRef Name='Date_x0020_D_x00e9_but' />
                                           <Value Type='DateTime'>" + DateTime.Today.Date.AddDays(5).ToString("s") + @"</Value>
                                        </Leq>
                                     </And>
                                     <Eq>
                                        <FieldRef Name='Projet' />
                                        <Value Type='Text'>" + globalProjet + @"</Value>
                                     </Eq>
                                  </And>
                               </Where>";
    
                    objSPListItemCollection = objSPList.GetItems(objSPQuery);
                    #endregion
    
    
                    #region Affecter la valeur de la requête au grid
                    dt = objSPListItemCollection.GetDataTable();
                    #endregion
    
                    if (dt != null)
                    {
                        foreach (DataColumn column in dt.Columns)
                        {
                            column.ColumnName = objSPList.Fields.GetFieldByInternalName(column.ColumnName).InternalName;
                            column.Caption = objSPList.Fields.GetFieldByInternalName(column.ColumnName).Title;
                        }
                    }
                }
                else
                {
                    //Page.Response.Write(" GB Null");
                    dt = SPContext.Current.Web.Lists["Intervention"].GetItems(SPContext.Current.Web.Lists["Intervention"].DefaultView).GetDataTable();
                }
               
    
            }
    
            protected override void OnPreRender(EventArgs e)
            {
                base.OnPreRender(e);
                // Page.Response.Write("   Render Global Projet " + globalProjet);
    
            }
    
                
        }
    
    }
    
    
        
    
        

    Friday, July 24, 2009 9:52 AM

All replies

  • Hi ZemZemi

    Please see these

    http://blogs.sharepointace.com/post/SPGridView-Using-a-custom-TemplateField-to-add-a-Checkbox-Column.aspx

    http://www.reversealchemy.net/blog/2009/07/08/building-a-spgridview-control-intermezzo-templatefields-and-the-rowcommand-event/

    Hope that will help

    cheers


    SharePoint 2007 (Administration/Development) Web developer and .NET DTS Programmer .NET Framework 2.0/3.5 SQL Server 2008/2005/2k
    • Proposed as answer by aliusman Thursday, July 29, 2010 5:49 AM
    Tuesday, July 27, 2010 10:57 AM
  • Hi,

     

    Could you see the date of my post ?

    Thank you for your help.

    Thursday, July 29, 2010 9:04 AM