Bind Drop-down with SharePoint List and display list items in a Gridview

In this blog, I will explain about below point through C# code:
1. Bind all list in a dropdown
2 Load List items in a Gridview once a user changes list name in dropdown.

You need to create a visual webpart in Visual studio 2010.



Visual WebPart ASCX code:

<asp:DropDownList ID="ddlList" AutoPostBack="true" runat="server" 
    onselectedindexchanged="ddlList_SelectedIndexChanged">
</asp:DropDownList>
<p>
    <asp:Label ID="lblItemCount" runat="server" Text=""></asp:Label>
</p>
<asp:GridView ID="gvListItem" AutoGenerateColumns="false" runat="server">
</asp:GridView>

Visual Webpart .ascx.cs code:

Add below name space:

using Microsoft.SharePoint;

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var web = SPContext.Current.Web;
                ddlList.DataSource = web.Lists;
                ddlList.DataTextField = "Title";
                ddlList.DataBind();
            }
        }

        protected void ddlList_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            var web = SPContext.Current.Web;
            var list = web.Lists[ddlList.SelectedItem.Text];
            lblItemCount.Text = list.Items.Count.ToString();
            gvListItem.DataSource = list.Items.GetDataTable();
            gvListItem.DataBind();

        }
Protected by Copyscape

Comments

  1. Thanks so much! Your instructions are very clear and helpful. I've been wondering how to do this for months and thrilled to find out how finally!
    sharepoint developer training

    ReplyDelete

Post a Comment

Dear Readers, Please post your valuable feedback in the comment section if you like this blog or if you have any suggestions. I would love to hear the same from you. Thanks

Popular

SharePoint Interview Questions and Answers

Calling ASP.Net WebMethod using jQuery AJAX

What is Cloud Computing - A guide for beginners