none
如何在一个自定义webpart中的自定义datagrid控件中增加checkbox列 RRS feed

  • 问题

  • 如何在一个自定义webpart中的自定义datagrid控件中增加Checkbox列,并且能够在Griddata分页浏览的时候,能够保存CHECKBOX的选择状态呢?这个问题困扰我一周了,真想撞墙!
    2009年5月18日 7:52

答案

  • 你好,
    我按照你给的代码测试仍然正确啊,除了因你的数据源与我的不同而稍做修改外其它的完全一样。 你看看你的数据源是否有问题。
    <%@ Page Language="C#" %>
    
    <%@ Import Namespace="System.Data" %>
    
    
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    
    
    <script runat="server">
    
        public class ColumnTemplate : ITemplate
    
        {
    
            private string ControlId = "";
    
            private bool blnEnable;
    
            public ColumnTemplate(string strId, bool enable)
    
            {
    
                ControlId = strId;
    
                blnEnable = enable;
    
            }
    
            public void InstantiateIn(Control container)
    
            {
    
                CheckBox myCheckBox = new CheckBox();
    
                myCheckBox.Checked = true;
    
                myCheckBox.ID = ControlId;
    
                myCheckBox.Enabled = blnEnable;
    
                container.Controls.Add(myCheckBox);
    
    
    
            }
    
    
    
        }
    
    
    
        
    
        protected void Page_Load(object sender, EventArgs e)
    
        {
    
            if (!this.IsPostBack)
    
            {
    
                TreeDataGrid tdg = new TreeDataGrid();
    
                tdg.DataSourceID = "ObjectDataSource1";
    
                this.Panel1.Controls.Add(tdg);
    
                
    
            }
    
        }
    
         [ToolboxData("<{0}:TreeDataGrid   runat=server></{0}:TreeDataGrid>")]
    
    
    
            public class TreeDataGrid : System.Web.UI.WebControls.DataGrid
    
            {
    
                public string  _keyDataField = "Task_UID";
    
                public string  _parentDataField ="Task_Parent_UID" ;
    
                public string _nameDataField = "Task_Name";
    
                public string _plusImageUrl = "/_layouts/images/whiteplus.gif";
    
                public string _minusImageUrl = "/_layouts/images/whiteminus.gif";
    
    
    
                //public   string   _displayDataField 
    
    
    
                public bool _defaultExpand = true  ;
    
                public string _defaultDisplay = "";
    
    
    
                public DataTable _treeTable;
    
               
    
                       
    
                 protected override void OnItemCreated(DataGridItemEventArgs e)
    
                {
    
                    base.OnItemCreated(e);
    
    
    
                    if (this.Site != null && this.Site.DesignMode) return;
    
    
    
                    DataRowView row = e.Item.DataItem as DataRowView;
    
    
    
                    if (row == null) return;
    
    //下面是我稍作修改部分。因为数据源不一样的原因,所以注释掉了一些代码。
    //string sId = row[this._keyDataField].ToString(); //string pId = row[this._parentDataField].ToString(); //e.Item.Attributes.Add("id", this.ClientID + "_" + sId); // if (row[this._parentDataField].ToString() == "378aa44f-7ef1-4e54-ba0d-42b4381b06e6") // e.Item.Style.Add("display", ""); // else // e.Item.Style .Add ("display",_defaultDisplay); } protected override void OnInit(EventArgs e) { base.OnInit(e); TemplateColumn newtempColumn; newtempColumn = new TemplateColumn(); newtempColumn.HeaderText = "Active"; newtempColumn.HeaderStyle.Width = Unit.Pixel(50); ColumnTemplate cTemp; cTemp = new ColumnTemplate("CheckBox1", false); newtempColumn.ItemTemplate = cTemp; cTemp = new ColumnTemplate("CheckBox1", true); newtempColumn.EditItemTemplate = cTemp; this.Columns.Add(newtempColumn); string jsKey="test"; if (this.Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), jsKey) == false) { string js = @"<script language=""javascript"" runat=""server""> function TreeDataGrid_changeDisplay( parentId , id , ids ){ //alert(ids);return; if( ids == "","" ) return ; arr = ids.split("",""); pref=parentId + ""_"" ; //obj = eval( "" pref + arr[1].split('.')[1] "" ); obj = document.getElementById(eval(""pref+ arr[1].split('.')[1]"")) ; display = """"; if( obj.style.display == """" ) display = ""none"" ;" + "\n imgId = pref + 'img_' + id ;" + "minusImg='" + this._minusImageUrl + "';" + "plusImg='" + this._plusImageUrl + "';" + "\n if( display == \"\" ) document.getElementById( eval(\"imgId\") ).src= minusImg ;" + "\n else document.getElementById( eval(\"imgId\") ).src= plusImg ;\n" + @" for( i = 1 ; i < arr.length ; i ++){ //obj = eval( ""document.all.""+arr[i] + """" ) if( arr[i] == '' ) continue ; arrCId = arr[i].split('.'); if( display == '' && arrCId[0] != id ) continue ; // obj = eval( "" pref + arrCId[1] "" ); obj = document.getElementById(eval(""pref + arrCId[1]"") ); if(obj==null) continue ; obj.style.display = display ; if( display == 'none' ){ imgId = pref + 'img_' + arrCId[1] ; img = document.getElementById( eval(""imgId"") ) ; if( img == null ) continue ; if( display == '' ) document.getElementById( eval(""imgId"")).src= minusImg ; else document.getElementById( eval(""imgId"") ).src= plusImg ; } } } <" + "/script>"; this.Page.ClientScript.RegisterStartupScript(this.GetType(),jsKey, js); } } } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:WebPartManager ID="WebPartManager1" runat="server"> </asp:WebPartManager> <asp:WebPartZone runat="server" ID="zone1"> <ZoneTemplate> <asp:Panel ID="Panel1" runat="server"> </asp:Panel> </ZoneTemplate> </asp:WebPartZone> </div> <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" DeleteMethod="Delete" InsertMethod="Insert" OldValuesParameterFormatString="original_{0}" SelectMethod="GetData" TypeName="test_EmployeeInfo_SKDataSetTableAdapters.Images1TableAdapter" UpdateMethod="Update"> <DeleteParameters> <asp:Parameter Name="Original_Id" Type="Int32" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="ImageName" Type="String" /> <asp:Parameter Name="Des" Type="String" /> <asp:Parameter Name="Path" Type="String" /> <asp:Parameter Name="CategoryId" Type="Int32" /> <asp:Parameter Name="Original_Id" Type="Int32" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="ImageName" Type="String" /> <asp:Parameter Name="Des" Type="String" /> <asp:Parameter Name="Path" Type="String" /> <asp:Parameter Name="CategoryId" Type="Int32" /> </InsertParameters> </asp:ObjectDataSource> </form> </body> </html>

    Microsoft Online Community Support
    2009年5月21日 7:12

全部回复

  • 1.checkBox 可以用模版列实现, 
    2.声明一个 Dictionary<,> 保存到 Session 中, 当 checkBox 状态发生变化时,将主键值 和 checkBox.Checked 的值存到Dictionary中
    3.在 ItemDataBound 事件中,判断行的主键是否在 Dictionary 中,如果在就修改 checkbox 的 checked 属性

    大概就是这样,当然还是有一些细节要处理

    知识改变命运,奋斗成就人生!
    2009年5月18日 8:06
    版主
  • 问题的关键不在保存状态,是我用了下面的代码来给模板列添加了一个CHECKBOX列,可是在Webpart中就是显示不出来,前几天那个孟先生帮我看了一下,说没有问题,可是我的就是出不来,不知道为什么,我的代码和他的测试代码区别是:我的DATAGRID是嵌入在webpart中调用,他测试的环境是用一个网页来展示的。

     public  class  ColumnTemplate  :  ITemplate 


      private  string  ControlId  =  ""; 
      private  bool  blnEnable; 
      public  ColumnTemplate(string  strId,bool  enable) 
      { 
      ControlId  =  strId; 
      blnEnable=enable; 
      } 
      public  void  InstantiateIn(Control  container) 
      { 
      CheckBox  myCheckBox  =  new  CheckBox(); 
        myCheckBox.Checked  =true; 
      myCheckBox.ID  =  ControlId;                     
      myCheckBox.Enabled=blnEnable; 
      container.Controls.Add(myCheckBox); 
       
      } 
          
    }


     protected override void OnInit(EventArgs e)
                {
                    base.OnInit(e);
                    TemplateColumn  newtempColumn; 
                    newtempColumn  =  new  TemplateColumn();                       
                    newtempColumn.HeaderText  =  "Active"; 
                    newtempColumn.HeaderStyle.Width=Unit.Pixel(50); 
                    ColumnTemplate  cTemp; 
                    cTemp  =  new  ColumnTemplate("CheckBox1",false); 
                    newtempColumn.ItemTemplate  =  cTemp; 
                    cTemp  =  new  ColumnTemplate("CheckBox1",true); 
                    newtempColumn.EditItemTemplate=cTemp;         
                    datagrid.Columns.Add(newtempColumn);
                 }

    2009年5月18日 8:45
  • 楼主,你好

    根据你的代码我的测试结果如下,可见是可以显示的。

    <%@ Page Language="C#" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <script runat="server">
        public class ColumnTemplate : ITemplate
        {
            private string ControlId = "";
            private bool blnEnable;
            public ColumnTemplate(string strId, bool enable)
            {
                ControlId = strId;
                blnEnable = enable;
            }
            public void InstantiateIn(Control container)
            {
                CheckBox myCheckBox = new CheckBox();
                myCheckBox.Checked = true;
                myCheckBox.ID = ControlId;
                myCheckBox.Enabled = blnEnable;
                container.Controls.Add(myCheckBox);
    
            }
    
        }
    
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            TemplateColumn newtempColumn;
            newtempColumn = new TemplateColumn();
            newtempColumn.HeaderText = "Active";
            newtempColumn.HeaderStyle.Width = Unit.Pixel(50);
            ColumnTemplate cTemp;
            cTemp = new ColumnTemplate("CheckBox1", false);
            newtempColumn.ItemTemplate = cTemp;
            cTemp = new ColumnTemplate("CheckBox1", true);
            newtempColumn.EditItemTemplate = cTemp;
            this.dg.Columns.Add(newtempColumn);
        }
    </script>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:WebPartManager ID="WebPartManager1" runat="server">           
            
            </asp:WebPartManager>
            <asp:WebPartZone runat="server" ID="zone1">
                <ZoneTemplate>
                             <asp:DataGrid runat="server" ID="dg" DataSourceID="ObjectDataSource1"></asp:DataGrid>
                
                </ZoneTemplate>
                    
                
            </asp:WebPartZone>
        </div>
        <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
            DeleteMethod="Delete" InsertMethod="Insert" 
            OldValuesParameterFormatString="original_{0}" SelectMethod="GetData" 
            TypeName="test_EmployeeInfo_SKDataSetTableAdapters.ImagesTableAdapter" 
            UpdateMethod="Update">
            <DeleteParameters>
                <asp:Parameter Name="Original_Id" Type="Int32" />
            </DeleteParameters>
            <UpdateParameters>
                <asp:Parameter Name="ImageName" Type="String" />
                <asp:Parameter Name="Des" Type="String" />
                <asp:Parameter Name="Path" Type="String" />
                <asp:Parameter Name="CategoryId" Type="Int32" />
                <asp:Parameter Name="Original_Id" Type="Int32" />
            </UpdateParameters>
            <InsertParameters>
                <asp:Parameter Name="ImageName" Type="String" />
                <asp:Parameter Name="Des" Type="String" />
                <asp:Parameter Name="Path" Type="String" />
                <asp:Parameter Name="CategoryId" Type="Int32" />
            </InsertParameters>
        </asp:ObjectDataSource>
        </form>
    </body>
    </html>
    

    代码如下:

    Microsoft Online Community Support
    2009年5月20日 4:38
  • 非常感谢版主的热心!我也是初学者,代码写得不好,也说不大清楚,还是贴出来吧!我是这样产生页面代码的,可是就是出不来!郁闷死了

            protected override void CreateChildControls()
            {
                
                  Controls.Add(new LiteralControl("<br>"));

                _lbltext.Text ="Please select a project name:";

                _lbltext.ControlStyle.ForeColor = Color .Red ;
               
               
                Controls.Add(_lbltext);

                Controls.Add(new LiteralControl("<br>"));

                _lbProject = new ListBox();

                _lbProject.AutoPostBack = true;

                setProjectListDataSet();

                for (int i = 0; i < _projectListDS.Project.Count; i++)
                {
                   

                    _lbProject.Items.Add(_projectListDS .Project [i].PROJ_NAME);
                 
               
                }

                _lbProject.Items[0].Selected = true;

               // _lbProject .SelectedIndexChanged += new EventHandler ( myClick_Change);
               
                Controls.Add(_lbProject);
              

                Controls.Add (new LiteralControl("<br>"));

     

                _up.ImageUrl = "/_layouts/images/LeftIndent.GIF";

                Controls.Add(_up);

                _down.ImageUrl = "/_layouts/images/RightIndent.GIF";
                Controls.Add(_down);

                _insert.ImageUrl = "/_layouts/images/INSROW.GIF";

                Controls.Add(_insert);

                _delete.ImageUrl = "/_layouts/images/DELROW.GIF";
                Controls.Add(_delete);


                Controls.Add(new LiteralControl("<br>"));


                  setTaskDataSet(proj_Guid);

                _treeDataGrid.DataSource = displayTaskDT;

                _treeDataGrid.DataBind();

                _treeDataGrid.KeyDataField = displayTaskDT.Columns["Task_UID"].ToString ();

                _treeDataGrid.ParentDataField = displayTaskDT.Columns["Task_Parent_UID"].ToString ();

                _treeDataGrid.NameDataField = displayTaskDT.Columns["Task_Name"].ToString ();

     

    }


            //自定义控件TREEGRID  --BEGIN
            [ToolboxData("<{0}:TreeDataGrid   runat=server></{0}:TreeDataGrid>")]

            public class TreeDataGrid : System.Web.UI.WebControls.DataGrid
            {
                public string  _keyDataField = "Task_UID";
                public string  _parentDataField ="Task_Parent_UID" ;
                public string _nameDataField = "Task_Name";
                public string _plusImageUrl = "/_layouts/images/whiteplus.gif";
                public string _minusImageUrl = "/_layouts/images/whiteminus.gif";

                //public   string   _displayDataField 

                public bool _defaultExpand = true  ;
                public string _defaultDisplay = "";

                public DataTable _treeTable;

               .........
                       
                 protected override void OnItemCreated(DataGridItemEventArgs e)
                {
                    base.OnItemCreated(e);

                    if (this.Site != null && this.Site.DesignMode) return;

                    DataRowView row = e.Item.DataItem as DataRowView;

                    if (row == null) return;

                    string sId = row[this._keyDataField].ToString();
                    //string pId = row[this._parentDataField].ToString();

                    e.Item.Attributes.Add("id", this.ClientID + "_" + sId);

                   // if (row[this._parentDataField].ToString() == "378aa44f-7ef1-4e54-ba0d-42b4381b06e6")
                    //    e.Item.Style.Add("display", "");
                   // else
                        e.Item.Style .Add ("display",_defaultDisplay);
                }

                protected override void OnInit(EventArgs e)
                {
                    base.OnInit(e);

     

                    TemplateColumn newtempColumn;
                    newtempColumn = new TemplateColumn();
                    newtempColumn.HeaderText = "Active";
                    newtempColumn.HeaderStyle.Width = Unit.Pixel(50);
                    ColumnTemplate cTemp;
                    cTemp = new ColumnTemplate("CheckBox1", false);
                    newtempColumn.ItemTemplate = cTemp;
                    cTemp = new ColumnTemplate("CheckBox1", true);
                    newtempColumn.EditItemTemplate = cTemp;
                    this.Columns.Add(newtempColumn);

              
                   

                    if (this.Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), jsKey) == false)
                    {

                        string js = @"<script   language=""javascript"" runat=""server"">  
                         function   TreeDataGrid_changeDisplay(   parentId   ,   id   ,   ids   ){  
                        //alert(ids);return;  
       
                       if(   ids   ==   "",""   )   return   ;  
                       arr   =   ids.split("","");  
       
                       pref=parentId   +   ""_""   ;  
       
                      //obj   =   eval( ""  pref   +   arr[1].split('.')[1]    "" );  
                     obj    =    document.getElementById(eval(""pref+   arr[1].split('.')[1]"")) ;
                      display   =   """";  
                      if(   obj.style.display   ==   """"   )  
                      display   =   ""none""   ;" +

                         "\n   imgId   =   pref   +   'img_'   +   id   ;" +
                         "minusImg='" + this._minusImageUrl + "';" +
                         "plusImg='" + this._plusImageUrl + "';" +

                         "\n   if(   display   ==   \"\"   )   document.getElementById( eval(\"imgId\")  ).src=   minusImg   ;" +
                         "\n   else     document.getElementById( eval(\"imgId\")  ).src=   plusImg   ;\n" +

                         @"  
                           for(   i   =   1   ;   i   <   arr.length   ;   i   ++){  
                         //obj   =   eval(   ""document.all.""+arr[i]   +   """"   )  
                        if(   arr[i]   ==   ''   )   continue   ;  
                        arrCId   =   arr[i].split('.');  
                        if(   display   ==   ''   &&   arrCId[0]   !=   id   )   continue   ;        
                      // obj   =   eval(  "" pref   +   arrCId[1]  ""   );  
                         obj    =    document.getElementById(eval(""pref   +   arrCId[1]"") );
                       if(obj==null)   continue   ;    
                          obj.style.display   =   display   ;  
       
                          if(   display   ==   'none'   ){  
                          imgId   =   pref   +   'img_'   +   arrCId[1]   ;  
                         img   =   document.getElementById( eval(""imgId"") )  ;  
                         if(   img   ==   null   )   continue   ;  
                         if(   display   ==   ''   )   document.getElementById( eval(""imgId"")).src=   minusImg   ;  
                         else     document.getElementById( eval(""imgId"") ).src=   plusImg   ;  
                           }  
       
                           }  
                           }  
                              <" + "/script>";  

                      this.Page.ClientScript.RegisterStartupScript(this.GetType(), jsKey, js);
                     
                    }

                }

     

     
            }

               ////自定义控件treeGrid   --END

     

     

      

    2009年5月20日 11:40
  • 你好,
    我按照你给的代码测试仍然正确啊,除了因你的数据源与我的不同而稍做修改外其它的完全一样。 你看看你的数据源是否有问题。
    <%@ Page Language="C#" %>
    
    <%@ Import Namespace="System.Data" %>
    
    
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    
    
    <script runat="server">
    
        public class ColumnTemplate : ITemplate
    
        {
    
            private string ControlId = "";
    
            private bool blnEnable;
    
            public ColumnTemplate(string strId, bool enable)
    
            {
    
                ControlId = strId;
    
                blnEnable = enable;
    
            }
    
            public void InstantiateIn(Control container)
    
            {
    
                CheckBox myCheckBox = new CheckBox();
    
                myCheckBox.Checked = true;
    
                myCheckBox.ID = ControlId;
    
                myCheckBox.Enabled = blnEnable;
    
                container.Controls.Add(myCheckBox);
    
    
    
            }
    
    
    
        }
    
    
    
        
    
        protected void Page_Load(object sender, EventArgs e)
    
        {
    
            if (!this.IsPostBack)
    
            {
    
                TreeDataGrid tdg = new TreeDataGrid();
    
                tdg.DataSourceID = "ObjectDataSource1";
    
                this.Panel1.Controls.Add(tdg);
    
                
    
            }
    
        }
    
         [ToolboxData("<{0}:TreeDataGrid   runat=server></{0}:TreeDataGrid>")]
    
    
    
            public class TreeDataGrid : System.Web.UI.WebControls.DataGrid
    
            {
    
                public string  _keyDataField = "Task_UID";
    
                public string  _parentDataField ="Task_Parent_UID" ;
    
                public string _nameDataField = "Task_Name";
    
                public string _plusImageUrl = "/_layouts/images/whiteplus.gif";
    
                public string _minusImageUrl = "/_layouts/images/whiteminus.gif";
    
    
    
                //public   string   _displayDataField 
    
    
    
                public bool _defaultExpand = true  ;
    
                public string _defaultDisplay = "";
    
    
    
                public DataTable _treeTable;
    
               
    
                       
    
                 protected override void OnItemCreated(DataGridItemEventArgs e)
    
                {
    
                    base.OnItemCreated(e);
    
    
    
                    if (this.Site != null && this.Site.DesignMode) return;
    
    
    
                    DataRowView row = e.Item.DataItem as DataRowView;
    
    
    
                    if (row == null) return;
    
    //下面是我稍作修改部分。因为数据源不一样的原因,所以注释掉了一些代码。
    //string sId = row[this._keyDataField].ToString(); //string pId = row[this._parentDataField].ToString(); //e.Item.Attributes.Add("id", this.ClientID + "_" + sId); // if (row[this._parentDataField].ToString() == "378aa44f-7ef1-4e54-ba0d-42b4381b06e6") // e.Item.Style.Add("display", ""); // else // e.Item.Style .Add ("display",_defaultDisplay); } protected override void OnInit(EventArgs e) { base.OnInit(e); TemplateColumn newtempColumn; newtempColumn = new TemplateColumn(); newtempColumn.HeaderText = "Active"; newtempColumn.HeaderStyle.Width = Unit.Pixel(50); ColumnTemplate cTemp; cTemp = new ColumnTemplate("CheckBox1", false); newtempColumn.ItemTemplate = cTemp; cTemp = new ColumnTemplate("CheckBox1", true); newtempColumn.EditItemTemplate = cTemp; this.Columns.Add(newtempColumn); string jsKey="test"; if (this.Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), jsKey) == false) { string js = @"<script language=""javascript"" runat=""server""> function TreeDataGrid_changeDisplay( parentId , id , ids ){ //alert(ids);return; if( ids == "","" ) return ; arr = ids.split("",""); pref=parentId + ""_"" ; //obj = eval( "" pref + arr[1].split('.')[1] "" ); obj = document.getElementById(eval(""pref+ arr[1].split('.')[1]"")) ; display = """"; if( obj.style.display == """" ) display = ""none"" ;" + "\n imgId = pref + 'img_' + id ;" + "minusImg='" + this._minusImageUrl + "';" + "plusImg='" + this._plusImageUrl + "';" + "\n if( display == \"\" ) document.getElementById( eval(\"imgId\") ).src= minusImg ;" + "\n else document.getElementById( eval(\"imgId\") ).src= plusImg ;\n" + @" for( i = 1 ; i < arr.length ; i ++){ //obj = eval( ""document.all.""+arr[i] + """" ) if( arr[i] == '' ) continue ; arrCId = arr[i].split('.'); if( display == '' && arrCId[0] != id ) continue ; // obj = eval( "" pref + arrCId[1] "" ); obj = document.getElementById(eval(""pref + arrCId[1]"") ); if(obj==null) continue ; obj.style.display = display ; if( display == 'none' ){ imgId = pref + 'img_' + arrCId[1] ; img = document.getElementById( eval(""imgId"") ) ; if( img == null ) continue ; if( display == '' ) document.getElementById( eval(""imgId"")).src= minusImg ; else document.getElementById( eval(""imgId"") ).src= plusImg ; } } } <" + "/script>"; this.Page.ClientScript.RegisterStartupScript(this.GetType(),jsKey, js); } } } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:WebPartManager ID="WebPartManager1" runat="server"> </asp:WebPartManager> <asp:WebPartZone runat="server" ID="zone1"> <ZoneTemplate> <asp:Panel ID="Panel1" runat="server"> </asp:Panel> </ZoneTemplate> </asp:WebPartZone> </div> <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" DeleteMethod="Delete" InsertMethod="Insert" OldValuesParameterFormatString="original_{0}" SelectMethod="GetData" TypeName="test_EmployeeInfo_SKDataSetTableAdapters.Images1TableAdapter" UpdateMethod="Update"> <DeleteParameters> <asp:Parameter Name="Original_Id" Type="Int32" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="ImageName" Type="String" /> <asp:Parameter Name="Des" Type="String" /> <asp:Parameter Name="Path" Type="String" /> <asp:Parameter Name="CategoryId" Type="Int32" /> <asp:Parameter Name="Original_Id" Type="Int32" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="ImageName" Type="String" /> <asp:Parameter Name="Des" Type="String" /> <asp:Parameter Name="Path" Type="String" /> <asp:Parameter Name="CategoryId" Type="Int32" /> </InsertParameters> </asp:ObjectDataSource> </form> </body> </html>

    Microsoft Online Community Support
    2009年5月21日 7:12
  • 我自己感觉,可能差别就是在于下面这段html代码,你用的是页面展现,而我的完全是由webpart来管理和展现,根本就没有页面HTML代码出现,就是插入过一个脚本块

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head runat="server">

        <title></title>

    </head>

    <body>

        <form id="form1" runat="server">

        <div>

          。。。。。

    下面是我的全部的源代码,没有任何保留,是建立在安装和部署好的微软的EPM系统WEB SERVICES基础上的,代码不多,请楼主帮忙看一下,到底是什么原因让那个DATAGRID展现不出来加入的控件,我准备在它里面加一个CHECKBOx和一个日历控件呢,现在就卡在这里了,不知道是不是GRID在展现的时候,是不是被重复展现过?render,controlrender等函数有没有覆盖展现结果,这个好像是比较深层次了,只是猜测!:

    2009年5月22日 0:49
  • using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    using System.Drawing;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.Services;
    using Microsoft.Office.Project.Server.Library;
    using Microsoft.Office.Project.PWA;
    using Microsoft.SharePoint.WebPartPages;
    using Microsoft.SharePoint.Utilities;
    using System.Data;
    using System.ComponentModel;
    using System.Collections;

     


    namespace EPMAdd_In
    {
            public class SubTaskModule:WebPart
        {
            //web Services引用常量

            const string PROJECT_SERVER_URI = "http://highfar/PWA/";

            const string PROJECT_SERVICE_PATH = "_vti_bin/psi/project.asmx";

            const string RESOURCE_SERVICE_PATH = "_vti_bin/psi/resource.asmx";

            const string RESOURCEPLAN_SERVICE_PATH = "_vti_bin/psi/resource.asmx";

            const string QUEUESYSTEM_SERVICE_PATH = "_vti_bin/psi/queuesystem.asmx";

            //共用的项目实体和项目数据集实体

            public       projectWS.Project                   _proj                   = new EPMAdd_In.projectWS.Project ();

            public       projectWS.ProjectDataSet            _projectListDS          = new EPMAdd_In.projectWS.ProjectDataSet();

            static   public     projectWS.ProjectDataSet             _projectDS             = new EPMAdd_In.projectWS.ProjectDataSet();
             
            //为了显示任务列表

            public      DataRow                              taskDataRow;
            public      DataRow                              displayTaskDataRow;
            public      DataRow[]                            taskRows;
            public      DataTable                            displayTaskDT          = new DataTable();

            //为了显示项目列表

            public      DataRow                              projectDataRow;
            public      DataRow                              displayProjectDataRow;
            //public    DataRow[]                            projectRows;
            public      DataTable                            displayProjectDT       =  new DataTable();

     

            //项目显示和任务显示的表格定义

            //public GridViewOfCheckBox                        projectGridview       = new GridViewOfCheckBox();

           // public GridViewOfCheckBox                        taskGridView          = new GridViewOfCheckBox();

            public TreeDataGrid                              _treeDataGrid         = new TreeDataGrid();

            public    ImageButton                                _up                =  new ImageButton();
           
            public    ImageButton                                _down              =  new ImageButton();
           
            public    ImageButton                                _insert            =  new ImageButton();
           
            public    ImageButton                                _delete            =  new ImageButton();
           
            public    ImageButton                                _save              =  new ImageButton();
           
            public    ImageButton                                _publish           =  new ImageButton();
           
            public    Label                                      _lbltext           =  new Label();

      

            //菜单定义

           // public    System.Web.UI.WebControls.Menu   _menu1;

            //
            public System.Web.UI.WebControls.ListBox _lbProject;

            //public Guid proj_Guid ;
            public Guid proj_Guid = new Guid("b60bc19c-4262-4d95-9020-af746ea44374");

           

            //根据项目名称取项目UID

            public Guid GetProjectUidFromProjectName(projectWS.Project proj, string projectName)
            {
                Guid result = Guid.Empty;
                projectWS.ProjectDataSet dsProjectList = new EPMAdd_In.projectWS.ProjectDataSet();
               
                dsProjectList = proj.ReadProjectList();

                for (int row = 0; row < dsProjectList.Project.Count; row++)
                {
                    if (projectName == dsProjectList.Project[row].PROJ_NAME.ToString ())

                    {
                        result = dsProjectList.Project[row].PROJ_UID;
                        break;
                    }
                }
                return result;
            }

            //根据项目UID 取项目名称

            public string GetProjectProjectNameFromUid(projectWS.Project proj, Guid projectUid)
            {
                string result = null;

                projectWS.ProjectDataSet dsProjectList = new projectWS.ProjectDataSet();

                dsProjectList = proj.ReadProjectList();

                for (int row = 0; row < dsProjectList.Project.Count; row++)
                {
                    if (projectUid == dsProjectList.Project[row].PROJ_UID )
                    {
                        result = dsProjectList.Project[row].PROJ_NAME;
                        break;
                    }
                }
                return result;
            }

            public void setProjectEntity()
            {
                _proj.Url          =  PROJECT_SERVER_URI + PROJECT_SERVICE_PATH;

                _proj.Credentials  =  CredentialCache.DefaultCredentials;

     

     


            }

            public void setProjectListDataSet()
            {
                setProjectEntity();

                _projectListDS = _proj.ReadProjectList();

                //projectRows = _projectListDS.Project.Select("*");

                if (_projectListDS.Project.Count >= 1)
                {
                    displayProjectDT.Columns.Add(new DataColumn("Project_Name", _projectListDS.Project.Columns[_projectListDS.Project.PROJ_NAMEColumn.ColumnName].DataType));
                    displayProjectDT.Columns.Add(new DataColumn("Project_Guid", _projectListDS.Project.Columns[_projectListDS.Project.PROJ_UIDColumn.ColumnName].DataType));

                    //displayProjectDT.Columns.Add(new DataColumn("Start", _projectListDS.Project.Columns[_projectListDS.Project.PROJ_INFO_START_DATEColumn.ColumnName].DataType));

                    // displayProjectDT.Columns.Add(new DataColumn("Finish", _projectListDS.Project.Columns[_projectListDS.Project.PROJ_INFO_FINISH_DATEColumn.ColumnName].DataType));

                }

                foreach (projectWS.ProjectDataSet.ProjectRow projectRow in _projectListDS.Project)
                {
                    projectDataRow = projectRow;

                    displayProjectDataRow = displayProjectDT.NewRow();

                    // displayProjectDataRow ["Owner"] = projectRow [_projectListDS .Project .PROJ_PROP_MANAGERColumn ];
                    displayProjectDataRow["Project_Name"] = projectRow[_projectListDS.Project.PROJ_NAMEColumn];
                    displayProjectDataRow["Project_Guid"] = projectRow[_projectListDS.Project.PROJ_UIDColumn];
                    // displayProjectDataRow["Start"] = projectRow[_projectListDS.Project.PROJ_INFO_START_DATEColumn];
                    // displayProjectDataRow["Finish"] = projectRow[_projectListDS.Project.PROJ_INFO_FINISH_DATEColumn];

                    displayProjectDT.Rows.Add(displayProjectDataRow);

                }

     

     

     

     


            }

            public void setTaskDataSet(Guid proj_Guid)
            {
                int iTask = 0;

                setProjectEntity();

     


                _projectDS = _proj.ReadProject(proj_Guid, EPMAdd_In.projectWS.DataStoreEnum.PublishedStore);


                displayTaskDT.Clear();

                displayTaskDT.Columns.Clear();

                /////////////////
                //ProjectWS.ProjectDataSet projectListDS = ProjectWS.ReadProjectList();

                //DataRow[] projectRows = projectListDS.Project.Select("PROJ_NAME = '" +
                //    projName + "'");

                //projGuid = (Guid)projectRows[0]["PROJ_UID"];

                // Get a DataSet of all the tasks in a project.
                //projectDS = ProjectWS.ReadProject(projGuid,
                //    PWARefWebParts.ProjectWS.DataStoreEnum.PublishedStore);

                // Ignore the project summary task.
                if (_projectDS.Task.Count > 1)
                {
                    // Create a table with just the three columns we want to display in the Web Part.
                    displayTaskDT.Columns.Add(new DataColumn("Task_Name",
                          _projectDS.Task.Columns[_projectDS.Task.TASK_NAMEColumn.ColumnName].DataType));
                    displayTaskDT.Columns.Add(new DataColumn("Start",
                        _projectDS.Task.Columns[_projectDS.Task.TASK_START_DATEColumn.ColumnName].DataType));
                    displayTaskDT.Columns.Add(new DataColumn("Finish",
                        _projectDS.Task.Columns[_projectDS.Task.TASK_FINISH_DATEColumn.ColumnName].DataType));
                    displayTaskDT.Columns.Add(new DataColumn("Task_UID",
                       _projectDS.Task.Columns[_projectDS.Task.TASK_UIDColumn.ColumnName].DataType));
                    displayTaskDT.Columns.Add(new DataColumn("Task_Parent_UID",
                       _projectDS.Task.Columns[_projectDS.Task.TASK_PARENT_UIDColumn.ColumnName].DataType));

     

                    // Filter out tasks that are already completed.
                    taskRows = _projectDS.Task.Select(_projectDS.Task.TASK_PCT_COMPColumn.ColumnName + " <> 100 ",
                        _projectDS.Task.TASK_FINISH_DATEColumn.ColumnName + " ASC");

                    if (taskRows.Length > 0)
                    {
                        // Copy the number of tasks defined by the user into the DataTable object.
                        while (iTask < taskRows.Length)
                        {
                            taskDataRow = taskRows[iTask];
                            displayTaskDataRow = displayTaskDT.NewRow();

                            displayTaskDataRow["Task_Name"] =
                                taskDataRow[_projectDS.Task.TASK_NAMEColumn.ColumnName];
                            displayTaskDataRow["Start"] =
                                taskDataRow[_projectDS.Task.TASK_START_DATEColumn.ColumnName];
                            displayTaskDataRow["Finish"] =
                                taskDataRow[_projectDS.Task.TASK_FINISH_DATEColumn.ColumnName];

                            displayTaskDataRow["Task_UID"] =
                                taskDataRow[_projectDS.Task.TASK_UIDColumn.ColumnName];

                            displayTaskDataRow["Task_Parent_UID"] =
                                taskDataRow[_projectDS.Task.TASK_PARENT_UIDColumn.ColumnName];

     


                            displayTaskDT.Rows.Add(displayTaskDataRow);

                            iTask++;
                        }
                        //isTasksUncompleted = true;
                    }
                }

     

     


                ///////////////////

     


            }

            protected override void CreateChildControls()
            {
               
                //_menu1 = new System.Web.UI.WebControls.Menu();

                //System.Web.UI.WebControls.MenuItem homeMenuItem = new System.Web.UI.WebControls.MenuItem("升级", "Up");
                //System.Web.UI.WebControls.MenuItem homeMenuItem1 = new System.Web.UI.WebControls.MenuItem("降级", "Down");
                //System.Web.UI.WebControls.MenuItem homeMenuItem2 = new System.Web.UI.WebControls.MenuItem("插入", "Insert");
                //System.Web.UI.WebControls.MenuItem homeMenuItem3 = new System.Web.UI.WebControls.MenuItem("删除", "Delete");
                //System.Web.UI.WebControls.MenuItem homeMenuItem4 = new System.Web.UI.WebControls.MenuItem("链接", "Link");
                ////System.Web.UI.WebControls.MenuItem musicSubMenuItem = new System.Web.UI.WebControls.MenuItem("Music", "Category1");
                ////System.Web.UI.WebControls.MenuItem movieSubMenuItem = new System.Web.UI.WebControls.MenuItem("movie", "Category2");
                ////homeMenuItem.ChildItems.Add(musicSubMenuItem);
                ////homeMenuItem.ChildItems.Add(movieSubMenuItem);


                //_menu1.Items.Add(homeMenuItem);
                //_menu1.Items.Add(homeMenuItem1);
                //_menu1.Items.Add(homeMenuItem2);
                //_menu1.Items.Add(homeMenuItem3);
                //_menu1.Items.Add(homeMenuItem4);
                //_menu1.BorderColor = Color.White;
                //_menu1.BackColor = Color.White;
                //_menu1.BorderWidth = 2;

                //_menu1.ForeColor = Color.Tomato;
                //_menu1.BorderStyle = System.Web.UI.WebControls.BorderStyle.Solid;
                //_menu1.Orientation = System.Web.UI.WebControls.Orientation.Horizontal;

     


                //Controls.Add(_menu1);
                // Create _mytextbox control.

                //_mytextbox = new HtmlInputText();

                //_mytextbox.Value = "";

                //Controls.Add(_mytextbox);

     

                //// Create _mybutton control and wire its event handler.

                //_mybutton = new HtmlButton();

                //_mybutton.InnerText = "Set Web Part Title";

                //_mybutton.ServerClick += new EventHandler(_mybutton_click);

                //Controls.Add(_mybutton);


                //Create _gridview control
                //projectGridview = new GridView();

                //setProjectListDataSet();

                //projectGridview.DataSource = displayProjectDT;

                //projectGridview.DataBind();

                //Controls.Add(projectGridview);

                //Create _menu control


                Controls.Add(new LiteralControl("<br>"));

                _lbltext.Text ="Please select a project name:";

                _lbltext.ControlStyle.ForeColor = Color .Red ;
               
               
                Controls.Add(_lbltext);

                Controls.Add(new LiteralControl("<br>"));

                _lbProject = new ListBox();

                _lbProject.AutoPostBack = true;

                setProjectListDataSet();

                for (int i = 0; i < _projectListDS.Project.Count; i++)
                {
                   

                    _lbProject.Items.Add(_projectListDS .Project [i].PROJ_NAME);
                 
               
                }

                _lbProject.Items[0].Selected = true;

               // _lbProject .SelectedIndexChanged += new EventHandler ( myClick_Change);
               
                Controls.Add(_lbProject);
              

                Controls.Add (new LiteralControl("<br>"));

     

                _up.ImageUrl = "/_layouts/images/LeftIndent.GIF";

                Controls.Add(_up);

                _down.ImageUrl = "/_layouts/images/RightIndent.GIF";
                Controls.Add(_down);

                _insert.ImageUrl = "/_layouts/images/INSROW.GIF";

                Controls.Add(_insert);

                _delete.ImageUrl = "/_layouts/images/DELROW.GIF";
                Controls.Add(_delete);


                Controls.Add(new LiteralControl("<br>"));


                ////taskgridview
                //taskGridView = new GridViewOfCheckBox();
                //setTaskDataSet(proj_Guid);
                //taskGridView.DataSource = displayTaskDT;

                //taskGridView.DataBind();
                ////taskGridView.ApplyStyleSheetSkin(this);
                //taskGridView.HeaderStyle.BackColor = System.Drawing.Color.Beige;
                //taskGridView.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
                //taskGridView.BorderStyle = BorderStyle.None;
                //taskGridView.Font.Size = 28;
                //taskGridView.AllowSorting = true;
                //taskGridView.AutoGenerateEditButton = true;
                //taskGridView.AutoGenerateDeleteButton = true;
                //taskGridView.AutoGenerateColumns = true;
                //taskGridView.AutoGenerateSelectButton = true;
                //taskGridView.BackColor = Color.AliceBlue;

     

     

                //Controls.Add(taskGridView);

     

                ////////////////

                setTaskDataSet(proj_Guid);

                _treeDataGrid.DataSource = displayTaskDT;

                _treeDataGrid.DataBind();

                _treeDataGrid.KeyDataField = displayTaskDT.Columns["Task_UID"].ToString ();

                _treeDataGrid.ParentDataField = displayTaskDT.Columns["Task_Parent_UID"].ToString ();

                _treeDataGrid.NameDataField = displayTaskDT.Columns["Task_Name"].ToString ();

     

               //////////////////////

                Controls.Add(_treeDataGrid);


            }


            //protected override void RenderWebPart(HtmlTextWriter output)
            //{

            //    for (int i = 0; i <= taskGridView.Rows.Count - 1; i++)
            //    {
            //        CheckBox cbox = (CheckBox)taskGridView.Rows[i].FindControl("CheckBox1");

            //        cbox.Checked = true;

            //        //if (CheckBox2.Checked == true)
            //        //{
            //        //    cbox.Checked = true;
            //        //}
            //        //else
            //        //{
            //        //    cbox.Checked = false;
            //        //}
            //    }

     

            //    RenderChildren(output);

            //    // Securely write out HTML

            //    //output.Write("<BR>Test-1 ");


            //   // output.Write("<BR>Text Property: " + SPEncode.HtmlEncode(Text1));

     

     

            //}
           
          //  public void  myClick_Change (object sender,EventArgs e)
          // {
          //     ListBox LX=(ListBox)sender;

          //     proj_Guid = GetProjectUidFromProjectName(_proj, LX.SelectedItem.Value);

          //     //_mytextbox.Value = proj_Guid.ToString ();
             
                        
          //     setTaskDataSet(proj_Guid);

          //     taskGridView.DataBind();

     


          //     ////RenderWebPart(HtmlTextWriter output);

          //     ////

          //    //OnPreRender(e);
              
          //     //Page.Response.Write(taskGridView);

     

                      

          //// proj_Guid =<System.Web .UI .WebControls .ListBox>sender.
          
          
          // }

            //public class GridViewOfCheckBox :GridView
            //{
            //    public enum CustomColumnAlign
            //    {
            //        Left, Right
            //    }

            //    public CustomColumnAlign _align = CustomColumnAlign.Left;
            //    public string _checkBoxID = "CheckBox1";
            //    public Color _mouseOverColor;
            //    public DataControlFieldCollection _columnCol = new DataControlFieldCollection();

            //    [Browsable(true)]
            //    [Description("所建立的checkBox所在对齐方式")]
            //    [Category("扩展")]
            //    public CustomColumnAlign Align
            //    {
            //        get
            //        {
            //            return _align;
            //        }
            //        set
            //        {
            //            _align = value;
            //        }
            //    }

            //    [Browsable(true)]
            //    [Description("所建立的checkBoxID")]
            //    //  [DefaultValue("CheckBox1")]
            //    [Category("扩展")]
            //    public string CheckBoxID
            //    {
            //        get
            //        {
            //            return _checkBoxID;
            //        }
            //        set
            //        {
            //            _checkBoxID = value;
            //        }
            //    }

     

            //    //鼠标经过行时的颜色#region 鼠标经过行时的颜色
            //    [Browsable(true)]
            //    [Description("鼠标经过行的颜色")]
            //    [DefaultValue("")]
            //    [Category("扩展")]
            //    public Color MouseOverColor
            //    {
            //        get
            //        {
            //            return _mouseOverColor;
            //        }
            //        set
            //        {
            //            _mouseOverColor = value;
            //        }
            //    }

            //    protected override void OnRowDataBound(GridViewRowEventArgs e)
            //    {
            //        if (!_mouseOverColor.IsEmpty)
            //        {
            //            if (e.Row.RowType == DataControlRowType.DataRow)
            //            {
            //                //鼠标经过时,行背景色变
            //                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#" + this._mouseOverColor.ToArgb().ToString("X").Substring(2, 6) + "'");
            //                //        //当鼠标移开时还原背景色
            //                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
            //            }
            //        }
            //        base.OnRowDataBound(e);
            //    }


            //    protected override ICollection CreateColumns(PagedDataSource dataSource, bool useDataSource)
            //    {
            //        ArrayList col = base.CreateColumns(dataSource, useDataSource) as ArrayList;
            //        CreatCheckBox(col);
            //        _columnCol.Clear();
            //        foreach (DataControlField c in col)
            //        {
            //            _columnCol.Add(c);
            //        }
            //        return col;
            //    }


            //    public void CreatCheckBox(ArrayList col)
            //    {
            //        TemplateField checkColumn = new TemplateField();
            //        checkColumn.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            //        checkColumn.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            //        CheckBoxItemTemplate cbItemTemplate = new CheckBoxItemTemplate();
            //        CheckBoxItemTemplate.CheckBoxItemId = _checkBoxID;
            //        checkColumn.ItemTemplate = cbItemTemplate;
            //        CheckBoxHeaderTemplate cbHeaderTemplate = new CheckBoxHeaderTemplate();
            //        checkColumn.HeaderTemplate = cbHeaderTemplate;
            //        if (Align == CustomColumnAlign.Left)
            //        {
            //            col.Insert(0, checkColumn);
            //        }
            //        else if (Align == CustomColumnAlign.Right)
            //        {
            //            col.Add(checkColumn);
            //        }
            //    }

     

            //}
            //public class CheckBoxItemTemplate : ITemplate
            //{
            //    public static string _CheckBoxID;

            //    public static string CheckBoxItemId
            //    {
            //        get
            //        {
            //            return _CheckBoxID;
            //        }
            //        set
            //        {
            //            _CheckBoxID = value;
            //        }
            //    }
            //    public void InstantiateIn(Control container)
            //    {
            //        CheckBox cb = new CheckBox();
            //        cb.ID = _CheckBoxID;
            //        container.Controls.Add(cb);
            //    }
            //}
            //public class CheckBoxHeaderTemplate : ITemplate
            //{
            //    public void InstantiateIn(Control container)
            //    {
            //        Label la = new Label();
            //        la.Text = "Select";
            //        container.Controls.Add(la);
            //    }
            //}


            //自定义控件TREEGRID  --BEGIN
            [ToolboxData("<{0}:TreeDataGrid   runat=server></{0}:TreeDataGrid>")]

            public class TreeDataGrid : System.Web.UI.WebControls.DataGrid
            {
                public string  _keyDataField = "Task_UID";
                public string  _parentDataField ="Task_Parent_UID" ;
                public string _nameDataField = "Task_Name";
                public string _plusImageUrl = "/_layouts/images/whiteplus.gif";
                public string _minusImageUrl = "/_layouts/images/whiteminus.gif";

                //public   string   _displayDataField 

                public bool _defaultExpand = true  ;
                public string _defaultDisplay = "";

                public DataTable _treeTable;


                //////


                public enum CustomColumnAlign
                {
                    Left, Right
                }

                public CustomColumnAlign _align = CustomColumnAlign.Left;
                public string _checkBoxID = "CheckBox1";
                public Color _mouseOverColor;
                public DataControlFieldCollection _columnCol = new DataControlFieldCollection();

                [Browsable(true)]
                [Description("所建立的checkBox所在对齐方式")]
                [Category("Setting")]
                public CustomColumnAlign Align
                {
                    get
                    {
                        return _align;
                    }
                    set
                    {
                        _align = value;
                    }
                }

                [Browsable(true)]
                [Description("所建立的checkBoxID")]
                //  [DefaultValue("CheckBox1")]
                [Category("Setting")]
                public string CheckBoxID
                {
                    get
                    {
                        return _checkBoxID;
                    }
                    set
                    {
                        _checkBoxID = value;
                    }
                }

     

                //鼠标经过行时的颜色#region 鼠标经过行时的颜色
                [Browsable(true)]
                [Description("鼠标经过行的颜色")]
                [DefaultValue("")]
                [Category("Setting")]

                public Color MouseOverColor
                {
                    get
                    {
                        return _mouseOverColor;
                    }
                    set
                    {
                        _mouseOverColor = value;
                    }
                }

                ///////////////

                ///   <summary>  
                ///   折叠图标路径  
                ///   </summary>  
                [Bindable(true),
                Category("Setting")]
                public string MinusImgUrl
                {
                    set
                    {
                        _minusImageUrl = value;
                    }
                }

                ///   <summary>  
                ///   展开图标路径  
                ///   </summary>  
                [Bindable(true),
                Category("Setting")]
                public string PlusImgUrl
                {
                    set
                    {
                        _plusImageUrl = value;
                    }
                }

                ///   <summary>  
                ///   设置默认折叠状态  
                ///   </summary>  
                public bool DefaultExpand
                {
                    set
                    {
                        if (value) _defaultDisplay = "";
                        else _defaultDisplay = "none";
                        _defaultExpand = value;
                    }
                }

                ///   <summary>  
                ///   数据源表格主键列名  
                ///   </summary>  
                [Bindable(true),
                Category("Setting")]
                public string   KeyDataField
                {
                    get
                    {
                        return _keyDataField;
                    }

                    set
                    {
                        _keyDataField = value;
                    }
                }

                ///   <summary>  
                ///数据源表格父ID   列名  
                ///   </summary>  
                [Bindable(true),
                Category("Setting")]
                public string   ParentDataField
                {
                    get
                    {
                        return _parentDataField;
                    }

                    set
                    {
                        _parentDataField = value;
                    }
                }

                public Unit _imageWidth = new Unit("20");
                ///   <summary>  
                ///   折叠展开图标宽度  
                ///   </summary>  
                [Bindable(true),
                Category("Setting")]
                public Unit ImageWidth
                {
                    set
                    {
                        _imageWidth = value;
                    }
                }

                ///   <summary>  
                ///   折叠展开图标高度  
                ///   </summary>  
                public Unit _imageHeight = new Unit("20");
                [Bindable(true),
                Category("Setting")]
                public Unit ImageHeight
                {
                    set
                    {
                        _imageHeight = value;
                    }
                }

                // ///   <summary>  
                // ///   作为树文本显示的列名  
                // ///   </summary>  
                // public   string   DisplayDataField  
                // {  
                // get  
                // {  
                // return   _displayDataField;  
                // }  
                //  
                // set  
                // {  
                // _displayDataField   =   value;  
                // }  
                // }  

                ///   <summary>  
                ///   作为树文本显示的列名  
                ///   </summary>  
                [Bindable(true),
                Category("Setting")]
                public string NameDataField
                {
                    get
                    {
                        return _nameDataField;
                    }

                    set
                    {
                        _nameDataField = value;
                    }
                }

                ///   <summary>  
                ///   设置或获取数据源(数据源类型必须是DataTable)  
                ///   </summary>  
                ///  

               
                public override object DataSource
                {
                    get
                    {
                        return base.DataSource;
                    }
                    set
                    {
                        base.DataSource = value;

                        if (this.Site != null && this.Site.DesignMode) return;


                        if (value.GetType() != typeof(DataTable))
                            throw new Exception("只支持DataTable");

                        //_depth   =   0   ;  

                        _treeTable = new DataTable();

                        DataTable initTable = (DataTable)value;

                        foreach (DataColumn col in initTable.Columns)
                        {
                            _treeTable.Columns.Add(col.ColumnName);
                        }

                        // if(   _treeTable.Columns.Contains("Depth")   )  
                        // _treeTable.Columns.Add(   new   DataColumn(   "Depth"   ,   typeof(int)   )   );  
                        //  
                        // if(   _treeTable.Columns.Contains("HaveChildren")   )  
                        // _treeTable.Columns.Add(   new   DataColumn(     "HaveChildren"   ,   typeof(bool)   )   );  

                        Guid g1 = new Guid("378aa44f-7ef1-4e54-ba0d-42b4381b06e6");
                       

                        format(g1.ToString (), 0, (DataTable)value, _treeTable); ;

                        base.DataSource = _treeTable;
                        this.DataBind();
                    }
                }

                // public   override   void   DataBind()  
                // {  
                //  
                // base.DataBind   ();  
                // }  

                //public   int   _depth   =   0   ;  
                ///   <summary>  
                ///   格式化原始数据源  
                ///   </summary>  
                ///   <param   name="parentId"></param>  
                ///   <param   name="depth"></param>  
                ///   <param   name="initTalbe"></param>  
                ///   <param   name="formatTable"></param>  
                ///   <returns></returns>  
                ///  
                ////////////////////////////////

     


                //protected override ArrayList CreateColumnSet(PagedDataSource dataSource, bool useDataSource)
                //{
                //    ArrayList col = base.CreateColumnSet(dataSource, useDataSource) as ArrayList;
                //    CreatCheckBox(col);
                //    _columnCol.Clear();
                //    foreach (DataControlField c in col)
                //    {
                //        _columnCol.Add(c);
                //    }
                //    return col;
                //}

                //public void CreatCheckBox(ArrayList col)
                //{
                //    TemplateField checkColumn = new TemplateField();
                //    checkColumn.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                //    checkColumn.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
                //    CheckBoxItemTemplate cbItemTemplate = new CheckBoxItemTemplate();
                //    CheckBoxItemTemplate.CheckBoxItemId = _checkBoxID;
                //    checkColumn.ItemTemplate = cbItemTemplate;
                //    CheckBoxHeaderTemplate cbHeaderTemplate = new CheckBoxHeaderTemplate();
                //    checkColumn.HeaderTemplate = cbHeaderTemplate;
                //    if (Align == CustomColumnAlign.Left)
                //    {
                //        col.Insert(0, checkColumn);
                //    }
                //    else if (Align == CustomColumnAlign.Right)
                //    {
                //        col.Add(checkColumn);
                //    }
                //}

                //public class CheckBoxItemTemplate : ITemplate
                //{
                //    public static string _CheckBoxID;

                //    public static string CheckBoxItemId
                //    {
                //        get
                //        {
                //            return _CheckBoxID;
                //        }
                //        set
                //        {
                //            _CheckBoxID = value;
                //        }
                //    }
                //    public void InstantiateIn(Control container)
                //    {
                //        CheckBox cb = new CheckBox();
                //        cb.ID = _CheckBoxID;
                //        container.Controls.Add(cb);
                //    }
                //}
                //public class CheckBoxHeaderTemplate : ITemplate
                //{
                //    public void InstantiateIn(Control container)
                //    {
                //        Label la = new Label();
                //        la.Text = "Select";
                //        container.Controls.Add(la);
                //    }
                //}
    ////////////////////////////////////////////////////////////////////////////////////////

                public class ColumnTemplate : ITemplate
                {
                    private string ControlId = "";
                    private bool blnEnable;
                    public ColumnTemplate(string strId, bool enable)
                    {
                        ControlId = strId;
                        blnEnable = enable;
                    }
                    public void InstantiateIn(Control container)
                    {
                        CheckBox myCheckBox = new CheckBox();
                        myCheckBox.Checked = true;
                        myCheckBox.ID = ControlId;
                        myCheckBox.Enabled = blnEnable;
                        container.Controls.Add(myCheckBox);
                    }

                }

    ////////////////////////////////////////////////////////////////////////////////////////////

              


                public bool format(string parentId, int depth, DataTable initTalbe, DataTable formatTable)
                {
                   
                    DataRow[] rows = initTalbe.Select(this._parentDataField + " = '" + parentId + "'and  "+this._keyDataField +" <> '" + parentId +" '" );

                    string name, key, imgUrl, style = "";

                    int i;


                    if (this._defaultExpand == true)
                        imgUrl = this._minusImageUrl;
                    else
                        imgUrl = this._plusImageUrl;

                    if (this._imageWidth.IsEmpty == false)
                        style = "   width=" + _imageWidth.ToString();

                    if (this._imageHeight.IsEmpty == false)
                        style = "   height=" + _imageHeight.ToString();

                    foreach (DataRow r in rows)
                    {
                        DataRow newRow = formatTable.NewRow();
                        formatTable.Rows.Add(newRow);

                        //newRow["Depth"]   =   depth   ;  

                        foreach (DataColumn col in initTalbe.Columns)
                        {
                            newRow[col.ColumnName] = r[col.ColumnName];
                        }
                       

                        key = newRow[this._keyDataField].ToString();

                        if (format(r[this._keyDataField].ToString (), depth + 1, initTalbe, formatTable))
                        {
                            name = "<img   " + style + "   id='" + this.ClientID  + "_img_" + key + "'   src='" + imgUrl
                            + "'   onclick=\"TreeDataGrid_changeDisplay(   '" + this.ClientID + "'   ,     '" + key + "'   ,   '" +
                            getChildRowClientIds(initTalbe, key) + "'   )\"   style='cursor:hand'>"
                            + newRow[this._nameDataField].ToString();
                        }
                        else
                        {
                            name = "&nbsp;" + newRow[this._nameDataField].ToString();
                        }

                        for (i = 0; i < depth; i++)
                            name = "   &nbsp;   &nbsp;   " + name;

                        newRow[this._nameDataField] = name;

                    }

                    return rows.Length > 0 ? true : false;
                }

                public string getImgID(string key)
                {
                    return this.ClientID  + "_img_" + key;
                }

                ///   <summary>  
                ///   获取所有子行ID列表:   ,ParentId.Id,ParentId.Id,  
                ///   </summary>  
                ///   <param   name="t"></param>  
                ///   <param   name="parentId"></param>  
                ///   <returns></returns>  
                public string getChildRowClientIds(DataTable t, string parentId)
                {
                    DataRow[] rows = t.Select(this._parentDataField + "='" + parentId + "'");

                    string ids = ",";
                    string lowIds = "";
                    foreach (DataRow r in rows)
                    {
                        //if(   ids   !=   ""   )   ids   +=   ","   ;  
                        ids += parentId + "." + r[this._keyDataField].ToString() + ",";   //this.ID   +   "_"+  

                        lowIds = getChildRowClientIds(t, r[this._keyDataField].ToString());
                        if (lowIds != ",") ids += lowIds + ",";

                    }
                    return ids;
                }

                protected override void OnItemCreated(DataGridItemEventArgs e)
                {
                    base.OnItemCreated(e);

                    if (this.Site != null && this.Site.DesignMode) return;

                    DataRowView row = e.Item.DataItem as DataRowView;

                    if (row == null) return;

                    string sId = row[this._keyDataField].ToString();
                    //string pId = row[this._parentDataField].ToString();

                    e.Item.Attributes.Add("id", this.ClientID + "_" + sId);

                   // if (row[this._parentDataField].ToString() == "378aa44f-7ef1-4e54-ba0d-42b4381b06e6")
                    //    e.Item.Style.Add("display", "");
                   // else
                        e.Item.Style .Add ("display",_defaultDisplay);
                }

                protected override void OnInit(EventArgs e)
                {
                    base.OnInit(e);


    ////////////////////////////////////////////////////////////////////////////////////////////

                    TemplateColumn newtempColumn;
                    newtempColumn = new TemplateColumn();
                    newtempColumn.HeaderText = "Active";
                    newtempColumn.HeaderStyle.Width = Unit.Pixel(50);
                    ColumnTemplate cTemp;
                    cTemp = new ColumnTemplate("CheckBox1", false);
                    newtempColumn.ItemTemplate = cTemp;
                    cTemp = new ColumnTemplate("CheckBox1", true);
                    newtempColumn.EditItemTemplate = cTemp;
                    this.Columns.Add(newtempColumn);


    //////////////////////////////////////////////////////////////////////////////////////////

                 
                   

                    if (this.Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), jsKey) == false)
                    {

                        string js = @"<script   language=""javascript"" runat=""server"">  
                         function   TreeDataGrid_changeDisplay(   parentId   ,   id   ,   ids   ){  
                        //alert(ids);return;  
       
                       if(   ids   ==   "",""   )   return   ;  
                       arr   =   ids.split("","");  
       
                       pref=parentId   +   ""_""   ;  
       
                      //obj   =   eval( ""  pref   +   arr[1].split('.')[1]    "" );  
                     obj    =    document.getElementById(eval(""pref+   arr[1].split('.')[1]"")) ;
                      display   =   """";  
                      if(   obj.style.display   ==   """"   )  
                      display   =   ""none""   ;" +

                         "\n   imgId   =   pref   +   'img_'   +   id   ;" +
                         "minusImg='" + this._minusImageUrl + "';" +
                         "plusImg='" + this._plusImageUrl + "';" +

                         "\n   if(   display   ==   \"\"   )   document.getElementById( eval(\"imgId\")  ).src=   minusImg   ;" +
                         "\n   else     document.getElementById( eval(\"imgId\")  ).src=   plusImg   ;\n" +

                         @"  
                           for(   i   =   1   ;   i   <   arr.length   ;   i   ++){  
                         //obj   =   eval(   ""document.all.""+arr[i]   +   """"   )  
                        if(   arr[i]   ==   ''   )   continue   ;  
                        arrCId   =   arr[i].split('.');  
                        if(   display   ==   ''   &&   arrCId[0]   !=   id   )   continue   ;        
                      // obj   =   eval(  "" pref   +   arrCId[1]  ""   );  
                         obj    =    document.getElementById(eval(""pref   +   arrCId[1]"") );
                       if(obj==null)   continue   ;    
                          obj.style.display   =   display   ;  
       
                          if(   display   ==   'none'   ){  
                          imgId   =   pref   +   'img_'   +   arrCId[1]   ;  
                         img   =   document.getElementById( eval(""imgId"") )  ;  
                         if(   img   ==   null   )   continue   ;  
                         if(   display   ==   ''   )   document.getElementById( eval(""imgId"")).src=   minusImg   ;  
                         else     document.getElementById( eval(""imgId"") ).src=   plusImg   ;  
                           }  
       
                           }  
                           }  
                              <" + "/script>";  

                      this.Page.ClientScript.RegisterStartupScript(this.GetType(), jsKey, js);
                     
                    }

                }

     

                ///   <summary>  
                ///   将此控件呈现给指定的输出参数。  
                ///   </summary>  
                ///   <param   name="output">   要写出到的   HTML   编写器   </param>  
                //protected override void Render(HtmlTextWriter output)
                //{
                //    output.Write(output );
                //}  
            }

               ////自定义控件treeGrid   --END

     
    }

    }

     

      

    2009年5月22日 1:06
  • 你好,
    你说你的完全由“webpart来管理和展现”什么意思?
    Microsoft Online Community Support
    2009年5月22日 2:23
  • 高手好!我说的意思是我自己并没有写任何的展示自定义控件DATAGRID的展示代码!这个CHECKBOX列是动态生成的,所有的展示代码都是WEB PART自己展现的。所以,我现在想着是不是我需要OVERRIDE一下它的展现函数,但是不知道是哪个出了问题,那么高手您看呢?是展现出了问题,还是说数据源出了问题!头疼死了,这个问题都延误了项目两周了!我想这个问题可能是个深层次的问题,表面上看不出任何问题来!

    2009年5月24日 1:08