0

I have used the following code to get the list items in a gridview!!

Though I have only three fields visible in the list - Title, Mobile and Email ID. It ends up showing around 10 different fields like created, modified etc.. I need only the three columns (Title, Mobile and Email ID) to show up in the list, how can I do it!!

public partial class Contact_DetailsUserControl : UserControl
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                BindGrid();
            }
            catch (Exception ex)
            {
            }
        }




        private void BindGrid()
        {
            //string SiteListURL = ConfigurationManager.AppSettings["SiteListURL"].ToString();
            try
            {

                string SiteListURL = "http://sonio274:6419/Lists/MS%20presales%20Contact/";


                using (SPSite oSiteCollection = new SPSite(SiteListURL))
                using (SPWeb web = oSiteCollection.OpenWeb())
                {
                    DataTable dt = new DataTable();
                    SPQuery query = new SPQuery();
                    query.Query = "";
                    dt = web.Lists["MS presales Contact"].GetItems(query).GetDataTable();
                    if (dt != null)
                    {
                        GridView1.DataSource = dt;
                        GridView1.DataBind();
                    }
                    else
                    {
                        GridView1.DataSource = dt;
                        GridView1.DataBind();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

    }
1

Use the ViewFields property on your SPQuery to return only the fields you need, add in:

query.ViewFields = string.Concat(
                               "<FieldRef Name='Title' />",
                               "<FieldRef Name='Mobile' />",
                               "<FieldRef Name='EmailId' />");
query.ViewFieldsOnly = true; // Fetch only the data that we need.

You should be able to see the column names coming back in your grid at the moment to enter the correct names.

  • Thank you very much Daniel, for helping me again. That was a great info !! – Jithu Nov 3 '11 at 7:24
  • Hi Dan can I change that, Title to show as Employee ? – Jithu Nov 3 '11 at 8:03
  • 1
    Yes, but you need to manually specify all of your columns in the GridView, that way you can specify the Title of the column to be different. Set AutoGenerateColumns to false and use GridView1.Columns.Add() to programatically add them, or specify them in your design view. Have a look at GridView.Columns Property - link – Daniel Symonds-Lloyd Nov 3 '11 at 8:23

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.