Monday 20 June 2011

Can not connect to configuration database (error) in SharePoint


Here are some method to resolve this error taken from the Microsoft support site.i faced this problem and after restart of my MS SQL service for Sharepoint it works. So first please try Restarting the MS SQL service then you can follow the below steps

 

 

Method 1: Verify that the SQL database is running

  1. Click Start, point to Programs, point to Administrative Tools, and then click Services.
  2. In the list of services, locate the MSSQLSERVER service. This service may also be listed as MSSQL$SHAREPOINT.
  3. Note the value of the Status column. If the Status column lists Started, the database server is running. If the Status column is empty, the database server is not running.

    To start the database server, right-click the MSSQLSERVER service, and then click Start.

Method 2: Verify that IIS is not running in IIS 5.0 isolation mode

  1. Click Start, point to Programs, point to Administrative Tools, and then click Internet Information Services (IIS) Manager.
  2. In the left pane, right-click your server name, and then expand the local computer.
  3. Right click Web Sites, and then click Properties.
  4. Click the Service tab.
  5. Click to clear the Run WWW service in IIS 5.0 isolation mode check box.
  6. Click OK
  7. To start the WWW service, click Yes.

Method 3: Make sure that the account that is used by the application pool is the account that has the required permissions to the SQL Server database

First, you must first determine the application pool identity. To do this, follow these steps:
  1. Click Start, point to Programs, point to Administrative Tools, and then click Internet Information Services (IIS) Manager.
  2. Double-click the Web Sites folder.
  3. Right-click the virtual server that is running Windows SharePoint Services 2.0, and then click Properties.
  4. Click Home Directory.
  5. Note the information that is in the Application name box (this is the application pool name), and then click Cancel.
  6. In the left pane, right-click Application Pools, and then click Properties.
  7. Click the Identity tab.
  8. Note the information that is in the Application pool identitypane, and then click Cancel.
Next, you must verify that this account has the required permission the SQL Server database. To do this, follow these steps:
  1. Click Start, point to Programs, point to Microsoft SQL Server, and then click Enterprise Manager.
  2. In the left pane, double-click Microsoft SQL Servers, and then double-click your SQL server group.
  3. Double-click your server.
  4. Double-click Security.
  5. In the left pane, click Logins.
  6. In the right pane, double-click the user who you noted step 8 of the previous procedure.
  7. In the SQL Server Login Properties dialog box, click Server Roles.
  8. Click to select both the Security Administrators and the Database Creators check boxes, and then click Database Access.
  9. Under the Permit column, click to select the Windows SharePoint Services database.
  10. Click OK.

Method 4: Make sure that you have network connectivity and correct name resolution between the servers

To do this, follow these steps:
  1. Verify that the Windows SharePoint Services server is using the correct IP address for the SQL server. To do this, run the ping command on the Windows SharePoint Services server.
  2. Verify that the Windows SharePoint Services server is obtaining the correct IP address for the SQL server from DNS. To do this, run the nslookup command from the Windows SharePoint Services server.
  3. Make sure that there are no incorrect entries for the SQL server. To do this, examine the Hosts file on the Windows SharePoint Services server. This file is in the following location:
    %systemroot%\system32\drivers\etc\Hosts
  4. On the Windows SharePoint Services server, look for SQL client aliases. To do this, follow these steps:
    1. Click Start, click Run, and then type cliconfg in the Open box.
    2. Click the Alias tab.
    By default, there are no SQL client aliases. If you have any aliases for the SQL server, verify that they are correct, or remove them.

Wednesday 15 June 2011

Reading the Data From EXCEL Sheet in SharePoint and Asp.net




Method to read the Data from Excel Sheet

#region Read Data from Excel Sheet
        /// <summary>
        /// Read the Data from Excel Sheet.
        /// </summary>
        /// <param name="filePath">Excel File Path</param>
        /// <returns>Return in Datatable format</returns>
        private DataTable ReadExcelData(string filePath)
        {
            DataTable excelData = new DataTable();
            try
            {
                string fileExtension = Path.GetExtension(filePath).ToLower();

                string excelConnectionString = "";
                if (fileExtension == ".xlsx")
                {


                    //Get the Office 2007 Format
                    excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=YES;\"";
                }
                else
                {
                    //Get the Office 2003 Format


                    excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;'";
                }

                excelConnectionString = string.Format(excelConnectionString, filePath);



                //System.Threading.Thread.Sleep(10000);

                //Open the Oledb connection and get the data from Excel Sheet
                //Fill the data in DataTable (excelData).
                OleDbConnection connection = new OleDbConnection(excelConnectionString);
                OleDbCommand command = new OleDbCommand("select SAPCode,ImpactProdDesc,Notes from [Sheet1$]", connection);
                OleDbDataAdapter dataAdapter = new OleDbDataAdapter();
                //excelData.TableName = "tempCandidateList";

                connection.Open();
                dataAdapter.SelectCommand = command;
                dataAdapter.Fill(excelData);
                connection.Close();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
                objBusinessEntity.ErrorLog(ex.Message + ex.StackTrace);
                //utility.saveError(ex, "Create_candidate.aspx", "ReadExcelData: create_candidate");
            }
            return excelData;
        }
        #endregion


 Method to insert the Data into SPLIST item or Table row:

        #region Insert Excel Data
        /// <summary>
        /// Validate the Mandatory fields
        /// If Mandatory fields are missing, update the status is Invalid
        /// If Mandatory fields are satisfied, Insert into Database and update the status as InsertionSuccess.
        /// </summary>
        /// <param name="excelData">Excel Data within Datatable</param>
        /// <returns>List of Candidate with updated status.</returns>
        private DataTable UpdataExcelData(DataTable excelData)
        {
            Guid candidateID;
            DataColumn columnStatus = new DataColumn("ExcelStatus");
            excelData.Columns.Add(columnStatus);

            try
            {
                SPListItemCollection splistcollImpact = slImpactAnalysis.Items;
                //int intNumber = splistcollDesigncheck.Count;

                for (int count = 0; count < excelData.Rows.Count; count++)
                {
                    SPListItem splistitemImpact = null;
                    string excelstatus = "";

                    if ((excelData.Rows[count]["SAPCode"].ToString() == "") || (excelData.Rows[count]["ImpactProdDesc"].ToString() == "")
                        || (excelData.Rows[count]["Notes"].ToString() == "")
                        )
                    {
                        excelstatus = "invalid";
                        goto excelLable;
                    }
                    EntityList<GenerateIDItem> entGenerateID = dt.GetList<GenerateIDItem>("GenerateID");
                    var generatedID = from gen in entGenerateID.ToList()
                                      where gen.Title == "ImpactAnalysis"
                                      select gen;

                    // splistitemMomMastergenlist = splistcollMomMastergencol.GetItemById(2);
                    // splistitemMomMastergenlist["MOMID"] = Convert.ToInt32(splistitemMomMastergenlist["MOMID"]) + 1;
                    int intItemID = Convert.ToInt32(generatedID.ToList()[0].LastID);
                    generatedID.ToList()[0].LastID = generatedID.ToList()[0].LastID + 1;
                    splistitemImpact = splistcollImpact.Add();
                    EntityList<PartPhaseMasterItem> entityPhaseMaster = dt.GetList<PartPhaseMasterItem>(objBusinessEntity.PartPhaseMaster);

                    string strPhaseno = objBusinessEntity.PartPhaseNo(entityPhaseMaster, "Impact Analysis");
                    if (!string.IsNullOrEmpty(strPhaseno))
                    {
                        splistitemImpact["Title"] = string.Concat(strBOMID, ":", strPhaseno);
                    }

                    splistitemImpact["ImpactAnalysisNo"] = intItemID;
                    splistitemImpact["BOMID"] = objBusinessEntity.GetLookupValue(objBusinessEntity.BOM, "BOMNo", strBOMID); ;
                    splistitemImpact["SAPCode"] = excelData.Rows[count]["SAPCode"].ToString();
                    splistitemImpact["ImpactedProductDescription"] = excelData.Rows[count]["ImpactProdDesc"].ToString();
                    splistitemImpact["ImpactedPartNo"] = strPartNo;
                    splistitemImpact["ImpactedPartDescription"] = strPartDesc;
                    splistitemImpact["RetrievalStatus"] = "Manual";
                    splistitemImpact["FlowChartID"] = strFlowChartID;
                    splistitemImpact["Notes"] = excelData.Rows[count]["Notes"].ToString();




                excelLable:
                    if (string.IsNullOrEmpty(excelstatus))
                    {
                        try
                        {
                            splistitemImpact.Update();
                            dt.SubmitChanges();
                            excelData.Rows[count]["ExcelStatus"] = "InsertionSuccess";

                        }
                        catch
                        {
                            excelData.Rows[count]["ExcelStatus"] = "InsertionFailed";
                        }
                    }
                    else
                    {
                        excelData.Rows[count]["ExcelStatus"] = excelstatus;
                    }

                }

            }
            catch (Exception ex)
            {
                objBusinessEntity.ErrorLog(ex.Message + ex.StackTrace);//utility.saveError(ex, "Create_candidate.aspx", "UpdataExcelData: create_candidate");
            }

            return excelData;
        }
        #endregion
Button click event to process the Data from Excel Sheet:
        protected void btnProcess_Click(object sender, EventArgs e)
        {
            try
            {
                if (fuimpactedxls.PostedFile != null)
                {
                    //File Name of the Excel sheet
                    string excelFileName = fuimpactedxls.PostedFile.FileName.ToLower();
                    excelFileName = Path.GetFileName(excelFileName);
                    //Get the file extension of the excel sheet
                    string fileExtension = Path.GetExtension(excelFileName);
                    string excelFullPath = "";
                    //excelFullPath = @"C:\Users\vinitkumar.poshan\Desktop\ImpactedTemplate";
                    if (fileExtension == ".xlsx")
                    {
                        // Get the directory to save the excel sheet
                        excelFullPath = strFilepath;
                        //Create the Directory if not exists.
                        if (!Directory.Exists(excelFullPath))
                        {
                            Directory.CreateDirectory(excelFullPath);
                        }
                        excelFullPath += Guid.NewGuid().ToString() + "_" + excelFileName;
                        //Save the Excel sheet.
                        fuimpactedxls.SaveAs(excelFullPath);

                        //Read the excel sheet and get the data in DataTable format.
                        DataTable excelData = new DataTable();
                        excelData = ReadExcelData(excelFullPath);
                        Boolean isEmpty = false;

                        for (int i = 0; i < excelData.Rows.Count; i++)
                        {
                            isEmpty = true;
                            for (int j = 0; j < excelData.Columns.Count; j++)
                            {

                                if (
                                  string.IsNullOrEmpty(excelData.Rows[i][j].ToString()) == false)
                                {
                                    isEmpty = false; break;
                                }
                            } if (isEmpty == true)
                            {
                                excelData.Rows.RemoveAt(i); i--;
                            }
                        }

                        //DataTable dt = ValidateExcelData(excelData);
                        DataTable excelExecutionStatus = UpdataExcelData(excelData);
                        DataTable dtxls = getImpactManual();



                        //Bind the Data to Gridview.
                        gvfinal.DataSource = dtxls;
                        gvfinal.DataBind();

                    }

                }
            }
            catch (Exception ex)
            {

                objBusinessEntity.ErrorLog(ex.Message + ex.StackTrace);
            }
        }

Here three Methods are there ,using these three methods we can read excel data and store into a list or Table.

Please create a Excel based on your table column name or list column name.

First row of excel sheet it will use as a header column name and then data will be read.

Hope this is enough ....if any problem comes please let me know 



Join Operation between Lists in SharePoint 2010 using SPMetal and LINQ to SharePoint


Required class:

Entity Class generated using SPMEtal.exe

Procedure To create Entity class:

     create a text file and copy following text in green

set SPMETAL="C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN\SPMETAL.EXE"
%SPMETAL% /web:http://sitename/ /namespace:SharePointLINQ.JoinLists1 /code:EntityClass.cs

pause

Add the entity class into your sharepoint project solution

Add the reference of the class in project

join Operation between two or more  list using Entity class:

List Used Here are:
PartphaseDesign
PartDesign
DesignDocument
PartPhaseMaster

so we are combining 4 lists and giving the result in linq .we can bind this linq result to any grid.

CODE:

                EntityList<PartPhaseDesignItem> entPhaseDesign = dt.GetList<PartPhaseDesignItem>(objBusinessEntity.PartPhaseDesign);
                EntityList<PartPhaseMasterItem> entPhaseMaster = dt.GetList<PartPhaseMasterItem>(objBusinessEntity.PartPhaseMaster);
                EntityList<DesignDocumentDocument> entAttachments = dt.GetList<DesignDocumentDocument>(objBusinessEntity.DesignDocument);
                EntityList<PartDesignItem> entPartDesign = dt.GetList<PartDesignItem>(objBusinessEntity.PartDesign);
                var linqPhaseDesign = from d in entPhaseDesign.ToList()
                                      select d;
                var linqPhaseMaster = from m in entPhaseMaster.ToList()
                                      select m;
                var linqpartdesign = from c in entPartDesign.ToList()
                                     where c.BOMNo.BOMNo == strBOMID
                                     select c;
                var linqattach = from at in entAttachments.ToList()
                                 select at;
                if (linqpartdesign.Count() != 0)
                {
                                       var phaseDoc = from phaseitem in entPhaseDesign.ToList().Where(phaseitem => phaseitem.PartPhaseDesignNo.PartDesignNo == linqpartdesign.ToList()[0].PartDesignNo)
                                   from proj in linqattach.Where(proj =>
                                       phaseitem.Id.ToString() == proj.ItemID && strColumnName == proj.ColumnName
                                       && strListName == proj.ListName).DefaultIfEmpty()
                                   select new
                                       {

                                           //PartPhaseNo = (parthphase == null) ? "N/A" : parthphase.PartPhaseNo,
                                           //PhaseName = (parthphase == null) ? "N/A" : parthphase.PhaseName,
                                           //ListName = (parthphase == null) ? "N/A" : parthphase.ListName,
                                           PartPhaseID = (phaseitem == null) ? "N/A" : phaseitem.Id.ToString(),
                                           Remarks = (phaseitem == null) ? "N/A" : phaseitem.Remarks,
                                           FileName = (proj == null) ? "N/A" : proj.Name,
                                           Filepath = (proj == null) ? "N/A" : proj.Path + "/" + proj.Name,
                                           AssignedTo = (phaseitem == null) ? "N/A" : phaseitem.AssignedToName.ToString(),
                                           TargetDate = (phaseitem == null) ? System.DateTime.Now.Date : Convert.ToDateTime(phaseitem.TargetDate),
                                           ExistingData = (phaseitem == null) ? "N/A" : phaseitem.ExistingData,
                                           DocumentID = (proj == null) ? "N/A" : proj.Id.ToString(),
                                           PartphaseNo = (phaseitem == null) ? "N/A" : phaseitem.PartPhaseNo.PartPhaseNo.ToString(),
                                           //PartdesignID = (partdes == null) ? "N/A" : partdes.PartDesignNo
                                       };

                    var chklist1 = from parthphase in entPhaseMaster.ToList()
                                   from phaseitem in phaseDoc.ToList().Where(proj => proj.PartphaseNo == parthphase.PartPhaseNo).DefaultIfEmpty()
                                   orderby parthphase.PartPhaseNo
                                   select new
                                   {

                                       PartPhaseNo = (parthphase == null) ? "N/A" : parthphase.PartPhaseNo,
                                       PhaseName = (parthphase == null) ? "N/A" : parthphase.PhaseName,
                                       ListName = (parthphase == null) ? "N/A" : parthphase.ListName,
                                       PartPhaseID = (phaseitem == null) ? "N/A" : phaseitem.PartPhaseID.ToString(),
                                       Remarks = (phaseitem == null) ? "" : phaseitem.Remarks,
                                       FileName = (phaseitem == null) ? "N/A" : phaseitem.FileName,
                                       Filepath = (phaseitem == null) ? "N/A" : phaseitem.Filepath + "/" + phaseitem.FileName,
                                       AssignedTo = (phaseitem == null) ? "" : phaseitem.AssignedTo.ToString(),
                                       TargetDate = (phaseitem == null) ? System.DateTime.Now.Date : Convert.ToDateTime(phaseitem.TargetDate),
                                       ExistingData = (phaseitem == null) ? "" : phaseitem.ExistingData,
                                       DocumentID = (phaseitem == null) ? "N/A" : phaseitem.DocumentID.ToString(),
                                       PartdesignID = (phaseitem == null) ? "N/A" : linqpartdesign.ToList()[0].PartDesignNo
                                   };

Where the item is returning null give some value either empty string.... Very very important

Upload files in SharePoint Document Library using custom Webpart



Problem : Upload the file to SharePoint Document Library

Solution: Below is the code to upload the file to SharePoint Document Library.


  public string SingleUpload(FileUpload uploadFile, string tblName, string columnName, string itemID, string FolderName)
        {
            obDoc = dt.GetList<DesignDocumentDocument>(DesignDocument);
            string strReturn = string.Empty;
            objWeb = spSite.OpenWeb();
            if (uploadFile.PostedFile.FileName != string.Empty)
            {
                string fileName = Path.GetFileName(uploadFile.FileName);
                string destUrl = spSite.Url + "/" + FolderName + "/" + fileName;
                var lnqDesignDoc = from objDesignDoc in obDoc.ToList()
                                   where Convert.ToString(objDesignDoc.Name) == fileName
                                   select objDesignDoc;
                if (lnqDesignDoc.Count() > 0)
                {
                    strReturn = "0";
                }
                else
                {
                    SPWeb site = new SPSite(destUrl).OpenWeb();

                    SPList oList = objWeb.Lists[GenerateID];//"GenerateID"
                    SPListItemCollection reqGenCol = oList.Items;
                    SPListItem reqList = reqGenCol.GetItemById(GetListItemID(reqGenCol, "UploadID", "Title"));
                    int upldId = Convert.ToInt32(reqList["LastID"].ToString());

                    reqList["LastID"] = Convert.ToString(upldId + 1);
                    string strUpldID = reqList["LastID"].ToString();
                    reqList.Update();

                    Stream fStream = uploadFile.PostedFile.InputStream;
                    byte[] contents = new byte[fStream.Length];

                    fStream.Read(contents, 0, (int)fStream.Length);
                    fStream.Close();


                    EnsureParentFolder(site, destUrl);

                    site.Files.Add(destUrl, contents);

                    SPListItem slist = site.GetListItem(destUrl);
                    slist["itemID"] = itemID;
                    slist["ListName"] = tblName;
                    slist["ColumnName"] = columnName;
                    slist["DocID"] = upldId;
                    slist.Update();

                    //strFID = fileName;

                    //IndexCount = strFID.IndexOf('_');

                    //iConcat = IndexCount + 1;
                    //iFileCount = (strFID.Length) - (iConcat);
                    //strFileName = fileName.Substring(iConcat, iFileCount);

                    strReturn = upldId + "," + destUrl;

                }
            }
            return strReturn;
        }

        public string EnsureParentFolder(SPWeb parentSite, string destinUrl)
        {
            destinUrl = parentSite.GetFile(destinUrl).Url;

            int index = destinUrl.LastIndexOf("/");
            string parentFolderUrl = string.Empty;

            if (index > -1)
            {
                parentFolderUrl = destinUrl.Substring(0, index);

                SPFolder parentFolder
                    = parentSite.GetFolder(parentFolderUrl);

                //if (parentFolder.Exists)
                //{

                //    //return string.Empty;
                //}

                if (!parentFolder.Exists)
                {
                    SPFolder currentFolder = parentSite.RootFolder;

                    foreach (string folder in parentFolderUrl.Split('/'))
                    {
                        currentFolder
                            = currentFolder.SubFolders.Add(folder);
                    }
                }
            }
            return parentFolderUrl;
        }


Please let us know if you have any comments regarding this solution. or if you have any better approach please share to us.

Thanks Happy SharePointers

GRID ROW EDIT UPDATE CANCEL in Asp.net Pages or SharePoint Webparts

ASPX PAGE CODE:

    <asp:GridView ID="gvElectrode" CssClass="griddisplay" runat="server" AutoGenerateColumns="False"
                ShowFooter="True" BorderColor="#cccccc" BorderWidth="1px" HorizontalAlign="Center"
                OnRowCancelingEdit="gvElectrode_RowCancelingEdit" OnRowEditing="gvElectrode_RowEditing"
                OnRowUpdating="gvElectrode_RowUpdating" DataKeyNames="ElectrodeID" OnPageIndexChanging="gvElectrode_PageIndexChanging"
                OnRowDataBound="gvElectrode_RowDataBound" OnRowCommand="gvElectrode_Rowcommand" PageSize="20">
                <Columns>
                    <asp:TemplateField HeaderText="S No." SortExpression="Name" ItemStyle-Width="40px">
                        <EditItemTemplate>
                            <%# Container.DataItemIndex + 1 %>
                        </EditItemTemplate>
                        <FooterTemplate>
              
                        </FooterTemplate>
                        <ItemTemplate>
                            <%# Container.DataItemIndex + 1 %>
                        </ItemTemplate>
                        <FooterStyle HorizontalAlign="Left" />
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="3D Final Electrode Design" SortExpression="Name" ItemStyle-Width="300px">
                        <EditItemTemplate>
                            <div class="inputarea">
                                <div class="txtarealarge">
                                    <asp:FileUpload ID="fu3dElectrode" runat="server" Visible="true"  />
                                    <asp:Label ID="lblData3D" runat="server"><a href="#" onclick="g_varSkipRefreshOnFocus = true;editDocumentWithProgID2('<%# Eval("FilePath3d") %>', '', 'SharePoint.OpenDocuments', '0', '<%# Eval("URL") %>', '0')"><%# Eval("3DElectrode")%></a></asp:Label>
                                
                                 <%--   <asp:LinkButton ID="lnkbut3DCon" CommandName="delete3D" runat="server" Text="Delete"
                                        ForeColor="Red" Visible="true"></asp:LinkButton>--%>
                                    <asp:HiddenField ID="hdf3dCon" runat="server" Value='<%# Eval("DocuementID3d") %>' />
                              
                                    <asp:RequiredFieldValidator ID="rfv3d" runat="server" ControlToValidate="fu3dElectrode"
                                        ErrorMessage="Select the File" ValidationGroup="valid" Display="Dynamic">
                                    </asp:RequiredFieldValidator>
                                </div>
                            </div>
                            <div class="inputarea">
                                <div class="lblarea">
                                    <asp:Label ID="lblNotes3dE" runat="server" Text="Notes   :" CssClass="lblarea"></asp:Label></div>
                                <div class="txtarea">
                                    <asp:TextBox ID="txtNotes3dE" runat="server" Text='<%# Bind("3DFinalNotes") %>' TextMode="MultiLine"
                                        MaxLength="250" /></div>
                            </div>
                        </EditItemTemplate>
                        <FooterTemplate>
                             <div class="inputarea">
                                <div class="txtarealarge">
                                    <asp:FileUpload ID="fu3dElectrode" runat="server" Visible="true"  />
                             
                              
                              
                                    <asp:RequiredFieldValidator ID="rfval1" runat="server" ControlToValidate="fu3dElectrode"
                                        ErrorMessage="Select the File" ValidationGroup="validate" Display="Dynamic">
                                    </asp:RequiredFieldValidator>
                                </div>
                            </div>
                            <div class="inputarea">
                                <div class="lblarea">
                                    <asp:Label ID="lblNotes3dF" runat="server" Text="Notes   :" CssClass="lblarea"></asp:Label></div>
                                <div class="txtarea">
                                    <asp:TextBox ID="txtNotes3dF" runat="server"  TextMode="MultiLine"
                                        MaxLength="250" /></div>
                            </div>
                        </FooterTemplate>
                        <ItemTemplate>
                            <div class="inputarea">
                                <div class="txtarealarge">
                                  
                                    <asp:Label ID="lblData3D" runat="server"><a href="#" onclick="editDocumentWithProgID2('<%# Eval("FilePath3d") %>', '', 'SharePoint.OpenDocuments', '0', '<%# Eval("URL") %>', '0')"><%# Eval("3DElectrode")%></a></asp:Label>
                              
                                
                              
                             
                                </div>
                            </div>
                            <div class="inputarea">
                                <div class="lblarea">
                                    <asp:Label ID="lblNotes3dI" runat="server" Text="Notes   :" CssClass="lblarea"></asp:Label></div>
                                <div class="txtarea">
                                    <asp:Label ID="txtNotes3dI" runat="server" Text='<%# Bind("3DFinalNotes") %>'
                                        MaxLength="250" /></div>
                            </div>
                        </ItemTemplate>
                        <FooterStyle HorizontalAlign="Left" />
                    </asp:TemplateField>




                      <asp:TemplateField HeaderText="2D Final Electrode Design" SortExpression="Name" ItemStyle-Width="300px">
                        <EditItemTemplate>
                            <div class="inputarea">
                                <div class="txtarealarge">
                                    <asp:FileUpload ID="fu2dElectrode" runat="server"  Visible="true"  />
                                    <asp:Label ID="lblData2D" runat="server"><a href="#" onclick="g_varSkipRefreshOnFocus = true; editDocumentWithProgID2('<%# Eval("FilePath2d") %>', '', 'SharePoint.OpenDocuments', '0', '<%# Eval("URL") %>', '0')"><%# Eval("2DElectrode")%></a></asp:Label>
                              
                                   <%-- <asp:LinkButton ID="lnkbut2DCon" CommandName="delete2D" runat="server" Text="Delete"
                                        ForeColor="Red" Visible="true"></asp:LinkButton>--%>
                                    <asp:HiddenField ID="hdf2dCon" runat="server" Value='<%# Eval("DocuementID2d") %>' />
                              
                                    <asp:RequiredFieldValidator ID="rfv2d" runat="server" ControlToValidate="fu2dElectrode"
                                        ErrorMessage="Select the File" ValidationGroup="valid" Display="Dynamic">
                                    </asp:RequiredFieldValidator>
                                </div>
                            </div>
                            <div class="inputarea">
                                <div class="lblarea">
                                    <asp:Label ID="lblNotes2dE" runat="server" Text="Notes   :" CssClass="lblarea"></asp:Label></div>
                                <div class="txtarea">
                                    <asp:TextBox ID="txtNotes2dE" runat="server" Text='<%# Bind("2DFinalNotes") %>' TextMode="MultiLine"
                                        MaxLength="250" /></div>
                            </div>
                        </EditItemTemplate>
                        <FooterTemplate>
                             <div class="inputarea">
                                <div class="txtarealarge">
                                    <asp:FileUpload ID="fu2dElectrode" runat="server" Visible="true"  />
                             
                              
                              
                                    <asp:RequiredFieldValidator ID="rfv2d" runat="server" ControlToValidate="fu2dElectrode"
                                        ErrorMessage="Select the File" ValidationGroup="validate" Display="Dynamic">
                                    </asp:RequiredFieldValidator>
                                </div>
                            </div>
                            <div class="inputarea">
                                <div class="lblarea">
                                    <asp:Label ID="lblNotes2dF" runat="server" Text="Notes   :" CssClass="lblarea"></asp:Label></div>
                                <div class="txtarea">
                                    <asp:TextBox ID="txtNotes2dF" runat="server"  TextMode="MultiLine"
                                        MaxLength="250" /></div>
                            </div>
                        </FooterTemplate>
                        <ItemTemplate>
                            <div class="inputarea">
                                <div class="txtarealarge">
                                  
                                    <asp:Label ID="lblData2D" runat="server"><a href="#" onclick="g_varSkipRefreshOnFocus = true; editDocumentWithProgID2('<%# Eval("FilePath2d") %>', '', 'SharePoint.OpenDocuments', '0', '<%# Eval("URL") %>', '0')"><%# Eval("2DElectrode")%></a></asp:Label>
                              
                                
                              
                             
                                </div>
                            </div>
                            <div class="inputarea">
                                <div class="lblarea">
                                    <asp:Label ID="lblNotes2dI" runat="server" Text="Notes   :" CssClass="lblarea"></asp:Label></div>
                                <div class="txtarea">
                                    <asp:Label ID="txtNotes2dI" runat="server" Text='<%# Bind("2DFinalNotes") %>' TextMode="SingleLine"
                                        MaxLength="250" /></div>
                            </div>
                        </ItemTemplate>
                        <FooterStyle HorizontalAlign="Left" />
                    </asp:TemplateField>
               
                    <asp:TemplateField HeaderText="Edit" ShowHeader="False" ItemStyle-Width="60px">
                        <EditItemTemplate>
                            <asp:ImageButton ID="ImageButton1" runat="server" CausesValidation="True" CommandName="Update"
                                ValidationGroup="validateEdit" ImageUrl="../_layouts/images/ExpressPLM/gridicon-floppy.gif" />
                            <asp:ImageButton ID="ImageButton2" runat="server" CausesValidation="false" CommandName="Cancel"
                                ImageUrl="../_layouts/images/ExpressPLM/gridicon-pencil-x.gif" />
                        </EditItemTemplate>
                        <FooterTemplate>
                            <asp:LinkButton ID="lnkAdd" runat="server" Text="Add" OnClick="lnkAdd_Click"
                                ValidationGroup="validate"></asp:LinkButton>
                        </FooterTemplate>
                        <ItemTemplate>
                            <asp:ImageButton ID="ImageButton3" runat="server" CausesValidation="false" CommandName="Edit"
                                ImageUrl="../_layouts/images/ExpressPLM/gridicon-pencil.gif" />
                        </ItemTemplate>
                        <ItemStyle HorizontalAlign="Center" />
                        <HeaderStyle HorizontalAlign="Center" />
                    </asp:TemplateField>
                    <%-- <asp:TemplateField HeaderText="Delete">
                                            <ItemTemplate>
                                                   <asp:ImageButton ID="ImageButton4" runat="server" CausesValidation="false" CommandName="Delete" ImageUrl="~/Images/griddelete.gif" />
                                            </ItemTemplate>
                                              <ItemStyle  HorizontalAlign="Center"/>
                                            <HeaderStyle  HorizontalAlign="Center"/>
                                        </asp:TemplateField>--%>
                </Columns>
                <EmptyDataTemplate>
                </EmptyDataTemplate>
                <FooterStyle HorizontalAlign="Center" />
            </asp:GridView>


CODE BEHIND CS FILE:

        #region Grid Events


        #region Add new
        /// <summary>
        /// Adding the new role to database
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkAdd_Click(object sender, EventArgs e)
        {
            try
            {
                SPListItemCollection slcollElectrode = slElectrodeDesign.Items;
                SPListItem slitemElectrode = slcollElectrode.Add();
                if (Page.IsValid)
                {
                    TextBox txtNotes3dF = (TextBox)gvElectrode.FooterRow.FindControl("txtNotes3dF");
                    TextBox txtNotes2dF = (TextBox)gvElectrode.FooterRow.FindControl("txtNotes2dF");
                    FileUpload  fu3dElectrode        =(FileUpload)gvElectrode.FooterRow.FindControl("fu3dElectrode");
                    FileUpload fu2dElectrode = (FileUpload)gvElectrode.FooterRow.FindControl("fu2dElectrode");
                    slitemElectrode["Final2DAttachment"]=txtNotes2dF.Text.Trim();
                    slitemElectrode["Final3DAttachment"]=txtNotes3dF.Text.Trim();
                    //Need to discuss what kind of status will be maintained
                    slitemElectrode["Status"]="Save";
                    slitemElectrode["MTFGBOMNO"] = objBusinessEntity.GetLookupValue(objBusinessEntity.MTFGBOM, "MTFGBOMNO", strMTFGBOMNO);
                    slitemElectrode.Update();
                    int intItemID = slitemElectrode.ID;

                    if (fu3dElectrode.PostedFile.FileName != string.Empty)
                    {
                        string file3Dretun = objBusinessEntity.SingleUpload(fu3dElectrode, objBusinessEntity.ElectrodeDesign, "3D_Electrode", intItemID.ToString(), objBusinessEntity.DesignDocument);
                    }
                    if (fu2dElectrode.PostedFile.FileName != string.Empty)
                    {
                        string file2Dretun = objBusinessEntity.SingleUpload(fu2dElectrode, objBusinessEntity.ElectrodeDesign, "2D_Electrode", intItemID.ToString(), objBusinessEntity.DesignDocument);
                    }

                    bindElectrodeDesign();
                   
                }
            }
            catch (Exception ex)
            {
               // ErrorLog.WriteError(ex.Message, "lnkAdd_Click");
            }
            finally
            {
               // FillRolesGrid();
            }
        }
        #endregion

        #region
        /// <summary>
        /// to cancel the editing of the role
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvElectrode_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            try
            {
                gvElectrode.EditIndex = -1;
                bindElectrodeDesign();
            }
            catch (Exception ex)
            {
               // ErrorLog.WriteError(ex.Message, "gvElectrode_RowCancelingEdit");
            }
        }
        #endregion

        #region
        /// <summary>
        /// to edit the existing role
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvElectrode_RowEditing(object sender, GridViewEditEventArgs e)
        {
            try
            {
                gvElectrode.EditIndex = e.NewEditIndex;
                bindElectrodeDesign();
            }
            catch (Exception ex)
            {
               // ErrorLog.WriteError(ex.Message, "gvElectrode_RowEditing");
            }
        }
        #endregion

        #region
        /// <summary>
        /// updating the existing role with new rolename
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvElectrode_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
               



              int itemID=int.Parse(gvElectrode.DataKeys[gvElectrode.EditIndex].Value.ToString());

                 SPListItemCollection slcollElectrode = slElectrodeDesign.Items;
                SPListItem slitemElectrode = slcollElectrode.GetItemById(itemID);
                if (Page.IsValid)
                {
                    EntityList<DesignDocumentDocument> entAttachments = dt.GetList<DesignDocumentDocument>("DesignDocument");
                    TextBox txtNotes2dE = (TextBox)gvElectrode.Rows[e.RowIndex].FindControl("txtNotes2dE");
                    TextBox txtNotes3dE = (TextBox)gvElectrode.Rows[e.RowIndex].FindControl("txtNotes3dE");
                    FileUpload fu3dElectrode = (FileUpload)gvElectrode.Rows[e.RowIndex].FindControl("fu3dElectrode");
                    FileUpload fu2dElectrode = (FileUpload)gvElectrode.Rows[e.RowIndex].FindControl("fu2dElectrode");



                    HiddenField hdf3dCon = (HiddenField)gvElectrode.Rows[e.RowIndex].FindControl("hdf3dCon");



                    HiddenField hdf2dCon = (HiddenField)gvElectrode.Rows[e.RowIndex].FindControl("hdf2dCon");
                    slitemElectrode["Final2DAttachment"] = txtNotes2dE.Text.Trim();
                    slitemElectrode["Final3DAttachment"] = txtNotes3dE.Text.Trim();
                    //Need to discuss what kind of status will be maintained
                    //slitemElectrode["Status"] = "Save";
                   // slitemElectrode["MTFGBOMNO"] = objBusinessEntity.GetLookupValue(objBusinessEntity.MTFGBOM, "MTFGBOMNO", strMTFGBOMNO);
                    slitemElectrode.Update();
                    int intItemID = slitemElectrode.ID;

                    if (fu3dElectrode.PostedFile.FileName != string.Empty)
                    {
                        int intDOC1 = Convert.ToInt32(hdf3dCon.Value);
                        var deletedocument1 = (from en in entAttachments.ToList()
                                               where en.DocID == intDOC1.ToString()
                                               select en).First();
                        entAttachments.DeleteOnSubmit(deletedocument1);
                        dt.SubmitChanges();
                      
                        string file3Dretun = objBusinessEntity.SingleUpload(fu3dElectrode, objBusinessEntity.ElectrodeDesign, "3D_Electrode", intItemID.ToString(), objBusinessEntity.DesignDocument);
                    }
                    if (fu2dElectrode.PostedFile.FileName != string.Empty)
                    {
                        int intDOC2 = Convert.ToInt32(hdf2dCon.Value);
                        var deletedocument1 = (from en in entAttachments.ToList()
                                               where en.DocID == intDOC2.ToString()
                                               select en).First();
                        entAttachments.DeleteOnSubmit(deletedocument1);
                        dt.SubmitChanges();
                        string file2Dretun = objBusinessEntity.SingleUpload(fu2dElectrode, objBusinessEntity.ElectrodeDesign, "2D_Electrode", intItemID.ToString(), objBusinessEntity.DesignDocument);
                    }

                   // bindElectrodeDesign();

                }
            }
            catch (Exception ex)
            {
              //  ErrorLog.WriteError(ex.Message, "gvElectrode_RowUpdating");
            }
            finally
            {
               gvElectrode.EditIndex = -1;
               bindElectrodeDesign();
            }
        }
        #endregion

        #region
        /// <summary>
        /// page changing events for gridview control
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvElectrode_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                gvElectrode.EditIndex = -1;
                gvElectrode.PageIndex = e.NewPageIndex;
                bindElectrodeDesign();
            }
            catch (Exception ex)
            {
               // ErrorLog.WriteError(ex.Message, "gvElectrode_PageIndexChanging");
            }
        }
        #endregion


        protected void gvElectrode_Rowcommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                LinkButton lnkbtnNew = e.CommandSource as LinkButton;
                GridViewRow gvrROW = lnkbtnNew.NamingContainer as GridViewRow;
                Label lblData3D = (Label)gvrROW.FindControl("lblData3D");
                FileUpload fu3dElectrode = (FileUpload)gvrROW.FindControl("fu3dElectrode");
                LinkButton lnkbut3DCon = (LinkButton)gvrROW.FindControl("lnkbut3DCon");
                HiddenField hdf3dCon = (HiddenField)gvrROW.FindControl("hdf3dCon");
                Label lblData2D = (Label)gvrROW.FindControl("lblData2D");
                FileUpload fu2dElectrode = (FileUpload)gvrROW.FindControl("fu2dElectrode");
                LinkButton lnkbut2DCon = (LinkButton)gvrROW.FindControl("lnkbut2DCon");
                HiddenField hdf2dCon = (HiddenField)gvrROW.FindControl("hdf2dCon");
                RequiredFieldValidator rfv3d = (RequiredFieldValidator)gvrROW.FindControl("rfv3d");
                RequiredFieldValidator rfv2d = (RequiredFieldValidator)gvrROW.FindControl("rfv2d");



                EntityList<DesignDocumentDocument> entAttachments = dt.GetList<DesignDocumentDocument>("DesignDocument");
                if (e.CommandName == "delete2D")
                {
                    int intDOC1 = Convert.ToInt32(hdf2dCon.Value);
                    var deletedocument1 = (from en in entAttachments.ToList()
                                           where en.DocID == intDOC1.ToString()
                                           select en).First();
                    entAttachments.DeleteOnSubmit(deletedocument1);
                    lblData2D.Visible = false;
                    lnkbut2DCon.Visible = false;
                    fu2dElectrode.Visible = true;
                    rfv2d.ValidationGroup = "validateEdit";
                }
                if (e.CommandName == "delete3D")
                {
                    int intDOC2 = Convert.ToInt32(hdf3dCon.Value);
                    var deletedocument2 = (from en in entAttachments.ToList()
                                           where en.DocID == intDOC2.ToString()
                                           select en).First();
                    entAttachments.DeleteOnSubmit(deletedocument2);
                    lblData3D.Visible = false;
                    lnkbut3DCon.Visible = false;
                    fu3dElectrode.Visible = true;
                    rfv3d.ValidationGroup = "validateEdit";
                }

                dt.SubmitChanges();


            }

            catch (Exception ex)
            {
                objBusinessEntity.ErrorLog(ex.Message + ex.StackTrace);
            }
        }
        #region
        /// <summary>
        /// binding the status radion button list to the gridview control
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvElectrode_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                //if ((e.Row.RowType == DataControlRowType.DataRow))
                //{
                //    RadioButtonList rbnStatus = (RadioButtonList)e.Row.FindControl("rbnStatus");
                //    Label lblStatus = (Label)e.Row.FindControl("lblStatus");
                //    if (lblStatus.Text == "True")
                //    {
                //        if (rbnStatus != null)
                //        {
                //            rbnStatus.SelectedValue = "1";
                //        }
                //        else
                //        {
                //            lblStatus.Text = "Active";
                //        }
                //    }
                //    else
                //    {
                //        if (rbnStatus != null)
                //        {
                //            rbnStatus.SelectedValue = "0";
                //        }
                //        else
                //        {
                //            lblStatus.Text = "In Active";
                //        }
                //    }
                //}
            }
            catch (Exception ex)
            {
               // ErrorLog.WriteError(ex.Message, "gvElectrode_RowDataBound");
            }
        }
        #endregion


        #endregion
        #region Bind Grid
        protected void bindElectrodeDesign()
        {
            try
            {
                var linqelctrode = from elct in entElectrode.ToList()
                                   where elct.MTFGBOMNO.MTFGBOMNO == strMTFGBOMNO
                                   select elct;
                dtElectrode.Columns.Add(new DataColumn("ElectrodeID", typeof(string)));
                dtElectrode.Columns.Add(new DataColumn("FilePath3d", typeof(string)));
                dtElectrode.Columns.Add(new DataColumn("3DElectrode", typeof(string)));
                dtElectrode.Columns.Add(new DataColumn("URL", typeof(string)));
                dtElectrode.Columns.Add(new DataColumn("DocuementID3d", typeof(string)));
                dtElectrode.Columns.Add(new DataColumn("3DFinalNotes", typeof(string)));
                dtElectrode.Columns.Add(new DataColumn("FilePath2d", typeof(string)));
                dtElectrode.Columns.Add(new DataColumn("2DElectrode", typeof(string)));
                dtElectrode.Columns.Add(new DataColumn("DocuementID2d", typeof(string)));
                dtElectrode.Columns.Add(new DataColumn("2DFinalNotes", typeof(string)));
                if (linqelctrode.Count() == 0)
                {
                  


                    dtElectrode.Rows.Add(dtElectrode.NewRow());

                    gvElectrode.DataSource = dtElectrode;
                    gvElectrode.DataBind();
                    gvElectrode.FooterRow.Visible = true;
                    gvElectrode.Rows[0].Visible = false;
                }
                else
                {

                    



                    for (int i = 0; i < linqelctrode.Count(); i++)
                    {
                        int intItemID = Convert.ToInt32(linqelctrode.ToList()[i].Id);

                        var linq2dattach = from att1 in entdoc.ToList().Where(att => att.ItemID == intItemID.ToString() && att.ListName == slElectrodeDesign.Title && att.ColumnName == str2Dattachment)
                                         select att1;
                        var linq3dattach = from att2 in entdoc.ToList().Where(att => att.ItemID == intItemID.ToString() && att.ListName == slElectrodeDesign.Title && att.ColumnName == str3Dattachment)
                                         select att2;
                        DataRow drow = dtElectrode.NewRow();
                        drow["ElectrodeID"] = linqelctrode.ToList()[i].Id;
                        drow["2DFinalNotes"] = linqelctrode.ToList()[i].Final2DAttachment;
                        drow["3DFinalNotes"] = linqelctrode.ToList()[i].Final3DAttachment;
                        drow["URL"] = SPContext.Current.Web.Url;

                        if (linq2dattach.Count() != 0)
                        {
                            drow["2DElectrode"] = linq2dattach.ToList()[0].Name;
                            drow["FilePath2d"] = linq2dattach.ToList()[0].Path + "/" + linq2dattach.ToList()[0].Name;
                            drow["DocuementID2d"] = linq2dattach.ToList()[0].DocID;
                        }
                        else
                        {
                            drow["DocuementID2d"] = "";
                        }
                        if (linq3dattach.Count() != 0)
                        {
                            drow["3DElectrode"] = linq3dattach.ToList()[0].Name;
                            drow["FilePath3d"] = linq3dattach.ToList()[0].Path + "/" + linq3dattach.ToList()[0].Name; ;
                            drow["DocuementID3d"] = linq3dattach.ToList()[0].DocID;
                        }
                        else
                        {
                            drow["DocuementID3d"] = "N/A";
                        }
                    


                        dtElectrode.Rows.Add(drow);

                    }

                 
                    //var linqattach=from doc in entdesigndoc.ToList().Where(doc=>

                    gvElectrode.DataSource = dtElectrode;
                    gvElectrode.DataBind();

                }

            }
            catch (Exception ex)
            {
                objBusinessEntity.ErrorLog(ex.Message + ex.StackTrace+ "bindElectrodeDesign");
            }
        }

        #endregion