List of article and related data Category - article

I wanted to export the list of articles and related data category in excel format, I have tried to export through knowledgeArticleVersion but unable to add data category column in the list. Could please help?
Here is my code of what I tried.
controller class:
public class contactquery{
public PageReference Export() {
return page.testExportexcel;
}
Public string Artdata;
public List<KnowledgeArticleVersion> cs{get; set;}
public contactquery()
{
List<KnowledgeArticleVersion> cs1 = new list<KnowledgeArticleVersion>();
cs = (KnowledgeArticleVersion [])database.query('Select id,ArticleNumber,ArticleType,FirstPublishedDate,Language,LastModifiedDate,LastPublishedDate,Title,urlname from KnowledgeArticleVersion where PublishStatus = \'Online\' and language = \'en_US\'');
for (KnowledgeArticleVersion c : cs)
{
System.debug(Artdata);
cs1.add(c);
}
}
}
VF page to display list of article:
<apex:page controller="contactquery" >
<apex:form >
<apex:pageBlock title="List of Published Articles" >
<div align="center">
<apex:commandButton action="{!Export}" value="Export"/>
</div>
<apex:pageBlockTable value="{!cs}" var="arti">
<apex:column value="{!arti.title}"/>
<apex:column value="{!arti.Urlname}"/>
<apex:column value="{!arti.ArticleNumber}"/>
<apex:column value="{!arti.ArticleType}"/>
<apex:column value="{!arti.FirstPublishedDate}"/>
<apex:column value="{!arti.Language}"/>
<apex:column value="{!arti.LastModifiedDate}"/>
<apex:column value="{!arti.LastPublishedDate}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
Vf page for export fuctionality:
<apex:page controller="contactquery" contentType="application/vnd.ms-excel#SalesForceExport.xls" cache="true">
<apex:pageBlock title="Export Results" >
<apex:pageBlockTable value="{!cs}" var="arti">
apex:column value="{!arti.title}"/>
<apex:column value="{!arti.Urlname}"/>
<apex:column value="{!arti.ArticleNumber}"/>
<apex:column value="{!arti.ArticleType}"/>
<apex:column value="{!arti.FirstPublishedDate}"/>
<apex:column value="{!arti.Language}"/>
<apex:column value="{!arti.LastModifiedDate}"/>
<apex:column value="{!arti.LastPublishedDate}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>

Related

Django - get table data from templates into views.py

I am making a restaurant application and currently working on takeaway food functionality i.e. user orders food online.
I am displaying food items from my postgresql database onto my takeaway.html template and assigning each food item a class. Each food item will have an 'add to basket' button, JavaScript provides all functionality related to the basket.
I have found some resources that mention using the GET method with a form but I'm still not too sure. I am curious as to how I can access this 'basket' in my views.py and be able to put the values into my database.
I wish to access the food name, quantity and the price from the table if possible. Any resources or help would be greatly appreciated.
takeaway.html
<div class="col-sm-12 my-auto">
<h3>Starters</h3>
{% for starter in starters %}
<div id="{{ starter.id }}">
<span class="food-item-name">{{ starter.name }}</span>
<div class="food-item-details">
<p>{{ starter.description }}</p>
<p class="food-item-price">{{ starter.price }}</p>
<p>{% for a in starter.allergen.all %}{{ a.name }} | {% endfor %}</p>
<button class="add-item-button" onclick="addToBasket(this)">Add to Basket</button>
</div>
{% endfor %}
</div>
<div>
<h3>Mains</h3>
{% for m in mains %}
<div id="{{ m.id }}">
<span class="food-item-name">{{ m.name }}</span>
<div class="food-item-details">
<p>{{ m.description }}</p>
<p class="food-item-price">{{ m.price }}</p>
<p>{% for a in m.allergen.all %}{{ a.name }} | {% endfor %}</p>
<button class="add-item-button" onclick="addToBasket(this)">Add to Basket</button>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
<div>
<h3>Basket</h3>
<form method="get">
<table id="basket" style="border: 1px solid black">
<tr>
<th>Item</th>
<th>Quantity</th>
<th>Price</th>
<th>Total Price of Item(s)</th>
</tr>
</table>
<h3 id="basket-total-price">0.0</h3>
<button type="submit">submit</button>
</form>
</div>
takeaway.js
function addToBasket(selected)
{
const id = selected.parentElement.parentElement;
const itemName = id.getElementsByClassName("food-item-name")[0].innerText;
const itemPrice = id.getElementsByClassName("food-item-price")[0].innerText;
// check if item already in basket
if (check(itemName))
{
updateQuantity(itemName);
updateItemPrice(itemName);
}
else
{
const basketTable = document.getElementById("basket");
const rowCount = basketTable.rows.length;
const row = basketTable.insertRow(rowCount);
const basketRowName = row.insertCell(0);
const basketRowQuantity = row.insertCell(1);
const basketRowPrice = row.insertCell(2)
const basketRowTotalPrice = row.insertCell(3);
basketRowName.className = "basket-item-name";
basketRowQuantity.className = "basket-item-quantity";
basketRowPrice.className = "basket-item-price";
basketRowTotalPrice.className = "basket-item-total-price";
basketRowName.innerText = itemName;
basketRowPrice.innerText = itemPrice;
basketRowQuantity.innerText = "1";
updateItemPrice(itemName);
}
}
// check if item already in basket
function check(itemName)
{
const basketTable = document.getElementById("basket");
for(let i = 0; i < basketTable.rows.length; i++)
{
if (basketTable.rows[i].cells[0].innerHTML === itemName)
{
return true;
}
}
}
// update quantity field for item
function updateQuantity(itemName)
{
const basketTable = document.getElementById("basket");
for(let i = 0; i < basketTable.rows.length; i++)
{
if (basketTable.rows[i].cells[0].innerHTML === itemName){
const itemQuantity = basketTable.rows[i].getElementsByClassName("basket-item-quantity")[0];
let quantity = Number(itemQuantity.innerText);
quantity += 1;
itemQuantity.innerText = quantity;
}
}
}
// update price for item and total basket
function updateItemPrice(itemName)
{
const basketTable = document.getElementById("basket");
let itemTotal = 0;
let basketTotal = 0;
for (let i = 0; i < basketTable.rows.length; i++)
{
if (basketTable.rows[i].cells[0].innerHTML === itemName)
{
let itemPrice = basketTable.rows[i].getElementsByClassName("basket-item-price")[0];
let itemQuantity = basketTable.rows[i].getElementsByClassName("basket-item-quantity")[0];
let itemPriceTotal = basketTable.rows[i].getElementsByClassName("basket-item-total-price")[0];
let overall = document.getElementById("basket-total-price");
let current_price = parseFloat(overall.innerText);
// update price for items x quantity
itemTotal = parseFloat(itemPrice.innerText) * parseInt(itemQuantity.innerText);
itemPriceTotal.innerText = ""+ itemTotal;
// update basket total price
basketTotal = current_price + itemTotal;
overall.innerHTML = ""+basketTotal
}
}
}

How to use if statments to run second function Google script

I am trying to speed up my script, right now I currently have it set up so that on a button click a custom dialog (HTML) appears asking some questions. On submit, it calls out a gs function to pull the info back as variables. Depending on the first answer I have a series of If statments that trigger. Each of them pull up a different template, make a copy, populate some cells, emails it to you, and then dumps the data into a tracker. Each of them are different so the script is rather long - is there a way to have each if statment its own function? Would this even help the speed? I am new to scripting so any feedback is appreciated. Below is the Code and HTML
function onOpen() //adds option to top row in case buttons are not working.
{
var ui = SpreadsheetApp.getUi();
ui.createMenu('Create Doc.')
.addItem('Create Tracked Document', 'addItem')
.addToUi();
}
function addItem()//starts the initiation process
{
var html = HtmlService.createTemplateFromFile('form')
.evaluate()
.setWidth(300)
.setHeight(550);
SpreadsheetApp.getUi()
.showModalDialog(html, 'Create New Document');
}
function addNewItem(form_data)//pulls data from form
{
var ui = SpreadsheetApp.getUi();
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
var n = new Date();
var now = ((n.getMonth()+1) + "/" + n.getDate() + "/" + n.getFullYear());
var doctyp = form_data.Document_Type;
var name = form_data.Name;
var title = form_data.Title;
var platform = form_data.Platform;
var area = form_data.Area;
var rota = form_data.Rotation;
var works = form_data.WorkSt;
var recipient = Session.getEffectiveUser().getEmail();
if (form_data.Document_Type == "Text2"){
var dumpfolder = DriveApp.getFolderById("12345")
var templateSheet = DriveApp.getFileById("67890");
var Newform2= templateSheet.makeCopy(title+ " "+now,dumpfolder);
var qs = SpreadsheetApp.open(Newform2);
var dropSheet = qs.getSheetByName("blank");
var URL3 = Newform2.getUrl();
dropSheet.getRange("i8").setValue(title);
dropSheet.getRange("bc5").setValue(now);
dropSheet.getRange("b5").setValue(platform);
dropSheet.getRange("p5").setValue(area);
dropSheet.getRange("x5").setValue(rota);
dropSheet.getRange("al5").setValue(works);
dropSheet.getRange("at6").setValue(name);
NewOPLPOA.setSharing(DriveApp.Access.DOMAIN,DriveApp.Permission.COMMENT);
NewOPLPOA.setOwner("ME");
sheet.appendRow([now,doctyp,name,title,platform,area,rota,works,URL3]);
GmailApp.sendEmail(recipient, title+ " has been created.", "Your document has been created." +'\n'+ "Here is the link to your copy! Link: " + URL3);
ui.alert("Email Sent", "An email has been sent with your documents link. You can also use the below link to view the document now, click ctrl C to copy. \
" + URL3, ui.ButtonSet.OK);
}
else if (form_data.Document_Type == "Text1"){
var dumpfolder = DriveApp.getFolderById("abcd")
var templateSheet = DriveApp.getFileById("bgtrd");
var Newform1 = templateSheet.makeCopy(title+ " "+now,dumpfolder);
var qs = SpreadsheetApp.open(Newform1);
var dropSheet = qs.getSheetByName("DOC1");
var URL4 = Newform1.getUrl();
dropSheet.getRange("aa3").setValue(platform);
dropSheet.getRange("ah3").setValue(area);
dropSheet.getRange("ao3").setValue(works);
NewSEWO.setSharing(DriveApp.Access.DOMAIN, DriveApp.Permission.COMMENT);
NewSEWO.setOwner("Me");
sheet.appendRow([now,doctyp,name,title,platform,area,rota,works,URL4]);
GmailApp.sendEmail(recipient, title+ " has been created.", "Your document has been created." +'\n'+ "Here is the link to your copy! Link: " + URL4);
ui.alert("Email Sent", "An email has been sent with your documents link. You can also use the below link to view the document now, click ctrl C to copy. \
" + URL4, ui.ButtonSet.OK);
}
else{
ui.alert("Error, Please try again, make sure you are listing all required information.");
}
}
--HTML--
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<form id="myform">
<div class="form-group">
<label for="Document_Type">Document Type</label>
<select class="form-control" id="Document_Type" name = "Document_Type" required="required">
<?
var SS = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Set Up");
var Avals = SS.getRange("A2:A").getValues();
var numberOfValues = Avals.filter(String).length;
var RangeVals = SS.getRange(2,1,numberOfValues).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeVals.length; ++i) { ?>
<option><?!= RangeVals[i] ?></option>
<? } ?>
</select>
</div>
<div class="form-group">
<label for ="Name">Your Name</label>
<select class="form-control" name='Name' id="Name" required="required">
<?
var AvalN = SS.getRange("E2:E").getValues();
var numberOfValuesN = AvalN.filter(String).length;
var RangeValsN = SS.getRange(2,5,numberOfValuesN).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsN.length; ++i) { ?>
<option><?!= RangeValsN[i] ?></option>
<? } ?>
</select>
</div>
<div class="form-group">
<label for="Platform">Platform</label>
<select class="form-control" id="Platform" name = "Platform" required="required">
<?
var AvalP = SS.getRange("C2:C").getValues();
var numberOfValuesP = AvalP.filter(String).length;
var RangeValsP = SS.getRange(2,3,numberOfValuesP).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsP.length; ++i) { ?>
<option><?!= RangeValsP[i] ?></option>
<? } ?>
</select>
</div>
<div class="form-group">
<label for="Area">Area</label>
<select class="form-control" id="Area" name = "Area" required="required">
<?
var AvalA = SS.getRange("D2:D").getValues();
var numberOfValuesA = AvalA.filter(String).length;
var RangeValsA = SS.getRange(2,4,numberOfValuesA).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsA.length; ++i) { ?>
<option><?!= RangeValsA[i] ?></option>
<? } ?>
</select>
</div>
<div class="block form-group">
<label for="Rotation">Rotation</label>
<select class="form-control" name='Rotation' id="Rotation">
<?
var AvalR = SS.getRange("F2:F").getValues();
var numberOfValuesR = AvalR.filter(String).length;
var RangeValsR = SS.getRange(2,6,numberOfValuesR).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsR.length; ++i) { ?>
<option><?!= RangeValsR[i] ?></option>
<? } ?>
</select>
</div>
<div class="block form-group">
<label for="WorkSt">Work Station</label>
<input type='text' name='WorkSt' id="WorkSt" />
</div>
<div class="block form-group">
<label for="Title">Title</label>
<input type='text' name='Title' id="Title" required="required"/>
</div>
<div class="block">
<button type="submit" class="action">Submit</button>
</div>
</form>
<script>
document.querySelector("#myform").addEventListener("submit",
function(e)
{
e.preventDefault(); //stop form from submitting
google.script.run.addNewItem(this);
google.script.host.close();//close this dialogbox
}
);
</script>
</body>
</html>
is there a way to have each if statement its own function?
For visibility purposes, you certainly can modify your code as
function addNewItem(form_data)//pulls data from form
{
var ui = SpreadsheetApp.getUi();
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
var n = new Date();
var now = ((n.getMonth()+1) + "/" + n.getDate() + "/" + n.getFullYear());
var doctyp = form_data.Document_Type;
var name = form_data.Name;
var title = form_data.Title;
var platform = form_data.Platform;
var area = form_data.Area;
var rota = form_data.Rotation;
var works = form_data.WorkSt;
var recipient = Session.getEffectiveUser().getEmail();
if (form_data.Document_Type == "Text2"){
function1();
}
else if (form_data.Document_Type == "Text1"){
function2();
}
else{
ui.alert("Error, Please try again, make sure you are listing all required information.");
}
function function1(){
var dumpfolder = DriveApp.getFolderById("12345")
var templateSheet = DriveApp.getFileById("67890");
...
}
function function2(){
var dumpfolder = DriveApp.getFolderById("abcd")
...
}
Would this even help the speed?
Not really. To help up speed, you should rather try to implement Best Practices.
In particular: Reduce repeated calls to external services, including SpreadsheetApp.
For example, try to position the cells to which you want to assign values into an adjacent range, so you can use the method setValues() instead of multiple setValue() and thus make your code more efficient.
Sample:
var range = dropSheet.getRange("I8:N8");
var values = [];
values[0] = [];
values[0].push(title, now, platform, area, rota, works, name);
range.setValues(values);
Also, try to avoid repeating the same request for each if condition and rather make a single request after exiting the if statement, e.g. for:
sheet.appendRow([now,doctyp,name,title,platform,area,rota,works,URL3]);
GmailApp.sendEmail(recipient, title+ " has been created.", "Your document has been created." +'\n'+ "Here is the link to your copy! Link: " + URL3);
ui.alert("Email Sent", "An email has been sent with your documents link. You can also use the below link to view the document now, click ctrl C to copy. \
" + URL3, ui.ButtonSet.OK);
I hope this helps!

Grails comparing a list within a list in a gsp

I have a one-to-many relationship table where I am grabbing a list of members by a committee id. When the output is displayed I get the correct amount of members but the corresponding committee position type is being displayed as a list and not the individual position for that committee.
So I came up with the idea of comparing the committee position list with a param that I pass.
When I put in the if tag, nothing is displayed. When I remote the tag, I can see the output of my list and the param that I am pasting into it. I have used == and .equals() but get that same output of nothing.
What an I missing?
Legacy DB Using Oracle 11g, and Grails 2.3.3
Here is an example of my list within a list.
Here is my GSP code
<thead>
<tr class="revheaddark-c">
<!-- display all of the current members information -->
<th width="33%" class="revheaddark-t"><g:message code="trustee.lastName.label" default="Name" /></th>
<th width="33%" class="revheaddark-t"><g:message code="trustee.committees.label" default="Officers of the Board" /></th>
<th width="33%" class="revheaddark-t"><g:message code="trustee.hospital.label" default="Trustee Membership" /></th>
</tr>
</thead>
<g:each in="${trusteeInstanceList}" status="i" var="trusteeInstance">
<tr class="${i % 2 == 0 ? 'even' : 'cellshade'}">
<td><g:link action="contactInfo" params="[contactId:'${trusteeInstance.id}']" id="${trusteeInstance.id}">${fieldValue(bean: trusteeInstance, field: "salutation")}${fieldValue(bean: trusteeInstance, field: "firstName")} ${fieldValue(bean: trusteeInstance, field: "middleName")} ${fieldValue(bean: trusteeInstance, field: "lastName")}</g:link></td>
enter code here
<td><g:each in="${trusteeInstance.membership}">
<g:if test="${it.committees.id == params.committee }">
<%--<tr><td>--%>
${params.committee }, ${it.position }, ${it.committees.id }
<%--</td></tr>--%>
</g:if>
<td><g:each in="${trusteeInstance.board}">
<g:if test="${it.boardName.next() == null}">${it.boardName} </g:if>
<g:else>${it.boardName}, </g:else>
</g:each></td>
</tr>
</g:each>
Here is my controller
def members(){
params.max = Math.min(params.max ? params.int('max'): 15, 100)
def listCommittees = Committees.findAll("from Committees as c where c.hospital.id = '1'")
def indexSearch = Trustee.withCriteria(){
//search by First letter of lastName
if(params.letter){
ilike("lastName", "${params.letter}%")
}
//search by lastName
if(params.lastName){
ilike("lastName", "%${params.lastName}%")
}
//search by firstName
if(params.firstName){
ilike("firstName", "%${params.firstName}%")
}
//search by hospitalName
// if(params.hospital){
// board{
// eq "hospital.id", params.long('hospital')
// }
// }
//search by committeeId
if(params.committee){
//display only members will the board id
membership{
eq "committees.id", params.long('committee')
}
}
//search by Type
if(params.mType){
membership{
eq("memberType", "${params.mType}")
}
}
//search by boardName
if(params.boardId){
//display only members with the boardName
board{
eq("id", params.long('boardId'))
}
}
like("is_Trustee","Y")
order("lastName", "asc")
}
//def memberTrustee = TrusteeMembership.findAll("from TrusteeMembership as tm where tm.committee.id = 'params.committee'")
respond Hospitals.list(params), model:[hospitalsInstanceCount: Hospitals.count(),
trusteeInstanceList : indexSearch,
//memberList: memberTrustee,
sideMenu: Hospitals.list(max:1, order:"desc")]
}
Here are the domains.
class TrusteeMembership implements Serializable{
String position
String memberType
static belongsTo = [trustee:Trustee, committees:Committees]//
static constraints = {
position nullable:true
memberType nullable:true, unique:true
}
static mapping = {
table 'BOT_TRUSTEE_COMMITTEES'
version false
id composite: ['trustee','committees']
trustee column:'TRUSTEE_ID'
committees column: 'COMMITTEE_ID'
position column:'POSITION'
memberType column:'TYPE'
}
package trusteedbtest
class Trustee {
String salutation
String firstName
String middleName
String lastName
static hasMany = [board:Boards, membership:TrusteeMembership]
static constraints = {
salutation nullable: true
firstName nullable: true
middleName nullable: true
lastName nullable: true
}
//map to the existing DB table
static mapping = {
table 'BOT_TRUSTEE'
id column:'TRUSTEE_ID'
salutation column: 'SALUTATION'
firstName column: 'FIRST_NAME'
middleName column: 'MIDDLE_INITIAL'
lastName column: 'LAST_NAME'
}
}

Is it possible to override form helpers?

Using the doc, I can set my own helper for the layout surrending my field, but I'd like to personalize also some fields given by play.
The main reason is for Twitter Bootstrap 2, where I need to change (in checkbox.scala.html)
#input(field, args:_*) { (id, name, value, htmlArgs) =>
<input type="checkbox" id="#id" name="#name" value="#boxValue" #(if(value == Some(boxValue)) "checked" else "") #toHtmlArgs(htmlArgs.filterKeys(_ == 'value))>
<span>#args.toMap.get('_text)</span>
}
to :
<label class="checkbox">
<input type="checkbox" name="#name" id="#id" value="#boxValue" #(if(value == Some(boxValue)) "checked" else "") #toHtmlArgs(htmlArgs.filterKeys(_ == 'value)) />
#args.toMap.get('_text)
</label>
How can I do that ?
Thanks for your help!
I finally did it like this :
I created a package views.helpers.form, that contains :
bootstrap.scala.html :
#(elements: helper.FieldElements)
<div class="control-group#if(elements.hasErrors) { error}">
<label class="control-label" for="#elements.id">#elements.label(elements.lang)</label>
<div class="controls">
#elements.input
#elements.infos(elements.lang).map { info =>
<span class="help-inline">#info</span>
}
#elements.errors(elements.lang).map { error =>
<span class="help-block">#error</span>
}
</div>
checkbox.scala.html :
#**
* Generate an HTML input checkbox.
*
* Example:
* {{{
* #checkbox(field = myForm("done"))
* }}}
*
* #param field The form field.
* #param args Set of extra HTML attributes ('''id''' and '''label''' are 2 special arguments).
* #param handler The field constructor.
*#
#(field: play.api.data.Field, args: (Symbol,Any)*)(implicit handler: helper.FieldConstructor, lang: play.api.i18n.Lang)
#boxValue = #{ args.toMap.get('value).getOrElse("true") }
#helper.input(field, args:_*) { (id, name, value, htmlArgs) =>
<label class="checkbox">
<input type="checkbox" id="#id" name="#name" value="#boxValue" #(if(value == Some(boxValue)) "checked" else "") #toHtmlArgs(htmlArgs.filterKeys(_ == 'value))>
#args.toMap.get('_text)
</label>
div>
</div>
And in my template, all I have to do is :
#import helper.{FieldConstructor, inputText, inputPassword} #** Import the original helpers *#
#import helpers.form.checkbox #** Import my helpers *#
#implicitField = #{ FieldConstructor(helpers.form.bootstrap.f) }
And voilĂ ! It works!
It will be simpler to just write your own tag with the code you want and use it instead of the provided helper. It will simplify potential issues related to overwritting platform tags.

Retrieve the values from a list to Gridview in SharePoint Webpart?

I have a List called Registration and the following are the columns of my list.
Column : Type
Employee Name : Person or Group
Manager Name : Person or Group
Practice Name : Single line of text
Program Name : Lookup
Status : Choice
Prerequisite : Multiple lines of text
And now i created a web part which will display all these values as a grid view
here is the code which i have done for webpart.cs
protected void Page_Load(object sender, EventArgs e)
{
gridViewManager.DataSource = GetData();
gridViewManager.DataBind();
}
#region Try2
DataTable GetData()
{
SPSite oSiteCollection = SPContext.Current.Site;
SPWeb oWeb = oSiteCollection.OpenWeb();
SPList oSPList = oWeb.Lists["Registration"];
SPListItemCollection oSPListItemCollection = oSPList.Items;
DataTable dt = new DataTable();
try
{
dt.Columns.Add("Employee Name", typeof(String));
dt.Columns.Add("Manager Name", typeof(String));
dt.Columns.Add("Practice Name", typeof(String));
dt.Columns.Add("Program Name", typeof(LookupField));
//dt.Columns.Add("Program Name", typeof(String));
dt.Columns.Add("Status", typeof(String));
dt.Columns.Add("Prerequisite", typeof(String));
DataRow dataRow;
foreach (SPListItem oSplistItem in oSPListItemCollection)
{
dataRow = dt.Rows.Add();
dataRow["Employee Name"] = oSplistItem["Employee Name"].ToString();
dataRow["Manager Name"] = oSplistItem["Manager Name"].ToString();
dataRow["Practice Name"] = oSplistItem["Practice Name"].ToString();
dataRow["Program Name"] = oSplistItem["Program Name"].ToString();
dataRow["Status"] = oSplistItem["Status"].ToString();
dataRow["Prerequisite"] = oSplistItem["Prerequisite"].ToString();
}
return dt;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Managers Approval" + ex.Message.ToString());
return dt;
}
#endregion Try2
}
Here is the code for usercontrol code:
<SharePoint:SPGridView runat="server" ID="gridViewManager" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Employee Name" HeaderText="Employee Name" />
<asp:BoundField DataField="Manager Name" HeaderText="ManagerName" />
<asp:BoundField DataField="Practice Name" HeaderText="Practice Name" />
<asp:BoundField DataField="Program Name" HeaderText="Program Name" />
<asp:BoundField DataField="Status" HeaderText="Current Status" />
<asp:BoundField DataField="Prerequisite" HeaderText="Prerequisite" />
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Button ID="BtnEdit" runat="server" Text="Take Action" />
<asp:Button ID="Button1" runat="server" Text="View Details" />
</ItemTemplate>
<HeaderTemplate>
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</SharePoint:SPGridView>
Now i am facing a proble with these two lines of code
dt.Columns.Add("Program Name", typeof(LookupField));
dt.Columns.Add("Prerequisite", typeof(String));
if i don't use this then this webpart works perfectly . but i wanted to display these fields too . how can i do this ?
Did you take a look at having the SharePoint API generate the DataTable for you using SPListItemCollection.GetDataTable()?
The problem you're having is with null values. .ToString() will fail if the object is null. I assume that all of the other fields never have any null values (at least with your queries) but the fields that you are having problems with do. You have a few options. You can just check if the value is null and put in an empty string if it's not, for many of the fields that are already strings you can just cast them, rather than .ToString-ing them. You can use Convert.ToString(object) which handles nulls. I could go on with several other options, but I think you can take it from here.