1

i want to update xsltlistviewwebpart to show only some items, but it could not be updated: these are the following scenario i made to update it.

//this is the web part
 <WebPartPages:WebPartZone runat="server" FrameType="None" ID="WebPartZone1"    
   Title="loc:Main"><ZoneTemplate>
    <WebPartPages:XsltListViewWebPart runat="server" ...>

     <ParameterBindings>
          ...

     </ParameterBindings>
  <DataFields>
  </DataFields>
  <XmlDefinition>
  <View ...><Query><Where>...</Where></Query><ViewFields>...</ViewFields><RowLimit   
      Paged="TRUE">30</RowLimit><JSLink>clienttemplates.js</JSLink><XslLink 
        Default="TRUE">main.xsl</XslLink><Toolbar Type="Standard"/></View>  
  </XmlDefinition>

  </WebPartPages:XsltListViewWebPart>

 </ZoneTemplate></WebPartPages:WebPartZone>


 //1°scenario
  SPWebPartManager wpm = SPWebPartManager.GetCurrentWebPartManager(this.Page) as    
    SPWebPartManager;

        SPList list = web.Lists["listname"];

        foreach (System.Web.UI.WebControls.WebParts.WebPart current in wpm.WebParts)
        {
            if (current is XsltListViewWebPart)
            {
                XsltListViewWebPart XsltListViewWebPart1 = current as 
                    XsltListViewWebPart;

                XsltListViewWebPart1.ListId = list.ID;
                  SPListItemCollection items = list.Items;

               XsltListViewWebPart1.DataSource = items.Cast<SPListItem>
                  ().Where(item=>item.Name == name).ToList() as IDataSource;

                XsltListViewWebPart1.AutoRefresh = true;
                XsltListViewWebPart1.AsyncRefresh = true;

              wpm.SaveChanges(XsltListViewWebPart1.StorageKey);
               web.Update();
             }
      }

   //2°scenario
         SPWebPartManager wpm = SPWebPartManager.GetCurrentWebPartManager(this.Page) 
      as SPWebPartManager;

        SPList list = web.Lists["listname"];

        foreach (System.Web.UI.WebControls.WebParts.WebPart current in wpm.WebParts)
        {
            if (current is XsltListViewWebPart)
            {
                XsltListViewWebPart XsltListViewWebPart1 = current as 
                    XsltListViewWebPart;

     StringBuilder xml = new StringBuilder();
    xml.Append("<View Name='" + 
    list.DefaultView.ID.ToString("B").ToString().ToUpper(CultureInfo.InvariantCulture) 
    + "' TabularView='FALSE' MobileView='TRUE' Type='HTML'  Hidden='TRUE' 
    DisplayName=''  Level='1' BaseViewID='1' ContentTypeID='0x' ImageUrl='/_layouts
    /images/generic.png'>");   Url='" + Request.Url.ToString() + "' 
    xml.Append("<Query><Where><Eq><FieldRef Name='LinkFilename'/><Value Type='Text'> " 
    + name + " </Value></Eq></Where><OrderBy><FieldRef Name='ID'/></OrderBy></Query>");
    xml.Append("<ViewFields><FieldRef Name='LinkFilename'/><FieldRef   
    Name='Auteur'/></ViewFields>");
    xml.Append("<RowLimit Paged='TRUE'>20</RowLimit>");
    xml.Append("</View>");



    XsltListViewWebPart1.XmlDefinition = xml.ToString();

    XsltListViewWebPart1.AutoRefresh = true;
    XsltListViewWebPart1.AsyncRefresh = true;

              wpm.SaveChanges(XsltListViewWebPart1.StorageKey);
               web.Update();
             }
      }

  //3°scenario
        SPWebPartManager wpm = SPWebPartManager.GetCurrentWebPartManager(this.Page) as    
    SPWebPartManager;

        SPList list = web.Lists["listname"];

        foreach (System.Web.UI.WebControls.WebParts.WebPart current in wpm.WebParts)
        {
            if (current is XsltListViewWebPart)
            {
                XsltListViewWebPart XsltListViewWebPart1 = current as 
                    XsltListViewWebPart;

                XsltListViewWebPart1.ListId = list.ID;
                  SPListItemCollection items = list.Items;

          StringBuilder sb = new StringBuilder();
          sb.Append("<Where><Eq><FieldRef Name='LinkFilename'/><Value  
          Type='Text'> " + name + " </Value></Eq></Where><OrderBy><FieldRef Name='ID'/>
          </OrderBy>");

           SPQuery query = new SPQuery();
           query.Query = sb.ToString();

           SPView vv = list.DefaultView;
           vv.Query = query.Query.ToString();
           vv.Update();

           XsltListViewWebPart1.ViewGuid = 
           vv.ID.ToString("B").ToUpper(CultureInfo.InvariantCulture);
           XsltListViewWebPart1.ViewId = int.Parse(vv.BaseViewID);
           XsltListViewWebPart1.XmlDefinition = vv.GetViewXml();

           XsltListViewWebPart1.AutoRefresh = true;
           XsltListViewWebPart1.AsyncRefresh = true;

              wpm.SaveChanges(XsltListViewWebPart1.StorageKey);
               web.Update();
             }
      }

  //notice i used the SPLimitedWebPartManager but it does not return any web part
1

Try this one you should get it in moment this code add web part to page and allow to search for all fields added by user if you want to search in all fields disable line if (!Field.SourceId.StartsWith("http://")). To get calculated field you must set type text or number. This one MergeCAMLConditions(Fields, MergeType.Or) i found in web don't remember where exactly. Hope this help you ;)

enum MergeType { Or, And };

/// <summary>
/// Merge CAML conditions in code
/// </summary>
/// <param name="conditions">A list of contitions to merge into alternative or conjunction</param>
/// <param name="type"><value>MergeType.Or</value> for alternative, MergeType.And for conjunction</param>
/// <returns></returns>
private static string MergeCAMLConditions(List<string> Fields, MergeType type)
{
    // No conditions => empty response
    if (Fields.Count == 0) return "";

    // Initialize temporary variables
    string typeStart = (type == MergeType.And ? "<And>" : "<Or>");
    string typeEnd = (type == MergeType.And ? "</And>" : "</Or>");

    // Build hierarchical structure
    while (Fields.Count >= 2)
    {
        List<string> complexConditions = new List<string>();

        for (int i = 0; i < Fields.Count; i += 2)
        {
            if (Fields.Count == i + 1) // Only one condition left
                complexConditions.Add(Fields[i]);
            else // Two condotions - merge
                complexConditions.Add(typeStart + Fields[i] + Fields[i + 1] + typeEnd);
        }

        Fields= complexConditions;
    }

    return Fields[0];
}
protected void Page_Load(object sender, EventArgs e)
{
   SPList myList = SPContext.Current.Web.Lists["List Name"];
   BindWebPart(myList);
}
private void BindWebPart(SPList myList)
{
SPList list = myList;
SPFieldCollection FieldsColl = list.Fields;
List<string> Fields = new List<string>();
string SearchValue = "Your Text Here";
foreach (SPField Field in FieldsColl)
{
    string FieldType = Field.Type.ToString();
    if (!Field.SourceId.StartsWith("http://"))
    {
        if (FieldType == "Calculated")
            FieldType = "Text";
        Fields.Add("<Contains><FieldRef Name='" + Field.InternalName.ToString().Replace(" ", "_x0020_")
            + "' />" + "<Value Type='" + FieldType + "'>" + SearchValue.Trim() + "</Value></Contains>");
    }
}

string QueryBuilder = MergeCAMLConditions(Fields, MergeType.Or);

XsltListViewWebPart XsltListViewWebPart1 = new XsltListViewWebPart();
XsltListViewWebPart1.ListId = list.ID;
SPView lstview = list.Views["View You want to show"];//list.DefaultView



Regex ViewFields = new Regex("<ViewFields>(.*)</ViewFields>");
var v = ViewFields.Match(lstview.GetViewXml().ToString());
string ViewFieldsSttring = v.Groups[1].ToString();
Regex RowLimit = new Regex("<RowLimit Paged=\"TRUE\">(.*)</RowLimit>");
var RowLimitFromXML = RowLimit.Match(lstview.GetViewXml().ToString());
string RowLimitFromXMLString = RowLimitFromXML.Groups[1].ToString();

Regex ViewName = new Regex("(.*) >");
var ViewNameXML = ViewName.Match(lstview.GetViewXml().ToString());
string ViewNameXMLString = ViewNameXML.Groups[1].ToString() + ">";

Regex QueryRow = new Regex("<Query>(.*)</Query>");
var QueryRowXML = QueryRow.Match(lstview.GetViewXml().ToString());
string QueryRowXMLString = QueryRowXML.Groups[1].ToString();

XsltListViewWebPart1.ListId = list.ID;
XsltListViewWebPart1.Toolbar = "";
StringBuilder xml = new StringBuilder();
xml.Append("<View Name='" + list.Views[lstview.ToString()].ID.ToString("B").ToString().ToUpper(CultureInfo.InvariantCulture)
    + "' TabularView='FALSE' MobileView='TRUE' Type='HTML'  Hidden='TRUE' DisplayName=''  Url='"
    + HttpContext.Current.Request.Url.ToString().Split('?')[0]
    + "'  Level='1' BaseViewID='1' ContentTypeID='0x' ImageUrl='/_layouts/images/generic.png'>");
if (QueryRowXMLString == "")
{
    xml.Append("<Query><Where>" + QueryBuilder + "</Where><OrderBy><FieldRef Name='ID'/></OrderBy></Query>");
}
else
{
    xml.Append("<Query><Where>" + QueryBuilder + "</Where>" + QueryRowXMLString + "</Query>");
}
xml.Append("<ViewFields>" + ViewFieldsSttring + "</ViewFields>");
xml.Append("<RowLimit Paged='TRUE'>" + RowLimitFromXMLString + "</RowLimit>");
xml.Append("<Aggregations Value='off'/>");
xml.Append("<Toolbar Type='Freeform'/></View>");




XsltListViewWebPart1.XmlDefinition = xml.ToString();
XsltListViewWebPart1.Title = list.Title;
XsltListViewWebPart1.AllowClose = false;
XsltListViewWebPart1.AllowConnect = false;
XsltListViewWebPart1.AllowEdit = false;
XsltListViewWebPart1.AllowHide = false;
XsltListViewWebPart1.AllowMinimize = false;
XsltListViewWebPart1.AllowZoneChange = false;
XsltListViewWebPart1.ChromeType = PartChromeType.Default;
Controls.Add(XsltListViewWebPart1);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.