Welcome to plsql4all.blogspot.com SQL, MYSQL, ORACLE, TERADATA, MONGODB, MARIADB, GREENPLUM, DB2, POSTGRESQL.

Sunday, 22 June 2014

Dynamically Bind SharePoint List Items to Gridview

public void BindDataTable(string LstName, SPListItem Item)
        {
            SPList lst = oWeb.Lists["LstName"];
            SPQuery M_Query = new SPQuery();
            StringBuilder sbQuery = new StringBuilder();
            sbQuery.Append("<Where>");
            sbQuery.Append("<Eq>");
            sbQuery.Append("<FieldRef Name='Title' />");
            sbQuery.Append("<Value Type='Text'>" + LstName + "</Value>");
            sbQuery.Append("</Eq>");
            sbQuery.Append("</Where>");
            M_Query.Query = sbQuery.ToString();
            SPListItemCollection lst_colls = lst.GetItems(M_Query);
            if (lst_colls.Count > 0)
            {
                string[] columnArr = lst_colls[0]["Columns"].ToString().Split(',');
               
                DataTable table;
                table = new DataTable();
                foreach (string Column in columnArr)
                {
                    table.Columns.Add(Column, typeof(string));
                }
                DataRow row = table.Rows.Add();
                foreach (string Column in columnArr)
                {
                    row[Column] = Convert.ToString(Item[Column]);
                }
                rptViewReq.DataSource = table.AsDataView();
                rptViewReq.DataBind();
            }
Please provide your feedback in the comments section above. Please don't forget to follow.