0

I'm trying to take records from a list, based on Article Type field, which value type is choice. The problem is, that no matter what I'm giving as a type in query, result is still the same. I ran it through CAML builder, and there it's working perfectly fine. When i change a query to run on a title field, it gives the proper value based on what parameter i provide. An ideas what is wrong? Here is the code:

    [ToolboxItemAttribute(false)]
public class NewestCategoryArticle : WebPart
{
    private Label Body = new Label();
    protected override void CreateChildControls()
    {
        try
        {

            SPList NewsList = SPContext.Current.Web.Lists["News"];
            if (NewsList == null)
                return;
            SPQuery query = new SPQuery();
            query.Query = "<Query><Where><Eq><FieldRef Name='Article_x0020_Type' /><Value Type='Choice'>"+CategoryName+"</Value></Eq></Where></Query>";
            SPListItemCollection Items = NewsList.GetItems(query);
            if (Items.Count > 0)
            {
                SPListItem NewItem = Items[0];
                foreach (SPListItem item in Items)
                {
                    if (item != null)
                        NewItem = item;
                }
                Title = NewItem["Title"].ToString();
                string title = (string)NewItem.Title.ToString();
                string author = (string)NewItem["Author"].ToString();
                string content = (string)NewItem["Body"].ToString();
                Body.Text = "<h1>" + title + " " + author + "</h1> \n\n\n" + content;
                this.Controls.Add(Body);
            }
        }
        catch (Exception ex)
        {
            return;
        }
    }
    public static string CategoryName;
    [Personalizable(PersonalizationScope.Shared), WebBrowsable(true), WebDisplayName("News")]
    public string _CategoryText
    {
        get { return CategoryName; }
        set { CategoryName = value; }
    }
}
0

You need to remove the <Query> tag.

Your CAML query should be as below:

query.Query = "<Where><Eq><FieldRef Name='Article_x0020_Type' /><Value Type='Choice'>"+CategoryName+"</Value></Eq></Where>";
  • Thanks, works perfectly fine. Can you tell me why is that in those tags it provided wrong result? – Wolwgang Jul 26 '17 at 9:49
  • Caml Builder includes Query tag which should not be there when using server-side C# code and CAML . The syntax was wrong basically. So, next time just ensure that before running CAML query in c# code, remove the <Query> tag – Gautam Sheth Jul 26 '17 at 9:56

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.