visualwebpart.ascx
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Register Details Display </title>
</head>
<body>
<div class="maindisplay">
<div class="griddisp">
<asp:GridView ID="gridViewManager" runat="Server" AutoGenerateColumns="False" OnRowEditing="EditRecord"
OnRowDataBound="onrowdatabound" CellPadding="4" CellSpacing="2" OnRowCancelingEdit="CancelRecord"
OnRowUpdating="UpdateRecord" OnRowDeleting="DeleteRecord" HeaderStyle-HorizontalAlign="left"
RowStyle-VerticalAlign="Top" ForeColor="#333333" GridLines="None">
<Columns>
<asp:TemplateField ShowHeader="False" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<table>
<tr>
<td>
<asp:LinkButton ID="lbkUpdate" runat="server" CausesValidation="True" CommandName="Update"
Text="Update"></asp:LinkButton>
</td>
<td>
</td>
<td>
<asp:LinkButton ID="lnkCancel" runat="server" CausesValidation="False" CommandName="Cancel"
Text="Cancel"></asp:LinkButton>
</td>
</tr>
</table>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lnkAdd" runat="server" CausesValidation="False" CommandName="Insert"
Text="Insert"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<%# Eval("Name")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="Server" Text='<%# Eval("Name") %>' Columns="20"></asp:TextBox>
<asp:RequiredFieldValidator ID="req1" runat="Server" Text="Please Enter The Name"
ControlToValidate="txtName"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<%# Eval("Designation")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDesignation" runat="Server" Text='<%# Eval("Designation") %>'
Columns="30"></asp:TextBox>
<asp:RequiredFieldValidator ID="req2" runat="Server" Text="Please Enter The Designation"
ControlToValidate="txtDesignation"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<%# Eval("Age")%>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddl_age" runat="server" Text='<%# Eval("Age") %>'>
<%-- <asp:ListItem>Select Age</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvalid_age" runat="server" ErrorMessage="Please Choose the Age"
ControlToValidate="ddl_age" SetFocusOnError="True" InitialValue="Select Age"></asp:RequiredFieldValidator></td>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Gender" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<%# Eval("Gender")%>
</ItemTemplate>
<EditItemTemplate>
<asp:RadioButtonList ID="Rlist_gender" runat="server" Text='<%# Eval("Gender") %>'>
<asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:RadioButtonList>
<asp:RequiredFieldValidator ID="Rfvalid_gender" runat="server" ErrorMessage="Please Choose the gender"
ControlToValidate="Rlist_gender" SetFocusOnError="True"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Native Place" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<%# Eval("Native Place")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="NativePlace" runat="Server" Text='<%# Eval("Native Place") %>' Columns="30"></asp:TextBox>
<asp:RequiredFieldValidator ID="req3" runat="Server" Text="Please Enter The Native Place"
ControlToValidate="NativePlace"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<%# Eval("Description")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="Description" runat="Server" Text='<%# Eval("Description") %>' Columns="30"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="link buttons" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<%--<asp:LinkButton runat="server" ID="lnkedit" Text="Edit" CommandName="Edit"></asp:LinkButton>
--%>
<span onclick="return confirm('Are you sure to Delete the record?')">
<asp:LinkButton runat="server" ID="lnkdelete" Text="Delete" CommandName="Delete"
CausesValidation="False"></asp:LinkButton>
</span>
</ItemTemplate>
<HeaderTemplate>
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
</body>
</html>
visual webpart.ascx.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;
using System.Data;
using System.Collections;
using System.Collections.Generic;
namespace Crudlistoperations.VisualWebPart2
{
public partial class VisualWebPart2UserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
displaydata();
}
}
public void displaydata()
{
gridViewManager.DataSource = GetData();
gridViewManager.DataBind();
}
#region Try2
DataTable GetData()
{
SPSite oSiteCollection = new SPSite(SPContext.Current.Site.Url);
SPWeb oWeb = oSiteCollection.OpenWeb();
SPList oSPList = oWeb.Lists["Registration"];
SPListItemCollection oSPListItemCollection = oSPList.Items;
DataTable dt = new DataTable();
try
{
dt.Columns.Add("AutoID", typeof(Int32));
dt.Columns.Add("Name", typeof(String));
dt.Columns.Add("Designation", typeof(String));
dt.Columns.Add("Age", typeof(Int32));
dt.Columns.Add("Gender", typeof(String));
dt.Columns.Add("Native Place", typeof(String));
dt.Columns.Add("Description", typeof(String));
DataRow dataRow;
foreach (SPListItem oSplistItem in oSPListItemCollection)
{
dataRow = dt.Rows.Add();
dataRow["AutoID"] = Convert.ToInt32(oSplistItem["ID"].ToString());
dataRow["Name"] = oSplistItem["Title"].ToString();
dataRow["Designation"] = oSplistItem["Designation"].ToString();
dataRow["Age"] = Convert.ToInt32(oSplistItem["Age"].ToString());
dataRow["Gender"] = oSplistItem["Gender"].ToString();
dataRow["Native Place"] = oSplistItem["Native Place"].ToString();
dataRow["Description"] = oSplistItem["Description"].ToString();
}
return dt;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Managers Approval" + ex.Message.ToString());
return dt;
}
#endregion Try2
}
protected void EditRecord(object sender, GridViewEditEventArgs e)
{
gridViewManager.EditIndex = e.NewEditIndex;
displaydata();
}
protected void CancelRecord(object sender, GridViewCancelEditEventArgs e)
{
gridViewManager.EditIndex = -1;
displaydata();
}
protected void onrowdatabound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ArrayList list = new ArrayList();
list.Add("DMG");
list.Add("SVC");
DropDownList theDropDownList = (DropDownList)e.Row.FindControl("ddl_age");
theDropDownList.DataSource = list;
theDropDownList.DataBind();
}
}
protected void UpdateRecord(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)gridViewManager.Rows[e.RowIndex];
int index = row.DataItemIndex;
TextBox tName = (TextBox)row.FindControl("txtName");
TextBox tDesignation = (TextBox)row.FindControl("txtDesignation");
DropDownList dAge = (DropDownList)row.FindControl("ddl_age");
RadioButtonList rGender = (RadioButtonList)row.FindControl("Rlist_gender");
TextBox tNativeplace = (TextBox)row.FindControl("NativePlace");
TextBox tDesc = (TextBox)row.FindControl("Description");
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = site.OpenWeb())
{
SPList myList = web.Lists["Registration"];
SPListItemCollection myListItemcoll = myList.Items;
int itemcount = myListItemcoll.Count;
for (int i = 0; i <= itemcount - 1; i++)
{
SPListItem myListItem = myListItemcoll[i];
if (index == i)
{
myListItem["Title"] = tName.Text.ToString();
myListItem["Designation"] = tDesignation.Text.ToString();
myListItem["Age"] = dAge.SelectedItem.Value;
myListItem["Gender"] = rGender.SelectedItem.Value;
myListItem["Native Place"] = tNativeplace.Text.ToString();
myListItem["Description"] = tDesc.Text.ToString();
myListItem.Update();
Response.Write("<script LANGUAGE='JavaScript' >alert('Updated Successfully'); </script>");
}
}
gridViewManager.EditIndex = -1;
displaydata();
}
}
}
protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)gridViewManager.Rows[e.RowIndex];
int a = row.DataItemIndex;
SPSite oSiteCollection = new SPSite(SPContext.Current.Site.Url);
SPWeb currentWeb = oSiteCollection.OpenWeb();
SPList lst = currentWeb.Lists["Registration"];
SPListItemCollection myColl = lst.Items;
int itemcount = myColl.Count;
for (int i = 0; i <= itemcount; i++)
{
if (i == a)
{
myColl[i].Delete();
gridViewManager.DataSource = GetData();
gridViewManager.DataBind();
}
}
}
}
}
ERROR OCCUR THIS LINES:
------------------------------------------
protected void onrowdatabound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ArrayList list = new ArrayList();
list.Add("DMG");
list.Add("SVC");
DropDownList theDropDownList = (DropDownList)e.Row.FindControl("ddl_age");
theDropDownList.DataSource = list;
theDropDownList.DataBind();
}
ERRor:
____________________________________________________________
Server Error in '/' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
Crudlistoperations.VisualWebPart2.VisualWebPart2UserControl.onrowdatabound(Object sender, GridViewRowEventArgs e) +362
System.Web.UI.WebControls.GridView.CreateRow(Int32 rowIndex, Int32 dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState, Boolean dataBind, Object dataItem, DataControlField[] fields, TableRowCollection rows, PagedDataSource pagedDataSource) +281
System.Web.UI.WebControls.GridView.CreateChildControls(IEnumerable dataSource, Boolean dataBinding) +3339
System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data) +71
System.Web.UI.WebControls.GridView.PerformDataBinding(IEnumerable data) +17
System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data) +146
System.Web.UI.WebControls.DataBoundControl.PerformSelect() +260
Crudlistoperations.VisualWebPart2.VisualWebPart2UserControl.displaydata() +124
Crudlistoperations.VisualWebPart2.VisualWebPart2UserControl.Page_Load(Object sender, EventArgs e) +88
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +24
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +41
System.Web.UI.Control.OnLoad(EventArgs e) +131
System.Web.UI.Control.LoadRecursive() +65
System.Web.UI.Control.AddedControl(Control control, Int32 index) +349
Crudlistoperations.VisualWebPart2.VisualWebPart2.CreateChildControls() +154
System.Web.UI.Control.EnsureChildControls() +145
System.Web.UI.Control.PreRenderRecursiveInternal() +60
System.Web.UI.Control.PreRenderRecursiveInternal() +223
System.Web.UI.Control.PreRenderRecursiveInternal() +223
System.Web.UI.Control.PreRenderRecursiveInternal() +223
System.Web.UI.Control.PreRenderRecursiveInternal() +223
System.Web.UI.Control.PreRenderRecursiveInternal() +223
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3393