SPListItem dont Add new Item
-
08-10-2020 - |
Вопрос
class Vote
{
public static void DoneVote(DataTable table)
{
string siteUrl = "...";
try
{
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.OpenWeb())
{
foreach (DataRow row in table.Rows)
{
SPList list = web.Lists.TryGetList("ListName");
if (list != null) {
SPListItem itemToAdd = list.AddItem();
itemToAdd["Title"] = "DA0000";
itemToAdd["IdProject"] = "10";
itemToAdd["DateOf"] = DateTime.Today;
itemToAdd["Type"] = "1";
itemToAdd["Project"] = "1";
itemToAdd.Update();
}
}
}
}
}
catch (Exception e)
{
//Log errors
Console.WriteLine(e);
}
}
And I am making call like below:
Vote.DoneVote(table);
I havn't got any error, but itemToAdd
not adding in ListName
.
When I debug it I see, what table
has correct data.
Решение
Try adding web.AllowUnsafeUpdates = true;
before for loop
and then after for loop
add web.AllowUnsafeUpdates = false;
So the code will be:
try
{
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList list = web.Lists.TryGetList("ListName");
foreach (DataRow row in table.Rows)
{
if (list != null) {
SPListItem itemToAdd = list.AddItem();
itemToAdd["Title"] = "DA0000";
itemToAdd["IdProject"] = "10";
itemToAdd["DateOf"] = DateTime.Today;
itemToAdd["Type"] = "1";
itemToAdd["Project"] = "1";
itemToAdd.Update();
}
}
web.AllowUnsafeUpdates = false;
}
}
}
catch (Exception e)
{
//Log errors
Console.WriteLine(e);
}
Другие советы
You should not update column ID as you have done in your code
Remove this line itemToAdd["ID"] = "10";
from your code
Entire code will be
class Vote
{
public static void DoneVote(DataTable table)
{
string siteUrl = "...";
try
{
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.OpenWeb())
{
foreach (DataRow row in table.Rows)
{
SPList list = web.Lists.TryGetList("ListName");
if (list != null) {
SPListItem itemToAdd = list.AddItem();
itemToAdd["Title"] = "DA0000";
itemToAdd["DateOf"] = DateTime.Today;
itemToAdd["Type"] = "1";
itemToAdd["Project"] = "1";
itemToAdd.Update();
Console.WriteLine(Convert.ToString(itemToAdd["ID"]));
}
}
}
}
}
catch (Exception e)
{
//Log errors
Console.WriteLine(e);
}
}
}
Не связан с sharepoint.stackexchange