Link to home
Start Free TrialLog in
Avatar of Isaac
IsaacFlag for United States of America

asked on

looping a list

I have a web part that displays a list.  Each item has a checkbox that should be checked for 'completed'.  If the checkbox is checked and submit is clicked, it should then be copied to another list.  My code below still copy's everything over to another list even if it's not checked.

Please help!

Thanks.
foreach(SPListItem item in sourceList.Items)
        {

            foreach (GridViewRow row in GridView1.Rows)
            {
                HiddenField hdID = (HiddenField)row.FindControl("hdID");
                CheckBox complete = (CheckBox)row.FindControl("complete");
                if (hdID.ToString() != null && complete.Checked)
                {
                    byte[] fileBytes = item.File.OpenBinary();
                    string destUrl = destList.RootFolder.Url + "/" + item.File.Name;
                    SPFile destFile = destList.RootFolder.Files.Add(destUrl, fileBytes, true /*overwrite*/);

                    // add the metadata to File            
                    SPListItem destItem = destFile.Item;
                    destItem["STATUS"] = "REROUTE";
                    destItem["CASE NUMBER"] = "CASE NUMBER";
                    destItem["PRIORITY"] = "Y";
                    destItem["PRIORITY CODE"] = "PRIORITY CODE";
                    destItem["COMPLETE"] = "YES";

                    destItem.Update();
                }
            }
        }

Open in new window

Picture1.png
Avatar of Miguel Oz
Miguel Oz
Flag of Australia image

Modify line 8 to:
if (hdID!= null && !String.IsNullOrEmpty(hdID.Value) && complete.Checked)

and put a breakpoint in line 10, and see if you can hit the breakpoint.
If breakpoint is not hit you need to check if your hidden value is properly set in your javascript and /or you are keeping the checkbox state (e.g. viewstate, controlstate)
Avatar of Isaac

ASKER

Oh...do I need JavaScript because I'm not using it.
You may require Javascript , but I need to know the debugging results that I asked for in my previous post.
Please post your gridview markup and how you are binding the gridview
Avatar of Isaac

ASKER

Please see below for the code.
Thanks.
<%@ Control Language="C#" AutoEventWireup="true" %>
<%@ Register assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" namespace="Microsoft.SharePoint.WebControls" tagprefix="SharePoint" %>
<%@ Register Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" namespace="Microsoft.SharePoint" tagprefix="SharePoint" %>

<script runat="server">

    protected void Button1_Click(object sender, EventArgs e)
    {
        msg.Text = "<style=color:red;font-weight:bold>Files copied over</style>";
        SPSite mySite = SPContext.Current.Site;
        SPWeb myWeb;
        SPList sourceList;
        SPList destList;     
        
        myWeb = SPContext.Current.Web;
        sourceList = (SPDocumentLibrary)myWeb.Lists["Hotline List"];
        SPListItemCollection results = sourceList.Items;

        destList = (SPDocumentLibrary)myWeb.Lists["HOTLINE"];   
                
        foreach(SPListItem item in sourceList.Items)
        {
            int num = 0;
            foreach (GridViewRow row in GridView1.Rows)           
            {
            
            HiddenField hdID = (HiddenField)row.FindControl("hdID");
            CheckBox complete = (CheckBox)row.FindControl("complete");
          
                num += 1;
            if (hdID == null && complete.Checked)
            {
                    byte[] fileBytes = this.complete.text;;
                    string destUrl = destList.RootFolder.Url + "/" + item.File.Name;
                    SPFile destFile = destList.RootFolder.Files.Add(destUrl, fileBytes, true /*overwrite*/);

                    // add the metadata to File            
                    SPListItem destItem = destFile.Item;
                    destItem["STATUS"] = "REROUTE";
                    destItem["CASE NUMBER"] = "CASE NUMBER";
                    destItem["PRIORITY"] = "Y";
                    destItem["PRIORITY CODE"] = "PRIORITY CODE";
                    destItem["COMPLETE"] = "YES"+num;

                    destItem.Update();
            }
            }
        }        
    }
    
    

    protected void Page_Load(object sender, EventArgs e)
    {
    
    }
  

</script>

<style type="text/css">
    .style1
    {
        width: 100%;
    }
</style>

<SharePoint:SPDataSource ID="HotLineCase" 
                  runat="server"
                  DataSourceMode="List"                  
                  SelectCommand="<Query><OrderBy><FieldRef Name='Status' /></OrderBy></Query>">
      <selectParameters>
            <asp:Parameter Name="WebID" DefaultValue="RootWeb" />
            <asp:Parameter Name="ListName" DefaultValue="Hotline List" />
      </selectParameters>                  
</SharePoint:SPDataSource>

<table class="style1">
        <tr>
            <td>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
    DataSourceID="HotLineCase" Font-Names="Verdana" Font-Size="X-Small" 
    HorizontalAlign="Center" GridLines="Horizontal">
    <RowStyle HorizontalAlign="Center" />
    <Columns>
        <asp:TemplateField HeaderText="Complete">
        <ItemTemplate>
            <asp:CheckBox runat="server" id="complete" Text="" />
        </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField HeaderText="Type" DataField="Type" />
        <asp:TemplateField HeaderText="Case Number">
            <ItemTemplate>
                <asp:TextBox ID="caseNumber" runat="server"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField HeaderText="Name" DataField="Name" />
        <asp:TemplateField HeaderText="STATUS">
        <ItemTemplate>
            <asp:DropDownList ID="status" runat="server">
                <asp:ListItem Value="...."></asp:ListItem>
                <asp:ListItem Value="Reroute">Reroute</asp:ListItem>
                <asp:ListItem Value="Spam">Spam</asp:ListItem>
            </asp:DropDownList>
        </ItemTemplate>        
        </asp:TemplateField>
        <asp:BoundField HeaderText="Modified" DataField="Modified" />
        <asp:BoundField HeaderText="Modified By" DataField="Modified By" />
        <asp:TemplateField HeaderText="Priority Code">
            <ItemTemplate>
            <asp:DropDownList ID="priorityCode" runat="server">
                <asp:ListItem Value="">....</asp:ListItem>
                <asp:ListItem Value="Priority">Priority</asp:ListItem>
                <asp:ListItem Value="Routine">Routine</asp:ListItem>
            </asp:DropDownList>                
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Priority">
            <ItemTemplate>
               <asp:DropDownList ID="priority" runat="server">
                <asp:ListItem Value="">.....</asp:ListItem>
                <asp:ListItem Value="Yes">Yes</asp:ListItem>
               <asp:ListItem Value="No">No</asp:ListItem>
            </asp:DropDownList>
            </ItemTemplate>        
        </asp:TemplateField>      
        <asp:TemplateField>
            <ItemTemplate>
                <asp:HiddenField ID="hdID" runat="server" Value='<%# Eval("ID") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    <HeaderStyle HorizontalAlign="Center" BackColor="#CCCCCC" />
    <AlternatingRowStyle BackColor="#EEEEEE" />
</asp:GridView>
            </td>
        </tr>
        <tr>
            <td align="center"><asp:Button ID="Button1" runat="server" Text="Submit" 
                    onclick="Button1_Click" /></td>
        </tr>
        <tr>
            <td align="center">
                <asp:Label ID="msg" runat="server" Text=""></asp:Label></td>
        </tr>
    </table>

Open in new window

Avatar of Isaac

ASKER

Line 33 is actually supposed to be

byte[] fileBytes = item.File.OpenBinary();
I still need to see your debugging results.

From the posted code, I am assuming that you are doing dynamic binding, please post this code as well, Where is it done (at Page_load event)?
How are you keeping state of your gridview afte initial binding (Viewstate only?)?
Avatar of Isaac

ASKER

I was unable to attach a process to debug.  I kept getting an error that says I did not have enough permissions.

This is the other piece of code:

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;

namespace WSPHotlineProj
{
    [Guid("6d5b1637-427e-4549-b15a-6bda07cb71ef")]
    public class WSPHotlineProj : Microsoft.SharePoint.WebPartPages.WebPart
    {
        private bool _error = false;
        private string _myProperty = null;

        Control _WebUserControl;
        String err;

        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("My Property Group")]
        [WebDisplayName("MyProperty")]
        [WebDescription("Meaningless Property")]
        public string MyProperty
        {
            get
            {
                if (_myProperty == null)
                {
                    _myProperty = "Hello SharePoint";
                }
                return _myProperty;
            }
            set { _myProperty = value; }
        }


        public WSPHotlineProj()
        {
            this.ExportMode = WebPartExportMode.All;
        }

        /// <summary>
        /// Create all your controls here for rendering.
        /// Try to avoid using the RenderWebPart() method.
        /// </summary>
        protected override void CreateChildControls()
        {
            if (!_error)
            {
                try
                {

                    base.CreateChildControls();
                    try
                    {
                        this.Controls.Clear();
                        this._WebUserControl = this.Page.LoadControl(@"~/_controltemplates/WebUserControl.ascx");
                        this.Controls.Add(this._WebUserControl);
                    }
                    catch (Exception e)
                    {
                        err = e.Message;
                    }
                    // Your code here...
                    this.Controls.Add(new LiteralControl(this.MyProperty));
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            try
            {
                _WebUserControl.RenderControl(writer);
            }
            catch(Exception e)
            {
                writer.Write(e.Message + " : " + err);
            }            
        }
        /// <summary>
        /// Ensures that the CreateChildControls() is called before events.
        /// Use CreateChildControls() to create your controls.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            if (!_error)
            {
                try
                {
                    base.OnLoad(e);
                    this.EnsureChildControls();

                    // Your code here...
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }

        /// <summary>
        /// Clear all child controls and add an error message for display.
        /// </summary>
        /// <param name="ex"></param>
        private void HandleException(Exception ex)
        {
            this._error = true;
            this.Controls.Clear();
            this.Controls.Add(new LiteralControl(ex.Message));
        }
    }
}
Log as administrator, so you can have full access to debug your code.
Your posted ocde does not show how the gridview binds the data. Please post that code
Avatar of Isaac

ASKER

This is part of my code that I posted above that does the binding. It's all in one file:


<SharePoint:SPDataSource ID="HotLineCase" 
                  runat="server"
                  DataSourceMode="List"                  
                  SelectCommand="<Query><OrderBy><FieldRef Name='Status' /></OrderBy></Query>">
      <selectParameters>
            <asp:Parameter Name="WebID" DefaultValue="RootWeb" />
            <asp:Parameter Name="ListName" DefaultValue="Hotline List" />
      </selectParameters>                  
</SharePoint:SPDataSource>

<table class="style1">
        <tr>
            <td>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
    DataSourceID="HotLineCase" Font-Names="Verdana" Font-Size="X-Small" 
    HorizontalAlign="Center" GridLines="Horizontal">
    <RowStyle HorizontalAlign="Center" />
    <Columns>
        <asp:TemplateField HeaderText="Complete">
        <ItemTemplate>
            <asp:CheckBox runat="server" id="complete" Text="" />
        </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField HeaderText="Type" DataField="Type" />
        <asp:TemplateField HeaderText="Case Number">
            <ItemTemplate>
                <asp:TextBox ID="caseNumber" runat="server"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField HeaderText="Name" DataField="Name" />
        <asp:TemplateField HeaderText="STATUS">
        <ItemTemplate>
            <asp:DropDownList ID="status" runat="server">
                <asp:ListItem Value="...."></asp:ListItem>
                <asp:ListItem Value="Reroute">Reroute</asp:ListItem>
                <asp:ListItem Value="Spam">Spam</asp:ListItem>
            </asp:DropDownList>
        </ItemTemplate>        
        </asp:TemplateField>
        <asp:BoundField HeaderText="Modified" DataField="Modified" />
        <asp:BoundField HeaderText="Modified By" DataField="Modified By" />
        <asp:TemplateField HeaderText="Priority Code">
            <ItemTemplate>
            <asp:DropDownList ID="priorityCode" runat="server">
                <asp:ListItem Value="">....</asp:ListItem>
                <asp:ListItem Value="Priority">Priority</asp:ListItem>
                <asp:ListItem Value="Routine">Routine</asp:ListItem>
            </asp:DropDownList>                
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Priority">
            <ItemTemplate>
               <asp:DropDownList ID="priority" runat="server">
                <asp:ListItem Value="">.....</asp:ListItem>
                <asp:ListItem Value="Yes">Yes</asp:ListItem>
               <asp:ListItem Value="No">No</asp:ListItem>
            </asp:DropDownList>
            </ItemTemplate>        
        </asp:TemplateField>      
        <asp:TemplateField>
            <ItemTemplate>
                <asp:HiddenField ID="hdID" runat="server" Value='<%# Eval("ID") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    <HeaderStyle HorizontalAlign="Center" BackColor="#CCCCCC" />
    <AlternatingRowStyle BackColor="#EEEEEE" />
</asp:GridView>
            </td>
        </tr>
        <tr>
            <td align="center"><asp:Button ID="Button1" runat="server" Text="Submit" 
                    onclick="Button1_Click" /></td>
        </tr>
        <tr>
            <td align="center">
                <asp:Label ID="msg" runat="server" Text=""></asp:Label></td>
        </tr>
    </table>

Open in new window

Avatar of Isaac

ASKER

I bind tthe list to the gridview with this code:

<SharePoint:SPDataSource ID="HotLineCase"
                 runat="server"
                 DataSourceMode="List"
                 SelectCommand="<Query><OrderBy><FieldRef Name='Status' /></OrderBy></Query>">
     <selectParameters>
           <asp:Parameter Name="WebID" DefaultValue="RootWeb" />
           <asp:Parameter Name="ListName" DefaultValue="Hotline List" />
     </selectParameters>
</SharePoint:SPDataSource>
ASKER CERTIFIED SOLUTION
Avatar of Isaac
Isaac
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Isaac

ASKER

After much web searching, I finally got a solution.