- Open Visual Studio 2010
- Create New Project
- Select your Sharepoint site
- Create Visual Webpart
- Add LAbels,Textboxes or Dropdownlist (NOTE: Update control names in your code accordingly)
- Use below code in page load event
try
{
SPQuery query = new SPQuery();
query.Query = “”;
query.ViewFields = “”;
query.RowLimit = 100;
using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists.TryGetList(“—ADD LIST NAME—”);
//Check List Exists
if (list != null)
{
//Check ITEMS Exists
if (list.GetItems(query).GetDataTable() != null)
{
DataTableReader rdr = list.GetItems(query).GetDataTable().CreateDataReader();
if (rdr.Read())
//Bind list items to ASP.NET Label
Label1.Text = rdr["Test_x0020_Item1"].ToString();
Label2.Text = rdr["TestField2"].ToString();
//To bind DROPDOWNLIST uncomment below code
// dropdownlist1.DataSource = rdr;
// dropdownlist1.DataTextField = “Title”;
// dropdownlist1.DataValueField = “Title”;
// dropdownlist1.DataBind();
//To bind REPEATER uncomment below code
// Repeater1.DataSource = rdr;
// Repeater1.DataBind();
rdr.Close();
}
else
{
lblInfo.Text = “No Items Found”;
}
}
else
{
lblErrorMessage.Text = “List not found.Please make sure list is created and go to webpart settings to add the List name “;
}
}
}
}
catch (Exception ex)
{
lblErrorMessage.Text = ex.Message.ToString();
}