1

I am a newbie in visual studio. I have a Sharepoint list which contains the following fields group name, user, section and active(which is a check box) . I have a grid view visual web part which will retrieve the values from the list, and I need a check box in the grid view.

When the user selects the check box in grid view and click on the Ok button , I want the SharePoint list item Active to get updated as True or Yes and unchecks and clicks Ok as False or No.

The following is what I have done so far. I am able to retrieve values from the list . but when i click on the check box nothing gets updated in my SharePoint list.

Code behind:

public partial class VisualWebPart1UserControl : UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        GridView1.DataSource = GetData();
        GridView1.DataBind();
    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    public void chkStatus_OnCheckedChanged(object sender, EventArgs e)
    {

        CheckBox chkStatus = null;
        chkStatus = (CheckBox)sender;
        GridViewRow row = (GridViewRow)chkStatus.NamingContainer;
     SPSite oSiteCollection = SPContext.Current.Site;
     SPWeb oWeb = oSiteCollection.OpenWeb();



     bool status = chkStatus.Checked;
     string strBoolean = Convert.ToString(status);

    SPList oSPList = oWeb.Lists["sample"];
    SPListItemCollection oSPListItemCollection = oSPList.Items;
        foreach (SPListItem oSplistItem in oSPListItemCollection)
        {
            if (strBoolean == "True")
                oSplistItem["Active"] = true;
            else
                oSplistItem["Active"] = false;
            oSplistItem.Update();
        }


    }
    DataTable GetData()
    {
        SPSite oSiteCollection = SPContext.Current.Site;
        SPWeb oWeb = oSiteCollection.OpenWeb();
        SPList oSPList = oWeb.Lists["sample"];
        SPListItemCollection oSPListItemCollection = oSPList.Items;

        DataTable dt = new DataTable();
        try
        {
            dt.Columns.Add("Group Name", typeof(String));
            dt.Columns.Add("User", typeof(String));
            dt.Columns.Add("Section", typeof(String));
            dt.Columns.Add("Active", typeof(Boolean));

            DataRow dataRow;
            foreach (SPListItem oSplistItem in oSPListItemCollection)
            {
                dataRow = dt.Rows.Add();
                dataRow["Group Name"] = oSplistItem["Group Name"].ToString();
                dataRow["User"] = oSplistItem["User"].ToString();
                dataRow["Section"] = oSplistItem["Section"].ToString();
             //   dataRow["Active"] = oSplistItem["Active"].ToString();

            }
            return dt;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine("Managers Approval" + ex.Message.ToString());
            return dt;
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
      /*  CheckBox chkStatus = null;
        chkStatus = (CheckBox)sender;
        bool status = chkStatus.Checked;
        string strBoolean = Convert.ToString(status);
        SPSite oSiteCollection = SPContext.Current.Site;
        SPWeb oWeb = oSiteCollection.OpenWeb();
        SPList oSPList = oWeb.Lists["sample"];
        SPListItemCollection oSPListItemCollection = oSPList.Items;
        foreach (SPListItem oSplistItem in oSPListItemCollection)
        {
            if (strBoolean == "True")
                oSplistItem["Active"] = true;
            else
                oSplistItem["Active"] = false;
            oSplistItem.Update();
        }*/
    }

}
    }
  • just ammended my answer – Ali Jafer Nov 19 '13 at 11:49
  • I am sorry i did not understand the rptitems, where should that be added , when i added i am getting it does not exist in the current context, and on button click what should i add , and the event which you added shouldnt i add it in the checkbox in .aspx page as well the name i mean – user3008273 Nov 19 '13 at 12:11
  • @user3008273 just updated the answer – Ali Jafer Nov 19 '13 at 13:38
  • I am not being able to use add comment, it is not working Thank you for providing a detailed answer, I just have few doubts. I do not have a repeater tag in my aspx page and in aspx.cs what should be added in the button click . Cos i want the field to update when the Ok button is clicked Could you have a look at my .cs page and see if anything is wrong. I am not receiving any error. The below is the column in sharepoint list which i need to update Its a Yes/No Box type. Is this right to add. dt.Columns.Add("Active", typeof(Boolean)); – user3008273 Nov 20 '13 at 4:48
  • just ammended my answer – Ali Jafer Nov 20 '13 at 8:52
1

do know if this is a typo or not but shouldnt it be like this:

protected void Button1_Click(object sender, EventArgs e)
{
    CheckBox chkStatus = null;
    chkStatus = (CheckBox)sender;
    bool status = chkStatus.Checked;
    string strBoolean = Convert.ToString(status);
    SPSite oSiteCollection = SPContext.Current.Site;

    using(SPWeb oWeb = oSiteCollection.OpenWeb())
    {
      SPList oSPList = oWeb.Lists["sample"];
      SPListItemCollection oSPListItemCollection = oSPList.Items;
      foreach (SPListItem oSplistItem in oSPListItemCollection)
      {
          if (strBoolean == "True")
          {
              oSplistItem["Active"] = true;
          }
          else
          {
              oSplistItem["Active"] = false;
          }
          oSplistItem.Update();
      }
    }
}

1) you had a comment block on the whole code?

2) your calling the spsite context which is fine but your not disposing the new spweb object! oSiteCollection.OpenWeb() is creating a new SPWeb object! so iv wraped it in a using statment to handle it.

3) put if statment in brakets to make it more understandable (no room for error) so you make sure the splistitem is updated after the if else statment :)

4) make sure that the column Active is of type text or bool and that your column is called Active

EDIT

also noticed somthing! lol you should post your full aspx code! i had a look over and your using the TemplateField but from experience that means your using a repeater control? am i correct??

if so you need to move the checkbox event to the repeater event ItemDataBound to handle the checked changed! so on your onload event you need to create a new event like so:

  rptItems.ItemDataBound += new RepeaterItemEventHandler(rptItems_ItemDataBound);
  rptItems.DataBind();

now create the event or let vs create it for you using tab:

  private void rptItems_ItemDataBound(Object Sender, RepeaterItemEventArgs e) 
  {
       RepeaterItem CBri = e.Item;
       CheckBox CBdataItem = CBri.DataItem as CheckBox;

       bool status = CBdataItem.Checked;
       string strBoolean = Convert.ToString(status);
       SPSite oSiteCollection = SPContext.Current.Site;

       using(SPWeb oWeb = oSiteCollection.OpenWeb())
       {
          SPList oSPList = oWeb.Lists["sample"];
          SPListItemCollection oSPListItemCollection = oSPList.Items;
          foreach (SPListItem oSplistItem in oSPListItemCollection)
          {
             if (strBoolean == "True")
             {
                oSplistItem["Active"] = true;
             }
             else
             {
                oSplistItem["Active"] = false;
             }
             oSplistItem.Update();
          }
       }

  }

EDIT

rptItems is the repeater! in your aspx page do you have a repeater tag? rptItems is what iv just called it, it should be the id that you have named it! the code that iv given the first part goes within the codebehind of your aspx (aspx.cs) file. within the onload event add the code and create the new method from the second part of code.

so just to make it clear ;), you have an aspx file that contains a tag called repeater, for me it looks like this:

<asp:Repeater id="rptitems" runat="server">

as you can see it has an id of rptitems!

now you should also have a codebehind file associated with the aspx file:

once again as an example i named my aspx: getitems.aspx but you should also see getitems.aspx.cs

double click on the .cs file to open up the class. you should have an onload event, within that even add:

  rptItems.ItemDataBound += new RepeaterItemEventHandler(rptItems_ItemDataBound);
  rptItems.DataBind();

it will look somthing similar to:

    protected void Page_Load(object sender, EventArgs e)
    {
        rptItems.ItemDataBound += new RepeaterItemEventHandler(rptItems_ItemDataBound);
        rptItems.DataBind();
    }

lets not forget that rptItems is taken from the aspx page as the .cs file is inherited from the aspx page! So what every you named the repeater control (ID) as you need to replace rptItems.

now you need to create the databound method:

  private void rptItems_ItemDataBound(Object Sender, RepeaterItemEventArgs e) 
  {
       RepeaterItem CBri = e.Item;
       CheckBox CBdataItem = CBri.DataItem as CheckBox;

       bool status = CBdataItem.Checked;
       string strBoolean = Convert.ToString(status);
       SPSite oSiteCollection = SPContext.Current.Site;

       using(SPWeb oWeb = oSiteCollection.OpenWeb())
       {
          SPList oSPList = oWeb.Lists["sample"];
          SPListItemCollection oSPListItemCollection = oSPList.Items;
          foreach (SPListItem oSplistItem in oSPListItemCollection)
          {
             if (strBoolean == "True")
             {
                oSplistItem["Active"] = true;
             }
             else
             {
                oSplistItem["Active"] = false;
             }
             oSplistItem.Update();
          }
       }

  }

EDIT

ahh now you have said that your using a grid view I know what you need!

within your button click event do the following:

protected void Button1_Click(object sender, EventArgs e)
{

   foreach (GridViewRow row in GridView1.Rows)
   {
      // Access the CheckBox
      CheckBox cb = (CheckBox)row.FindControl("chkStatus");
      if (cb != null)
      {
          SPSite oSiteCollection = SPContext.Current.Site;

          using(SPWeb oWeb = oSiteCollection.OpenWeb())
          {
             SPList oSPList = oWeb.Lists["sample"];
             SPListItemCollection oSPListItemCollection = oSPList.Items;
             foreach (SPListItem oSplistItem in oSPListItemCollection)
             {
                if (cb.Checked == "True")
                {
                    oSplistItem["Active"] = true;
                }
                else
                {
                    oSplistItem["Active"] = false;
                }
                oSplistItem.Update();
             }
         }

      }
   }
}

the above works for a checkbox with a given control name, if you have many checkboxes on the form than you would need to loop through all controls within the page rather than finding one specific checkbox!

so instead of:

CheckBox cb = (CheckBox)row.FindControl("chkStatus");

you need to do somthing like:

foreach (Control c in Page.Controls)
{
   if (c is Checkbox)
   {
       Checkbox cb = c as CheckBox;
       //do what you want to the checkbox
   }
}

or if it doesnt work because its nested within the girdview do:

   foreach (GridViewRow row in GridView1.Rows)
   {

      foreach (Control c in row.Controls)
      {
         if (c is Checkbox)
         {
            Checkbox cb = c as CheckBox;
            //do what you want to the checkbox
         }
      }
   }
  • @user3008273 just updated the answer – Ali Jafer Nov 19 '13 at 13:36

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.