0
namespace Gridwebpart.VisualWebPart1
{
    public partial class VisualWebPart1UserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                SPWeb site = SPContext.Current.Web;
                SPList list = site.Lists["GridList"];
                SPListItemCollection items = list.Items;
                DataTable dt = items.GetDataTable();
                Gridnames.DataSource = dt;
                Gridnames.DataBind();

            }

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            SPWeb site = SPContext.Current.Web;
            SPList list = site.Lists["GridList"];
            SPListItemCollection items = list.Items;
            //SPListItem item = list.GetItemById(1);
            SPListItem item = items.Add();
            item["Title"] = txtName.Text;
            item["Description"] = txtDescription.Text;
            item["IS Sharepoint 2010 Developer"] = chkbox.Checked;
            item.Update();
            site.AllowUnsafeUpdates = false;
            txtName.Text = "";
            txtDescription.Text = "";
             chkbox.Checked=false;
             items = list.Items;
             DataTable dt = items.GetDataTable();
             Gridnames.DataSource = dt;
             Gridnames.DataBind();
        }
    }
}
3

I am not sure whats best but you can use SPQuery (only for reading) as well to get Data out of sharepoint, however if you want someone to look at your code and improve it then I would suggest you try this question on

https://codereview.stackexchange.com/

hope it helped ;)

Just realized your not disposing your SharePoint objects in code, I would recommend you to look at this MSDN article

Disposing SharePoint Objects

  • 1
    added to your answer, you can add an item efficiently by following this blog: blog.robgarrett.com/2009/02/25/… – Change Aug 29 '12 at 8:01
  • There is no SharePoint objects in his code that he's allowed to dispose. Disposing the SPWeb from SPContext.Current.Web would be an error – Per Jakobsen Aug 29 '12 at 19:57
  • your right, I just had a quick look before i left that time – tereško Aug 29 '12 at 20:35

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.