My requirement is to select a value from a drop down and fetch the corresponding three fields and drop down must have the selected value in it.
However my code it fetches the corresponding three fields and sets the drop down selected value to first value.
Please tel me how to solve this issue.
Below are my code at page load and corresponding methods:
public partial class RegisterWebPartUserControl : UserControl
{
string titleid;
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SPSite oSPSiteCollection = SPContext.Current.Site;
SPWeb oSPWeb = SPContext.Current.Web;
SPList oSPList = oSPWeb.Lists["Registered"];
string names = oSPWeb.CurrentUser.ToString();
TxtEmployeeName.Text = names.ToString();
SPList oSPListCalender = oSPWeb.Lists["Scheduled Courses"];
DataTable dataTable = oSPListCalender.Items.GetDataTable();
dataTable.TableName = "Table1";
ds.Tables.Add(dataTable);
ddlDrop.DataSource = ds.Tables["Table1"];
ddlDrop.DataTextField = "Title";
ddlDrop.DataValueField = "TitleID";
titleid = ddlDrop.SelectedValue;
ddlDrop.DataBind();
}
protected void ddlDrop_SelectedIndexChanged(object sender, EventArgs e)
{
FetchReadOnlyFields(titleid);
}
public void FetchReadOnlyFields(string titleID)
{
string oStartDate = null;
string oEndDate = null;
string oPrerequisite = null;
SPSite oSPSiteCollection = SPContext.Current.Site;
SPWeb oSPWeb = SPContext.Current.Web;
SPList oSPList = oSPWeb.Lists["Registered"];
SPListItemCollection oItemCollection = oSPList.Items;
SPListItem ospListItem = oItemCollection.Add();
SPList oSPList1 = oSPWeb.Lists["Scheduled Courses"];
SPListItemCollection oItemCollectionCourse = oSPList1.Items;
SPFieldCalculated titleIDCourse = (SPFieldCalculated)oItemCollectionCourse.Fields["TitleID"];
SPField fieldStartDate = oItemCollectionCourse.Fields["Start Date"];
SPField fieldEndDate = oItemCollectionCourse.Fields["End Date"];
foreach (SPListItem ospListItemCourse in oItemCollectionCourse)
{
string value = titleIDCourse.GetFieldValueAsText(ospListItemCourse["TitleID"]);
if (titleID == value)
{
oPrerequisite = ospListItemCourse["Prerequisite"].ToString();
TxtPrerequisite1.Text = SPHttpUtility.ConvertSimpleHtmlToText(oPrerequisite, oPrerequisite.Length);
oStartDate = ospListItemCourse["Start Date"].ToString();
TxtStartDate.Text = oStartDate;
oEndDate = ospListItemCourse["End Date"].ToString();
TxtEndDate.Text = oEndDate;
break;
}
}
}
}
Hope to seek your help.
Thank you
This code
ddlDrop.DataBind();
Should be called only once. On the first load of the page.
Try
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack){ // this is what has changed
DataSet ds = new DataSet();
SPSite oSPSiteCollection = SPContext.Current.Site;
SPWeb oSPWeb = SPContext.Current.Web;
SPList oSPList = oSPWeb.Lists["Registered"];
string names = oSPWeb.CurrentUser.ToString();
TxtEmployeeName.Text = names.ToString();
SPList oSPListCalender = oSPWeb.Lists["Scheduled Courses"];
DataTable dataTable = oSPListCalender.Items.GetDataTable();
dataTable.TableName = "Table1";
ds.Tables.Add(dataTable);
ddlDrop.DataSource = ds.Tables["Table1"];
ddlDrop.DataTextField = "Title";
ddlDrop.DataValueField = "TitleID";
ddlDrop.DataBind();
}
titleid = ddlDrop.SelectedValue;
}
Related
I am getting the error "Disposable type not disposed Microsoft.SharePoint.SPWeb ***This may be a false positive depending on how the type was created or if it is disposed outside the current scope".
Below is my code :
public static int AddtoList( string title)
{
int returnValue = int.MinValue;
SPUser sysAcount = SPContext.Current.Web.AllUsers[#"SHAREPOINT\SYSTEM"];
SPUserToken sysAcountToken = sysAcount.UserToken;
using (SPSite siteCollection = new SPSite(SPContext.Current.Site.Url, sysAcountToken))
{
SPWeb currentWeb = siteCollection.RootWeb;
SPList list = currentWeb.Lists[MyList];
SPListItem newItem = errorList.Items.Add();
newItem[TitleColumnName] = title;
currentWeb.AllowUnsafeUpdates = true;
newItem.SystemUpdate(false);
currentWeb.AllowUnsafeUpdates = false;
returnValue = newItem.ID;
}
return returnValue;
}
I understood that when we use RootWeb we do not have dispose the object. Please let me know what does this error message mean and how do I correct it . I have several blogs bug failed to understand the error. Please help me.
Do you have the most up to date version of SPDisposeCheck?
An older version (Dec 2010?) incorrectly flagged .RootWeb
http://blogs.technet.com/b/stefan_gossner/archive/2010/12/15/first-issue-with-spdisposecheck-has-been-identified-by-the-community.aspx
Please try below code sample for SPDisposeChecker error resolve.
public static int AddtoList( string title)
{
int returnValue = int.MinValue;
SPUser sysAcount = SPContext.Current.Web.AllUsers[#"SHAREPOINT\SYSTEM"];
SPUserToken sysAcountToken = sysAcount.UserToken;
using (SPSite siteCollection = new SPSite(SPContext.Current.Site.Url, sysAcountToken))
{
//Add below code for dispose currentWeb object end of the functionality
using(SPWeb currentWeb = siteCollection.RootWeb)
{
SPList list = currentWeb.Lists[MyList];
SPListItem newItem = errorList.Items.Add();
newItem[TitleColumnName] = title;
currentWeb.AllowUnsafeUpdates = true;
newItem.SystemUpdate(false);
currentWeb.AllowUnsafeUpdates = false;
returnValue = newItem.ID;
}
}
return returnValue;
}
Happy SharePointing !!!
Thanks,
So, my problem is that my knowledge of CAML and Sharepoint is very poor.
Question: I need SPQuery for building query search, search text I have from textbox. I expect that my query returns me item(s) (for example, I type in textbox "Jo" and query returns me all items with surname "Johnson", or name "John", etc)
1)TextChanged works ok. I've check it, there is ok
2) SPGridView views items ok. Items from SPList I add to gridView - there are viewd by gridview.
3) But my query doesn't work. Please, help with links/advises
public class VisualWebPart1 : WebPart
{
SPSite site;
SPWeb web;
SPGridView gridView;
SPDataSource dataSource;
TextBox searchTextBox;
UpdatePanel panel;
SPList list;
SPList resultList;
string currentList;
// Visual Studio might automatically update this path when you change the Visual Web Part project item.
private const string _ascxPath = #"~/_CONTROLTEMPLATES/CRMSearchWebPart/VisualWebPart1/VisualWebPart1UserControl.ascx";
protected override void CreateChildControls()
{
gridView = new SPGridView();
searchTextBox = new TextBox();
panel = new UpdatePanel();
searchTextBox.AutoPostBack = true;
searchTextBox.Visible = true;
searchTextBox.Enabled = true;
searchTextBox.TextChanged += new EventHandler(searchTextBox_TextChanged);
gridView.Visible = true;
gridView.Enabled = true;
gridView.AutoGenerateColumns = false;
AddColumnToSPGridView("Surname", "Surname");
panel.UpdateMode = UpdatePanelUpdateMode.Conditional;
panel.ContentTemplateContainer.Controls.Add(searchTextBox);
panel.ContentTemplateContainer.Controls.Add(gridView);
Control control = Page.LoadControl(_ascxPath);
Controls.Add(control);
Controls.Add(panel);
}
protected override void Render(HtmlTextWriter writer)
{
panel.RenderControl(writer);
}
//Open WebSite with List "listName"
private void OpenWebSite(string listName)
{
site = SPContext.Current.Site;
web = site.OpenWeb();
list = web.Lists[listName];
}
//Add Column to gridView
private void AddColumnToSPGridView(string HeaderText, string Datafield)
{
SPBoundField boundField = new SPBoundField();
boundField.HeaderText = HeaderText;
boundField.DataField = Datafield;
gridView.Columns.Add(boundField);
}
//Build query for search; fieldName - Name of column of current List, searchQuery - our query
private string BuildQuery(string fieldRefName, string searchQuery)
{
string query = "";
switch (fieldRefName)
{
case "Surname":
query = "<Where><BeginsWith><FieldRef Name='Surname'/>" +
"<Value Type=Text>"+searchQuery+"</Value></BeginsWith></Where>";
break;
case "Name":
query = query = "<Where><BeginsWith><FieldRef Name='Name'/>" +
"<Value Type=Text>"+searchQuery+"</Value></BeginsWith></Where>";
break;
case "PassportNumber":
query = "<Where><BeginsWith><FieldRef Name='PassportNumber'/>" +
"<Value Type=Text>"+searchQuery+"</Value></BeginsWith></Where>";
break;
default: break;
}
return query;
}
// search in List for selected items and returns SPGridView
private void searchTextBox_TextChanged(object sender, EventArgs e)
{
dataSource = new SPDataSource();
string querySearch = searchTextBox.Text;
OpenWebSite("Surnames");
string query = BuildQuery("Surname", querySearch);
SPQuery spQuery = new SPQuery();
spQuery.ViewFields = "<FieldRef Name = 'Title'/><FieldRef Name = 'Surname'/><FieldRef Name = 'Name'/>";
spQuery.Query = query;
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem item in items)
{
searchTextBox.Text += item["Surname"] + " ";
}
//resultList = web.Lists["TempSurnames"];
//resultList = AddItemsToSPList(resultList, items);
BindDataSource(dataSource, resultList);
//resultList = AddSPList("Result2", "Result list");
//resultList = AddItemsToSPList(resultList, items);
list = AddItemsToSPList(list, items);
//BindDataSource(dataSource, resultList);
BindDataSource(dataSource, list);
BindGridView(gridView, dataSource);
//var item = list.Items[3];
//var item = resultList.Items[1];
//searchTextBox.Text = item["Surname"].ToString();
//resultList.Delete();
}
//Binds datasource of existing gridView with SPDataSource
private void BindGridView(SPGridView gridview, SPDataSource datasource)
{
gridview.DataSource = datasource;
gridview.DataBind();
}
//Add SPListItem items to SPList
private SPList AddItemsToSPList(SPList spList, SPListItemCollection collection)
{
foreach (SPListItem item in collection)
{
var listItem = spList.AddItem();
listItem = item;
}
return spList;
}
//Binds existing SPDataSource to SPList
private void BindDataSource(SPDataSource spDataSource, SPList spList)
{
spDataSource.List = spList;
}
private SPList AddSPList(string listName, string listDescription)
{
OpenWebSite("Surnames");
SPListCollection collection = web.Lists;
collection.Add(listName, listDescription, SPListTemplateType.CustomGrid);
resultList = web.Lists[listName];
return resultList;
}
Update:
This part gives me an error:
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem item in items)
{
searchTextBox.Text += item["Surname"] + " ";
}
System.ArgumentException: Value does not fall within the expected
range
You have to include the field Surname into the view fields of the query:
SPQuery query = // ...
query.ViewFields = "<FieldRef Name='Surname' />";
// ...
You can understand the view fields like the SELECT part of a SQL query.
Have you debugged your code to check the query string that is generated? Also, you have query = query = under the Name switch.
Also, you know that the switch is case sensitive, so ensure you enter your searchQuery option appropriately.
Does anyone know how to read the number of attachments, and the names etc for a ListItem using the Client .Net Object model in SharePoint?
Thanks
// For getting the list item field information
public void LoadPropertyInfo()
{
using (context = new ClientContext(siteCollectionUrl))
{
spWeb = context.Web;
propertiesList = spWeb.Lists.GetByTitle(listName);
FieldCollection fields = propertiesList.Fields;
context.Load(fields);
SP.CamlQuery query = new SP.CamlQuery();
query.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name=\"{0}\" /><Value Type=\"Text\">{1}</Value></Eq></Where></Query></View>", propertyID, PropertyIDValue);
listItems = propertiesList.GetItems(query);
context.Load(listItems);
context.ExecuteQueryAsync(GetRequestSucceeded, RequestFailed);
}
}
// Pass the item id here for getting the attachments
private void GetAttchmentCollection(string id)
{
string RedirectHost = string.Empty;
string Host = string.Empty;
context = SP.ClientContext.Current;
RedirectHost = serviceUrl + "_vti_bin/Lists.asmx";
BasicHttpBinding binding = new BasicHttpBinding();
if (System.Windows.Browser.HtmlPage.Document.DocumentUri.Scheme.StartsWith("https"))
{
binding.Security.Mode = BasicHttpSecurityMode.Transport;
}
binding.MaxReceivedMessageSize = int.MaxValue;
EndpointAddress endpoint = new EndpointAddress(RedirectHost);
ServiceReference1.ListsSoapClient oClient = new ServiceReference1.ListsSoapClient(binding, endpoint);
oClient.GetAttachmentCollectionCompleted += new EventHandler<ServiceReference1.GetAttachmentCollectionCompletedEventArgs>(oClient_GetAttachmentCollectionCompleted);
oClient.GetAttachmentCollectionAsync(listName, id);
}
Your can try this link too.
http://helpmetocode.blogspot.com/2011/11/managed-client-object-models-in.html
the error i get is
The security validation for this page is invalid. Click Back in your Web browser, refresh the page and try the operation again.
i am using moss 2007
protected void btnSubmit_Click(Object sender, EventArgs e)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPUtility.ValidateFormDigest();
using (SPSite mySite = new SPSite(_sLibUrl))
{
TextBox txtFirstName = (TextBox)usercontrol.FindControl("txtFirstName");
TextBox txtLastName = (TextBox)usercontrol.FindControl("txtLastName");
TextBox txtPhone = (TextBox)usercontrol.FindControl("txtPhone");
TextBox txtEmail = (TextBox)usercontrol.FindControl("txtEmail");
TextBox txtSubject = (TextBox)usercontrol.FindControl("txtSubject");
TextBox txtContant = (TextBox)usercontrol.FindControl("txtContant");
mySite.AllowUnsafeUpdates = true;
SPListItemCollection listItems = mySite.AllWebs[WebName].Lists[_sLibName].Items;
SPListItem item = listItems.Add();
item["FirstName"] = txtFirstName.Text;
item["LastName"] = txtLastName.Text;
item["Phone"] = txtPhone.Text;
item["Email"] = txtEmail.Text;
item["Subject"] = txtSubject.Text;
item["Contant"] = txtContant.Text;
item.Update();
mySite.AllowUnsafeUpdates = false;
mySite.AllWebs[WebName].Lists[_sLibName].Update();
txtFirstName.Text = string.Empty;
txtLastName.Text = string.Empty;
txtPhone.Text = string.Empty;
txtEmail.Text = string.Empty;
txtSubject.Text = string.Empty;
txtContant.Text = string.Empty;
}
Label lblMessage = (Label)usercontrol.FindControl("lblMessage");
// lblMessage.Text = "טופס נשלח בהצלחה";
});
}
catch (Exception ex)
{
Label lbl = (Label)usercontrol.FindControl("lblMessage");
lbl.Text = ex.Message;
}
}
Try putting mySite.AllowUnsafeUpdates = false; after mySite.AllWebs[WebName].Lists[_sLibName].Update();
i found the solution what i need to do is to remove the
mySite.AllowUnsafeUpdates = true;
and
mySite.AllowUnsafeUpdates = false;
and it works
I work with this solution always
using (var site = new SPSite(SPContext.Current.Site.ID))
using (var web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//add, update and etc. programatically crud operations with lists
web.AllowUnsafeUpdates = false;
}
I want to be able to create a KPI List on my MOSS 2007 installation via the object model. Is this possible?
using (SPWeb web1 = properties.Feature.Parent as SPWeb)
{
using (SPSite objSite = new SPSite(web1.Site.ID))
{
using (SPWeb web = objSite.OpenWeb(web1.ID))
{
SPListTemplate template = null;
foreach (SPListTemplate t in web.ListTemplates)
{
if (t.Type.ToString() == "432")
{
template = t;
break;
}
}
Guid gG = Guid.Empty;
SPList list = null;
string sListTitle = "Status List";
SPSecurity.RunWithElevatedPrivileges(delegate
{
try
{
web.AllowUnsafeUpdates = true;
gG = web.Lists.Add(sListTitle, sListTitle, template);
list = web.Lists[gG];
}
catch
{
// exists
list = web.Lists[sListTitle];
}
SPContentType ct =
list.ContentTypes["SharePoint List based Status Indicator"];
//declare each item which u want to insert in the kpi list
SPListItem item1 = list.Items.Add();
SPFieldUrlValue value1 = new SPFieldUrlValue();
item1["ContentTypeId"] = ct.Id;
item1.SystemUpdate();
item1["Title"] = "Project Specific Doc.Lib.Rating";
value1.Url = web.Url + "/Lists/Project Specific Documents";
item1["DataSource"] = value1;
item1["Indicator Goal Threshold"] = "3";
item1["Indicator Warning Threshold"] = "3";
item1["Value Expression"] =
"Average;Average_x0020_Rating:Number";
item1.SystemUpdate();
}
}
}
average is the calculation value and the column is Average_x0020_Rating.
http://alonsorobles.com/2010/03/17/important-custom-sharepoint-list-template-notes/
I found that the Template ID for a Status Indicator (KPI List) is 432. Google for this to find some info on creating a new list. I'm needing to read up what properties I can set on this list.
this is work for me:
private void CreateKPIDocumentLibrary(List<PageStructure> list)
{
SPListTemplate kpi = null;
foreach (SPListTemplate t in web.ListTemplates)
{
if (t.Type.ToString() == "432")
{
kpi = t;
break;
}
}
foreach (PageStructure st in list)
{
bool find = false;
string[] periodType = st.tag.Split('_');
string name = periodType[0] + "-" + st.effdate + "-" + st.template;
SPListCollection lstCol = site.OpenWeb().GetListsOfType(SPBaseType.GenericList);
foreach (SPList l in lstCol)
{
string title = l.Title;
if (title == name)
{
find = true;
break;
}
}
if (find == false)
{
Guid docLibID = web.Lists.Add(name, "", kpi);
}
SPList itemList = web.Lists[name];
SPListItem item = itemList.Items.Add();
SPFieldUrlValue value = new SPFieldUrlValue();
item["Title"] = st.tag;
value.Url = st.docUrl;
item["DetailLink"] = st.url;
item["DataSource"] = value;
item["Indicator Goal Threshold"] = "2";
item["Indicator Warning Threshold"] = "1";
item["View Name"] = "All Documents";
item.SystemUpdate();
web.Update();
KpiObject kp = new KpiObject(name, SPContext.Current.Site.Url + itemList.DefaultViewUrl);
this.kpiList.Add(kp);
}
}