Saving data to a Document Library from a web page

Hi

In my code below I take data that is entered on a page and save it into a Sharepoint 2007 Document Library.
All the fields are text bar 'Category' - that is a lookup to a List.

Everything saves fine apart from the value in Category

docProperties["Category"] = ddlCategory.SelectedValue;

Anyone any ideas?

Thanks
H


docProperties["Category"] = ddlCategory.SelectedValue;
String documentLibraryName = "Documents";
            
            using (SPSite oSite = new SPSite(sharePointSite))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    if (System.IO.File.Exists(fileToUpload))
                    {
                        SPFolder myLibrary = oWeb.Folders[documentLibraryName];

                        if (myLibrary.Name == "")
                        {
                        }

                        // Prepare to upload 
                        Boolean replaceExistingFiles = true;
                        String fileName = System.IO.Path.GetFileName(fileToUpload);
                        FileStream fileStream = File.OpenRead(fileToUpload);

                        Hashtable docProperties = new Hashtable();
                        //docProperties["DocumentTitle"] = tbTitle.Text;
                        docProperties["Title"] = tbTitle.Text;
                        docProperties["Category"] = ddlCategory.SelectedValue;
                        docProperties["Circulation"] = tbCirculation.Text;
                        docProperties["Page"] = tbPage.Text;
                        docProperties["Publication"] = tbPublication.Text;
                        docProperties["Publication Author"] = tbAuthor.Text;
                        //docProperties["Publication_x0020_Author"] = tbAuthor.Text;
                        //x0020
                        docProperties["Publication Date"] = dtcPublicationDate.SelectedDate;
                        //docProperties["Publication_x0020_Date"] = dtcPublicationDate.SelectedDate;
                        docProperties["Summary"] = tbSummary.Text;
                        docProperties["Rank"] = tbRank.Text;

                        
                        // Upload document 
                        SPFile spfile = myLibrary.Files.Add(fileName, fileStream, docProperties, replaceExistingFiles);
                        
                        // Commit  
                        myLibrary.Update();

                    }
                    else
                    {
                        throw new FileNotFoundException("File not found.", fileToUpload);
                    }
                }
            }

Open in new window

hmcgeehanAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

zadeveloperCommented:
please attach the code where you populate ddlCategory

also supply types for category (is it an int, guid, string etc...)
0
Kumaraswamy RCommented:
0
hmcgeehanAuthor Commented:
Hi zadeveloper

I've attached the code.
The list 'Media Coverage Categories' is a one column list with a value 'Title' this is a single line of text.

thanks
ddlCategory.DataSource = GetCategories();
                                ddlCategory.DataTextField = "Title";
                                ddlCategory.DataValueField = "Title";

                                ddlCategory.DataBind();
                        



private DataTable GetCategories()
        {

            string query = "<Query><OrderBy><FieldRef Name='Title' /></OrderBy></Query>";
            DataTable spDataTable = ExecuteCamlQuery("Media Coverage Categories", query);

            return spDataTable;
        }

Open in new window

0
IT Pros Agree: AI and Machine Learning Key

We’d all like to think our company’s data is well protected, but when you ask IT professionals they admit the data probably is not as safe as it could be.

hmcgeehanAuthor Commented:
BTW when I put in breakpoints to my code to debug it definitely picks up the string value for ddlCategory.SelectedValue;
0
RaphilassCommented:
what ype of field is the category field in the sharepoint list...a text field or a choice / lookup
0
hmcgeehanAuthor Commented:
It is a Lookup.

So the document librry 'Documents' has numerous fields and one of them is a lookup to the list 'Media Coverage Categories'

thanks

0
RaphilassCommented:
I think this is a similar problem i had some time ago....I wanted to write a value from a dropdown list on an application page back into a sharepoint list where is was stored as a lookup value. you cannot just write text back in.
 You need to define a variable as an SPFieldLookupValue then assign the value you want to write in to this field, then write the variable back to sharepoint.
Hope this makes sense (and works :)  )
 

SPFieldLookupValue categoryValue = default(SPFieldLookupValue);
categoryValue = new SPFieldLookupValue((int)this.ddlCategory.SelectedValue, this.ddlCategory.SelectedItem.ToString);
docProperties["Category"] = categoryValue ;

Open in new window

0
RaphilassCommented:
ps... my code was in VB,  i dont know C# to well so used a convertor...you might need to check the syntax ;)
0
hmcgeehanAuthor Commented:
thanks ...

so i do this ...

SPFieldLookupValue categoryValue = default(SPFieldLookupValue);
                        categoryValue = new SPFieldLookupValue(ddlCategory.SelectedItem.ToString());
                        docProperties["Category"] = categoryValue;

and it gives me an error ...

Value does not fall within the expected range.

pointing to line
categoryValue = new SPFieldLookupValue(ddlCategory.SelectedItem.ToString());
                       
Now I did a debug and the value it had for
ddlCategory.SelectedItem
was 'test3'

My list is made up of 6 values
test1, test2, test3 etc .... so the value is definitely there.

I think i might be doing something wrong :)

thanks for the help.
0
RaphilassCommented:
your missing part of the SPFieldLookupValue
it should be categoryValue = new SPFieldLookupValue(value as integer(the selected index), value as string (the selected text));
I am fairly sure the list you are selecting from will need to match the list lookup in the sharepoint list. How are you populating the list you are selecting from ? manually creating the lookup choices or populating from a datasource ?
0
hmcgeehanAuthor Commented:
or i thought i should try this ...

SPFieldLookupValue categoryLookup = new SPFieldLookupValue(Convert.ToString(myLibrary.Item["Category"]));
docProperties["Category"] = categoryLookup.LookupValue;

but it says ....

The object specified does not belong to a list.

and it points to the first line.
0
hmcgeehanAuthor Commented:
hi Raphilass

I bind the dropdownlist to a datasource (see code below)

then in my code when I try to assign the value to the list I do this ...

docProperties["Category"] = ddlCategory.SelectedValue;
                       
and when I check the code as it runs it has a text value for 'ddlCategory.SelectedValue'
It is the same text as an entry on the lookup list

thanks for the help
0
hmcgeehanAuthor Commented:
How would I find out the selected index of the drop down list?

All I have to work off is the Selected Text or Selected Value and they're both the same.
My Lookup list is just a list of strings.

thanks
0
RaphilassCommented:
Basically as i understand it you need to create a value that matches the lookup values in the sharepoint list, so.....
If your lookup values in the sharepoint list (the one you want to write to) are provided from another sharepoint list of value, the entries in the list of values will have an integer (the record ID) and the record name (Usually the title page).
so you list will look like
1   Category 1
2   Category 2
3   Category 3
and so on.
On the drop down list you are trying to write values back to sharepoint from you have 3 potential values to write back, the selected value, the selected tex or the selected index. When you create the SPFieldLookupValue object you should be adding an integer,string as the list above.
If the integer does not match with the string as in the list above you will get errors. so if you select list is in a different order to the SP List then you will find it hard to write back. I usually use the same source in my application page as i have in sharepoint then i am sure they match....so to populate the Drop Down list i would use the code below. Here i pick up the list i want to read from and use for each to go through line by line and add as values to the drop down list in my app page. You can use caml queries to filter the source list if necessary.
I hope this makes sense, basically match the values you want to squirt back in to the lookup


{
    if (!(IsPostBack == true)) {
        {
            SPListItemCollection listItems = PriorityList.Items;
            
            foreach (SPListItem currItem in listItems) {
                {
                    ddlPriority.Items.Add(new ListItem(currItem.Item("Title").ToString, currItem.Item("ID").ToString));
                }
            }
            ddlPriority.SelectedIndex = 1;
        }
    }
}

Open in new window

0
RaphilassCommented:
selected index is the position the value take in the list, cant remeber if it counts from 0 or 1 but each selection in the list is assigned this value automatically by .net when it is populated, incrementing by 1 for each value......basically you would use ddlCategory.selcetedindex
0
hmcgeehanAuthor Commented:
thanks Raphilass:

We're on the same wavelenght!

So I do this ...

SPFieldLookupValue categoryValue = default(SPFieldLookupValue);
                        categoryValue = new SPFieldLookupValue(ddlCategory.SelectedIndex, ddlCategory.SelectedItem.ToString());
                        docProperties["Category"] = categoryValue;

And that works fine!

But when I try to upload the document to the document library with the properties I get this ....

"Only String, int, and DateTime datatypes can be used as the value in Properties."

// Upload document
 SPFile spfile = myLibrary.Files.Add(fileName, fileStream, docProperties, replaceExistingFiles);    

This is because docProperties now contains the SPFieldLookupValue

See attached screenshot

thanks

                   
upload-error.jpg
0
RaphilassCommented:
ok, I must admit mine is not posting back to a doc library :)
 
Maybe you can try and get away with the original code,  did you try making the value of the dropdown list you are choosing from the ID of the record or writing back the selected index instead of the sected value in your original code ?
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
hmcgeehanAuthor Commented:
You're a legend!

It needed the SelectedIndex of the DropDownList and not the SelectedValue.

Thanks so much for your patience and help!
0
RaphilassCommented:
:) sorry it took so long lol
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SharePoint

From novice to tech pro — start learning today.