I want to extract email address from the Html String. First I extract the text from html string then pass the returning string into regular expression to search for email address.
import 'package:html/parser.dart';
import 'package:flutter/material.dart';
String _parseString(String htmlString) {
var document = parse(htmlString);
String parsedString = parse(document.body.text).documentElement.text;
return parsedString;
}
String _parseEmailString(String htmlString) {
var document = parse(htmlString);
String parsedString = parse(document.body.text).documentElement.text;
RegExp exp = new RegExp(
r"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$",
caseSensitive: false,
multiLine: false,
);
Iterable<RegExpMatch> matches = exp.allMatches('WS://127.0.0.1:56789');
print("hasMatch : " + exp.firstMatch("shahryar.rsm#gmail.com").toString());
var matches2 = "hasMatch : " + exp.stringMatch(parsedString).toString();
return matches2;
}
class HtmlToText extends StatelessWidget {
#override
Widget build(BuildContext context) {
String string =
'<p style=\"text-align: center\"><strong>The CV Club</strong> is a professional writing service that specialise in tailoring CVs, cover letters and more to your desired industry/ job role.</p>\n<p style=\"text-align: center\">The internet is full of dull CV templates, all exactly the same as each other. That’s why at <strong>The CV Club</strong>, we professionally tailor your CV to be as individual as you are and not at extortionate prices!</p>\n<p style=\"text-align: center\">We offer a FREE CV review and will give you constructive feedback on your current CV!</p>\n<p>Contact us on;</p>\n<p><strong>Website: https://www.thecvclub.org/</strong></p>\n<p><strong>Email: thecvclub#gmail.com</strong></p>\n<p><strong>Twitter: thecvclub_</strong></p>\n<p><img data-attachment-id=\"1055\" data-permalink=\"https://soleentrepreneur.co.uk/happy-world-book-day/\" data-orig-file=\"https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?fit=800%2C800&ssl=1\" data-orig-size=\"800,800\" data-comments-opened=\"1\" data-image-meta=\"{"aperture":"0","credit":"","camera":"","caption":"","created_timestamp":"0","copyright":"","focal_length":"0","iso":"0","shutter_speed":"0","title":"","orientation":"0"}\" data-image-title=\"Happy World Book Day!\" data-image-description=\"\" data-medium-file=\"https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?fit=300%2C300&ssl=1\" data-large-file=\"https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?fit=800%2C800&ssl=1\" class=\"alignnone size-medium wp-image-1055 alignleft\" src=\"https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day-300x300.png?resize=300%2C300\" alt=\"\" width=\"300\" height=\"300\" srcset=\"https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?resize=300%2C300&ssl=1 300w, https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?resize=80%2C80&ssl=1 80w, https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?resize=768%2C768&ssl=1 768w, https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?resize=36%2C36&ssl=1 36w, https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?resize=180%2C180&ssl=1 180w, https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?resize=705%2C705&ssl=1 705w, https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?resize=120%2C120&ssl=1 120w, https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?resize=450%2C450&ssl=1 450w, https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?resize=640%2C640&ssl=1 640w, https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?resize=50%2C50&ssl=1 50w, https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?w=800&ssl=1 800w\" sizes=\"(max-width: 300px) 100vw, 300px\" data-recalc-dims=\"1\" /> <img data-attachment-id=\"1056\" data-permalink=\"https://soleentrepreneur.co.uk/lets-celebrate/\" data-orig-file=\"https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?fit=800%2C800&ssl=1\" data-orig-size=\"800,800\" data-comments-opened=\"1\" data-image-meta=\"{"aperture":"0","credit":"","camera":"","caption":"","created_timestamp":"0","copyright":"","focal_length":"0","iso":"0","shutter_speed":"0","title":"","orientation":"0"}\" data-image-title=\"Let’s celebrate\" data-image-description=\"\" data-medium-file=\"https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?fit=300%2C300&ssl=1\" data-large-file=\"https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?fit=800%2C800&ssl=1\" class=\"alignnone size-medium wp-image-1056 alignleft\" src=\"https://i0.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate-300x300.png?resize=300%2C300\" alt=\"\" width=\"300\" height=\"300\" srcset=\"https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?resize=300%2C300&ssl=1 300w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?resize=80%2C80&ssl=1 80w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?resize=768%2C768&ssl=1 768w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?resize=36%2C36&ssl=1 36w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?resize=180%2C180&ssl=1 180w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?resize=705%2C705&ssl=1 705w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?resize=120%2C120&ssl=1 120w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?resize=450%2C450&ssl=1 450w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?resize=640%2C640&ssl=1 640w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?resize=50%2C50&ssl=1 50w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?w=800&ssl=1 800w\" sizes=\"(max-width: 300px) 100vw, 300px\" data-recalc-dims=\"1\" /> <img data-attachment-id=\"1059\" data-permalink=\"https://soleentrepreneur.co.uk/need-help-with-your-cv_/\" data-orig-file=\"https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?fit=800%2C800&ssl=1\" data-orig-size=\"800,800\" data-comments-opened=\"1\" data-image-meta=\"{"aperture":"0","credit":"","camera":"","caption":"","created_timestamp":"0","copyright":"","focal_length":"0","iso":"0","shutter_speed":"0","title":"","orientation":"0"}\" data-image-title=\"Need help with your CV_\" data-image-description=\"\" data-medium-file=\"https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?fit=300%2C300&ssl=1\" data-large-file=\"https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?fit=800%2C800&ssl=1\" class=\"alignnone size-medium wp-image-1059 alignleft\" src=\"https://i0.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_-300x300.png?resize=300%2C300\" alt=\"\" width=\"300\" height=\"300\" srcset=\"https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?resize=300%2C300&ssl=1 300w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?resize=80%2C80&ssl=1 80w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?resize=768%2C768&ssl=1 768w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?resize=36%2C36&ssl=1 36w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?resize=180%2C180&ssl=1 180w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?resize=705%2C705&ssl=1 705w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?resize=120%2C120&ssl=1 120w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?resize=450%2C450&ssl=1 450w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?resize=640%2C640&ssl=1 640w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?resize=50%2C50&ssl=1 50w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?w=800&ssl=1 800w\" sizes=\"(max-width: 300px) 100vw, 300px\" data-recalc-dims=\"1\" /></p>\n<p> </p>\n';
return Scaffold(
appBar: AppBar(),
body: Column(children: <Widget>[
SelectableText(
_parseString('$string'),
),
Text(_parseEmailString('$string'))
]));
}
}
Found out using wrong regex Regular Expression was
r"[a-zA-Z0-9-_.]+#[a-zA-Z0-9-_.]+"
Related
it's my first post.
I work to Quasar (Vue.js)
I have list of jobs, and in this list, i have words with special caractere.
Ex :
[ ...{ "libelle": "Agent hôtelier" },{"libelle": "Agent spécialisé / Agente spécialisée des écoles maternelles -ASEM-"},{ "libelle": "Agriculteur / Agricultrice" },{ "libelle": "Aide aux personnes âgées" },{ "libelle": "Aide de cuisine" },...]
And on "input" i would like to search "Agent spécialisé" but i want to write "agent specialise" (without special caractere) or the initial name, i want to write both and autocomplete my "input".
I just don't fin the solution for add to my filter code ...
My input :
<q-select
filled
v-model="model"
use-input
hide-selected
fill-input
input-debounce="0"
:options="options"
hint="Votre métier"
style="width: 250px; padding-bottom: 32px"
#filter="filterFn"
>
</q-select>
</div>
My code :
export default {
props: ['data'],
data() {
return {
jobList: json,
model: '',
options: [],
stringOptions: []
}
},
methods: {
jsonJobsCall(e) {
this.stringOptions = []
json.forEach(res => {
this.stringOptions.push(res.libelle)
})
},
filterFn(val, update) {
if (val === '') {
update(() => {
this.jsonJobsCall(val)
this.options = this.stringOptions
})
return
}
update(() => {
const regex = /é/i
const needle = val.toLowerCase()
this.jsonJobsCall(val)
this.options = this.stringOptions.filter(
v => v.replace(regex, 'e').toLowerCase().indexOf(needle) > -1
)
})
},
}
}
To sum up : i need filter for write with or witouth special caractere in my input for found in my list the job which can contain a special character.
I hope i was clear, ask your questions if i haven't been.
Thanks you very much.
I am not sure if its work for you but you can use regex to create valid filter for your need. For example, when there is "e" letter you want to check "e" or "é" (If I understand correctly)
//Lets say we want to match "Agent spécialisé" with the given search text
let searchText = "Agent spe";
// Lets create a character map for matching characters
let characterMap = {
e: ['e', 'é'],
a: ['a', '#']
}
// Replacing special characters with a regex part which contains all equivelant characters
// !Remember replaceAll depricated
Object.keys(characterMap).forEach((key) => {
let replaceReg = new RegExp(`${key}`, "g")
searchText = searchText.replace(replaceReg, `[${characterMap[key].join("|")}]`);
})
// Here we create a regex to match
let reg = new RegExp(searchText + ".*")
console.log("Agent spécialisé".match(reg) != null);
Another approach could be the reverse of this. You can normalize "Agent spécialisé". (I mean replace all é with normal e with a regex like above) and store in the object along with the original text. But search on this normalized string instead of original.
I want search a div for a string like "12345" and then put every matched string into a span.
But when find repetitive string, just do it for first matched several time.
Here is a jsfiddle:
function find(){
var regex = new RegExp(/12345/g),
list = $(".test").html().match(regex);
console.log(list)
for(each in list){
replacement = $(".test").html().replace(list[each], "<span class='box'>"+list[each]+"</span>");
$(".test").html(replacement);
}
}
find();
.box{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
<p>
12345 12345
</p>
</div>
Your approach is faulty: rather than extracting all matching substrings and later iterate them performing single replacements, you may use your own regex inside a String#replace method to modify the substrings "inline", "on-the-match" way:
function find(){
var regex = /12345/g;
var replacement = $(".test").html().replace(regex, "<span class='box'>$&</span>");
$(".test").html(replacement);
}
find();
.box{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
<p>
12345 12345
</p>
</div>
My solution (fiddle here), with pure JavaScript :
function find(){
var motif = "12345"
var regex = new RegExp(motif, "g")
document.querySelector("div.test").innerHTML = document.querySelector("div.test").innerHTML.replace(regex, "<span class='box'>" + motif + "</span>")
}
find()
I have a problem when using Regex. I have a html document which create an anchor link when it matches condition.
An example html:
Căn cứ Luật Tổ chức HĐND và UBND ngày 26/11/2003;
Căn cứ Nghị định số 63/2010/NĐ-CP ngày 08/6/2010 của Chính phủ về
kiểm soát thủ tục hành chính;
Căn cứ Quyết định số 165/2011/QĐ-UBND ngày 06/5/2011 của UBND tỉnh
ban hành Quy định kiểm soát thủ tục hành chính trên địa bàn tỉnh;
Căn cứ Quyết định số 278/2011/QĐ-UBND ngày 02/8/2011 của UBND tỉnh
ban hành Quy chế phối hợp thực hiện thống kê, công bố, công khai thủ
tục hành chính và tiếp nhận, xử lý phản ánh, kiến nghị của cá nhân, tổ
chức về quy định hành chính trên địa bàn tỉnh;
Xét đề nghị của Giám đốc Sở Công Thương tại Tờ trình số
304/TTr-SCT ngày 29 tháng 5 năm 2013
I want to match these bold texts and make anchor links from these. If it has, try ignore. Link example 63/2010/NĐ-CP
var matchLegals = new Regex(#"(?:[\d]+\/?)\d+\/[a-z\dA-Z_ÀÁÂÃÈÉÊÌÍÒÓÔÕÙÚĂĐĨŨƠàáâãèéêìíòóôõùúăđĩũơƯĂẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼỀỀỂưăạảấầẩẫậắằẳẵặẹẻẽềềểỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỦỨỪễệỉịọỏốồổỗộớờởỡợụủứừỬỮỰỲỴÝỶỸửữựỳỵỷỹ\-]+", RegexOptions.Compiled);
var doc = new HtmlDocument();
doc.LoadHtml(htmlString);
var allElements = doc.DocumentNode.SelectSingleNode("//div[#class='main-content']").Descendants();
foreach (var node in allElements)
{
var matches = matchLegals.Matches(node.InnerHtml);
foreach (Match m in matches)
{
var k = m.Value;
//dont know what to do
}
}
What can i do this
Many thanks.
I assume your regex pattern is OK and works. Another assumption is that node.InnerHtml doesn't contain any <a> tags already encompassing any of the potential matches.
In this case, it's as simple as doing something like this:
node.InnerHtml = Regex.Replace(node.InnerHtml, "[your pattern here]", "<a href='query=$&'>$&</a>");
...
doc.Save("output.html");
Note, that you may need to work on the href component - I'm unsure how your link should be built.
you match text and replace:
<script>
var s = '...';
var matchs = s.match(/\d{2,3}\/\d{4}\/[a-zA-Z\-áàảãạăâắằấầặẵẫậéèẻẽẹêếềểễệóòỏõọôốồổỗộơớờởỡợíìỉĩịđùúủũụưứửữựÀÁÂÃÈÉÊÌÍÒÓÔÕÙÚĂĐĨŨƠƯĂẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼÊỀỂỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỨỪỬỮỰỲỴÝỶỸửữựỵỷỹ]+/gi);
if (matchs != null) {
for(var i=0; i<matchs.length;i++){
var val = matchs[i];
s = s.replace(val, '<a href="?key=' + val + '"/>' + val + '</a>');
}
}
document.write(s);
</script>
#Shaamaan thank for your advice. After few hours of coding, it works now
var content = doc.DocumentNode.SelectSingleNode("//div[#class='main-content']");
var items = content.SelectNodes(".//text()[normalize-space(.) != '']");
foreach (HtmlNode node in items)
{
if (!matchLegals.IsMatch(node.InnerText) || node.ParentNode.Name == "a")
{
continue;
}
var texts = node.InnerHtml.Trim();
node.InnerHtml = matchLegals.Replace(texts, a => string.Format("<a href='/search?q={0}'>{0}</a>",a.Value));
}
Please help me out what expression i use in if condition to check whether the value of id is in digit or alphabet and i m using phonegap to develop a android app
In XML:-
<cat>
<id>1</id>
</cat>
<cat>
<id>30</id>
</cat>
<cat>
<id>ATTR11</id>
</cat>
<cat>
<id>ATR2</id>
</cat>
In JQuery
$.ajax({
type: "GET",
url: "one.html",
contentType: "text/xml",
dataType: "xml",
data: "",
success: function(xml){
$(xml).find("cat").each(function () {
var id = $(this).find('id').text();
if(id == ??????){
var a2 = ''+id+'';
$("#xyz").append(a2).trigger('create');
}else{
var a1 = ''+id+'';
$("#abc").append(a1).trigger('create');
}
}
});
This pattern matches only number values
var reg = new RegExp('^[0-9]+$');
You can use regular expression pattern to check if id is number or not.
var checkId = new RegExp('\d*');
\d A digit: [0-9]
d* zero or more times
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.