Search code examples
sharepointsharepoint-2010web-parts

Filter a sharepoint visual web part through created by column through code


I created a visual web part and loading the list in Grid. Now when User A login it has to display only the items which are created by user A. USER B it has to display only the items that belong to USER b. Here is the code which i have written.It Display all the items irrespective of the logged in user. Can any one help me on this

public void Displaylistdata()
        {
           // System.Diagnostics.Debugger.Break();

            DataTable dt = new DataTable();
            var oSPWeb = SPContext.Current.Web;
            SPList oSpList = oSPWeb.Lists["Participation at a Glance"];
            string strCreatedby = SPContext.Current.Web.Author.Name;
            SPQuery oQuery = new SPQuery();
            oQuery.Query = "<Query><Where><Eq><FieldRef Name='Author' /><Value Type='User'>" + strCreatedby + "</Value></Eq></Where></Query>";
            SPListItemCollection collListItems = oSpList.GetItems(oQuery);

            DataTable dts = collListItems.GetDataTable();

            if (dts != null)
            {
                Gridview1.GridLines = GridLines.None;
                Gridview1.DataSource = dts;
                Gridview1.DataBind();
                Controls.Add(Gridview1);
            }

            else`enter code here`
            {

                lbl_noact.Visible = true;
                lbl_noact.Text = "We apologize there are no times currently available.";

            }


        }

Solution

  • Hi I have fixed by changing my Camel query as below. Previously the data type is USER but when i changed to string it works like a charm :-)

            DataTable dt = new DataTable();
            var oSPWeb = SPContext.Current.Web;
            SPList oSpList = oSPWeb.Lists["Participation at a Glance"];
            string strCreatedby = SPContext.Current.Web.CurrentUser.Name;
            SPQuery oQuery = new SPQuery();
            oQuery.Query = @"<Where><Eq><FieldRef Name='Author' /><Value Type='String'>" + strCreatedby + "</Value></Eq></Where>";
            SPListItemCollection collListItems = oSpList.GetItems(oQuery);