How to highlight page numbers in PagedDataSource to paginate Repeater - pagination

I am using PagedDataSource To Paginate Repeater and it works fine but is there a way to highlight selected page number or make it bold. I tried css, itemcommand,and click event but no luck.
Thanks in advance
Repeater:
<asp:Repeater ID="repeaterPager" runat="server" OnItemCommand="repeaterPager_ItemCommand">
<ItemTemplate>
<asp:LinkButton CssClass="sayfaNo" ID="btnPage" CommandName="Page" CommandArgument="<%#Container.DataItem %>" runat="server">
<%# Container.DataItem %></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
CodeBehind :
private void MakeleleriGetir()
{
SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings[0].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("SELECT p.PostID,p.Title,p.DateTime,p.PostShort,p.CategoryID,i.SmallFileName,c.CategoryName From Posts as p inner join Resimler as i ON p.PostID = i.PostID inner join Categories as c On p.CategoryID = c.CategoryID", cnn);
DataTable dt = new DataTable();
da.Fill(dt);
PagedDataSource pds = new PagedDataSource();
pds.DataSource = dt.DefaultView;
pds.AllowPaging = true;
pds.PageSize = 4;
pds.CurrentPageIndex = CurrentPage;
PageCount = pds.PageCount;
btnPrevious.Enabled = !pds.IsFirstPage;
btnNext.Enabled = !pds.IsLastPage;
if (pds.PageCount > 1)
{
repeaterPager.Visible = true;
ArrayList pages = new ArrayList();
for (int i = 0; i < pds.PageCount; i++)
{
{
pages.Add((i + 1).ToString());
}
}
repeaterPager.DataSource = pages;
repeaterPager.DataBind();
}
else
{
repeaterPager.Visible = false;
}
RepeaterPosts.DataSource = pds;
RepeaterPosts.DataBind();
}
protected int CurrentPage
{
get
{ // look for current page in ViewState
object o = this.ViewState["_CurrentPage"];
if (o == null)
{
return 0; // default to showing the first page
}
else
{
return (int)o;
}
}
set
{
this.ViewState["_CurrentPage"] = value;
}
}
public int PageCount
{
get
{
if (ViewState["_PageCount"] != null)
return Convert.ToInt32(ViewState["_PageCount"]);
else
return 0;
}
set
{
ViewState["_PageCount"] = value;
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
repeaterPager.ItemCommand += new RepeaterCommandEventHandler(repeaterPager_ItemCommand);
}
protected void repeaterPager_ItemCommand(object source, RepeaterCommandEventArgs e)
{
CurrentPage = Convert.ToInt32(e.CommandArgument) - 1;
MakeleleriGetir();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
MakeleleriGetir();
}
protected void btnNext_Click(object sender, EventArgs e)
{
CurrentPage += 1;
MakeleleriGetir();
}
protected void btnPrevious_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
MakeleleriGetir();
}
}
}

Logic:
Use ItemDataBound event and compare currentpage with current value of btnPage. You may use FindControl to get the current btnPage value.
Hope that helps!

protected void repeaterPager_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
//Enabled False for current selected Page index
LinkButton lnkPage = (LinkButton)e.Item.FindControl("btnPage");
if (lnkPage.CommandArgument.ToString() == (CurrentPage+1).ToString())
{
lnkPage.Enabled = false;
lnkPage.BackColor = System.Drawing.Color.FromName("#FFCC01");
}
}

Related

How to show search results with their url's in Umbraco 7

I have implemented search in Umbraco 7 using examine and user control. Search is working fine. Now I need to show the URL of the search results displayed on the lists. Is there any index property like "BodyText" which can show the URL or do I have to do some stuff in user control?
User Control code:
public static class SiteSearchResultExtensions
{
public static string FullURL(this Examine.SearchResult sr)
{
return umbraco.library.NiceUrl(sr.Id);
}
}
public partial class SiteSearchResults : System.Web.UI.UserControl
{
#region Properties
private int _pageSize = 5;
public string PageSize
{
get { return _pageSize.ToString(); }
set
{
int pageSize;
if (int.TryParse(value, out pageSize))
{
_pageSize = pageSize;
}
else
{
_pageSize = 10;
}
}
}
private string SearchTerm
{
get
{
object o = this.ViewState["SearchTerm"];
if (o == null)
return "";
else
return o.ToString();
}
set
{
this.ViewState["SearchTerm"] = value;
}
}
protected IEnumerable<Examine.SearchResult> SearchResults
{
get;
private set;
}
#endregion
#region Events
protected override void OnLoad(EventArgs e)
{
try
{
CustomValidator.ErrorMessage = "";
if (!Page.IsPostBack)
{
topDataPager.PageSize = _pageSize;
bottomDataPager.PageSize = _pageSize;
string terms = Request.QueryString["s"];
if (!string.IsNullOrEmpty(terms))
{
SearchTerm = terms;
PerformSearch(terms);
}
}
base.OnLoad(e);
}
catch (Exception ex)
{
CustomValidator.IsValid = false;
CustomValidator.ErrorMessage += Environment.NewLine + ex.Message;
}
}
protected void searchResultsListView_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
try
{
if (SearchTerm != "")
{
topDataPager.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
bottomDataPager.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
PerformSearch(SearchTerm);
}
}
catch (Exception ex)
{
CustomValidator.IsValid = false;
CustomValidator.ErrorMessage += Environment.NewLine + ex.Message;
}
}
#endregion
#region Methods
private void PerformSearch(string searchTerm)
{
if (string.IsNullOrEmpty(searchTerm)) return;
var criteria = ExamineManager.Instance
.SearchProviderCollection["ExternalSearcher"]
.CreateSearchCriteria(UmbracoExamine.IndexTypes.Content);
// Find pages that contain our search text in either their nodeName or bodyText fields...
// but exclude any pages that have been hidden.
//var filter = criteria
// .GroupedOr(new string[] { "nodeName", "bodyText" }, searchTerm)
// .Not()
// .Field("umbracoNaviHide", "1")
// .Compile();
Examine.SearchCriteria.IBooleanOperation filter = null;
var searchKeywords = searchTerm.Split(' ');
int i = 0;
for (i = 0; i < searchKeywords.Length; i++)
{
if (filter == null)
{
filter = criteria.GroupedOr(new string[] { "nodeName", "bodyText", "browserTitle", "tags", "mediaTags" }, searchKeywords[i]);
}
else
{
filter = filter.Or().GroupedOr(new string[] { "nodeName", "bodyText", "browserTitle", "tags", "mediaTags" }, searchKeywords[i]);
}
}
//SearchResults = ExamineManager.Instance
// .SearchProviderCollection["ExternalSearcher"]
// .Search(filter);
SearchResults = ExamineManager.Instance.SearchProviderCollection["ExternalSearcher"].Search(filter.Compile());
if (SearchResults.Count() > 0)
{
searchResultsListView.DataSource = SearchResults.ToArray();
searchResultsListView.DataBind();
searchResultsListView.Visible = true;
bottomDataPager.Visible = topDataPager.Visible = (SearchResults.Count() > _pageSize);
}
summaryLiteral.Text = "<p>Your search for <b>" + searchTerm + "</b> returned <b>" + SearchResults.Count().ToString() + "</b> result(s)</p>";
// Output the query which an be useful for debugging.
queryLiteral.Text = criteria.ToString();
}
#endregion
}
}
I have done my Examine settings like this:
ExamineIndex.Config
<IndexSet SetName="ExternalndexSet" IndexPath="~/App_Data/TEMP/ExamineIndexes/ExternalIndex/">
<IndexAttributeFields>
<add Name="id"/>
<add Name="nodeName"/>
<add Name="nodeTypeAlias"/>
<add Name="parentID" />
</IndexAttributeFields>
<IndexUserFields>
<add Name="bodyText"/>
<add Name="umbracoNaviHide"/>
</IndexUserFields>
<IncludeNodeTypes/>
<ExcludeNodeTypes/>
</IndexSet>
ExamineSettings.Config
ExamineIndexProviders
<add name="ExternalIndexer" type="UmbracoExamine.UmbracoContentIndexer, UmbracoExamine"
runAsync="true"
supportUnpublished="true"
supportProtected="true"
interval="10"
analyzer="Lucene.Net.Analysis.WhitespaceAnalyzer, Lucene.Net"
indexSet="DemoIndexSet"
/>
ExamineSearchProvide
<add name="ExternalSearcher" type="UmbracoExamine.UmbracoExamineSearcher, UmbracoExamine"
analyzer="Lucene.Net.Analysis.WhitespaceAnalyzer, Lucene.Net"
indexSet="DemoIndexSet"
/>
It was quite simple and i done some editing in the Usercontrol(SiteSearchresult.ascx)
like this
<li>
<a href="<%# ((Examine.SearchResult)Container.DataItem).FullURL() %>">
<%# ((Examine.SearchResult)Container.DataItem).Fields["nodeName"] %>
<br >
addingvalue.webdevstaging.co.uk<%# ((Examine.SearchResult)Container.DataItem).FullURL() %>
</a>
<p><%# ((Examine.SearchResult)Container.DataItem).Fields.ContainsKey("bodyText") == true ? ((Examine.SearchResult)Container.DataItem).Fields["bodyText"] : ""%></p>
</li>

Some trouble with ComboBox in Ext.net

I have a Page which a FormPanel(there's a ComboBox in it) and a TreePanel(has a default root node) in it and open ViewState.
I set a value to ComboBox in GET.
When i GET the page the TreePanel's Store send a POST request(store read) before FormPane rendered in client,in this POST request the fromdata has no info about FormPane.
in the POST request recover the ComboBox.Value from ViewState,but in ComboBoxBase.LoadPostData() Ext.Net get value from formdata and cover ComboBox.Value without precondition
it's ComboBoxBase.LoadPostData() code
protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
this.HasLoadPostData = true;
string text = postCollection[this.UniqueName];
string state = postCollection[this.ValueHiddenName.IsNotEmpty() ? this.ValueHiddenName : ("_" + this.UniqueName + "_state")];
this.SuspendScripting();
this.RawValue = text;
this.Value = text;
this.ResumeScripting();
if (state == null && text == null)
{
return false;
}
if (!this.EmptyText.Equals(text) && text.IsNotEmpty())
{
List<ListItem> items = null;
if (this.SimpleSubmit)
{
var array = state.Split(new char[] { ',' });
items = new List<ListItem>(array.Length);
foreach (var item in array)
{
items.Add(new ListItem(item));
}
}
else if(state.IsNotEmpty())
{
items = ComboBoxBase.ParseSelectedItems(state);
}
bool fireEvent = false;
if (items == null)
{
items = new List<ListItem>
{
new ListItem(text)
};
/*fireEvent = this.SelectedItems.Count > 0;
this.SelectedItems.Clear();
return fireEvent;
*/
}
foreach (var item in items)
{
if (!this.SelectedItems.Contains(item))
{
fireEvent = true;
break;
}
}
this.SelectedItems.Clear();
this.SelectedItems.AddRange(items);
return fireEvent;
}
else
{
if (this.EmptyText.Equals(text) && this.SelectedItems.Count > 0)
{
this.SelectedItems.Clear();
return true;
}
}
return false;
}
Look at Line 5 to 11,why not change like this
string text = postCollection[this.UniqueName];
string state = postCollection[this.ValueHiddenName.IsNotEmpty() ? this.ValueHiddenName : ("_" + this.UniqueName + "_state")];
this.SuspendScripting();
this.RawValue = text;
this.ResumeScripting();
if (state == null && text == null)
{
return false;
}
this.SuspendScripting();
this.Value = text;
this.ResumeScripting();
Sample for this question
page file
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<ext:ResourceManager ID="ResourceManager1" runat="server" DisableViewState="false"
AjaxViewStateMode="Enabled" ViewStateMode="Enabled"/>
<form id="form1" runat="server">
<ext:Viewport runat="server" ID="VP">
</ext:Viewport>
</form>
</body>
</html>
cs file
public partial class WebFormTest : System.Web.UI.Page
{
protected override void OnInitComplete(EventArgs e)
{
FP = new FormPanel();
FP.ID = "FP";
FP.Title = "FP";
FP.Region = Region.Center;
TF = new TextField();
TF.ID = "TF";
TF.FieldLabel = "TF";
CB = new ComboBox();
CB.ID = "CB";
CB.FieldLabel = "CB";
CB.Items.Clear();
CB.Items.Add(new ListItem("one", "1"));
CB.Items.Add(new ListItem("two", "2"));
Button test = new Button() { ID = "testbtn", Text = "test" };
test.Listeners.Click.Handler = "App.Store2.load()";
FP.TopBar.Add(new Toolbar() { Items = { test } });
FP.Items.Add(TF);
FP.Items.Add(CB);
GP = new GridPanel();
GP.ID = "GP";
GP.Title = "GP";
GP.Region = Region.East;
GP.Listeners.BeforeRender.Handler = "App.Store1.reload()";
BTN = new Button();
BTN.ID = "BTN";
BTN.Text = "click";
BTN.Icon = Icon.ArrowJoin;
BTN.DirectEvents.Click.Event += new ComponentDirectEvent.DirectEventHandler(Click);
TB = new Toolbar();
TB.Items.Add(BTN);
GP.TopBar.Add(TB);
Store1 = new Store();
Store1.ID = "Store1";
Store1.ReadData += new Store.AjaxReadDataEventHandler(WebFormTest_ReadData);
Model1 = new Model();
Model1.ID = "Model1";
Store1.Model.Add(Model1);
GP.Store.Add(Store1);
TP = new TreePanel();
TP.ID = "TP";
TP.Title = "TP";
TP.Region = Region.East;
TP.RootVisible = false;
TP.Root.Add(new Node() { NodeID = "test", Text = "test" });
Store2 = new TreeStore();
Store2.ID = "Store2";
Store2.ReadData += new TreeStoreBase.ReadDataEventHandler(Store2_ReadData);
TP.Store.Add(Store2);
VP.Items.Add(FP);
//VP.Items.Add(GP);
VP.Items.Add(TP);
if (!X.IsAjaxRequest)
{
CB.Value = "2";
TF.Value = "TEXT";
}
base.OnInitComplete(e);
}
FormPanel FP;
TextField TF;
ComboBox CB;
GridPanel GP;
Button BTN;
Toolbar TB;
Store Store1;
Model Model1;
TreePanel TP;
TreeStore Store2;
protected override void CreateChildControls()
{
base.CreateChildControls();
}
void Store2_ReadData(object sender, NodeLoadEventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
//if (!X.IsAjaxRequest)
//{
// this.Store1.DataSource = this.Data;
// this.Store1.DataBind();
//}
}
protected void Refresh(object sender, DirectEventArgs e)
{
}
bool flag = false;
protected void Click(object sender, DirectEventArgs e)
{
GP.GetStore().Reload();
flag = true;
}
protected override void OnPreRender(EventArgs e)
{
if (flag)
{
TF.Value = "asdasd";
}
base.OnPreRender(e);
}
protected void WebFormTest_ReadData(object sender, StoreReadDataEventArgs e)
{
}
private object[] Data
{
get
{
return new object[]
{
new object[] { "3m Co", 71.72, 0.02, 0.03, "9/1 12:00am" },
};
}
}
}
you also can discuss in Ext.net Forums
We committed the change to the SVN trunk. It will go to the next release (v2.3).
The change is similar to your one, but we decided not to change RawValue as well. Thank you for the report and suggested fix.
Fix (ComboBoxBase LoadPostData)
protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
this.HasLoadPostData = true;
string text = postCollection[this.UniqueName];
string state = postCollection[this.ValueHiddenName.IsNotEmpty() ? this.ValueHiddenName : ("_" + this.UniqueName + "_state")];
if (state == null && text == null)
{
return false;
}
this.SuspendScripting();
this.RawValue = text;
this.Value = text;
this.ResumeScripting();

Blackberry - How if addElement() doesn't work?

I am a newbie of Blackberry developing application. I try to store all xml parsing data to an object, and set them to a vector.
public class XmlParser extends MainScreen {
Database d;
private HttpConnection hcon = null;
private Vector binN;
public Vector getBinN() {
return binN;
}
public void setBinN(Vector bin) {
this.binN = bin;
}
LabelField from;
LabelField ttl;
LabelField desc;
LabelField date;
public XmlParser() {
LabelField title = new LabelField("Headline News" ,LabelField.HCENTER|LabelField.USE_ALL_WIDTH);
setTitle(title);
try {
URI myURI = URI.create("file:///SDCard/Database/WebFeed.db");
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement("SELECT feed_url, feed_name FROM WebFeed");
st.prepare();
Cursor c = st.getCursor();
while (c.next()) {
Row r = c.getRow();
hcon = (HttpConnection)Connector.open(r.getString(0));
hcon.setRequestMethod(HttpConnection.GET);
hcon.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
hcon.setRequestProperty("Content-Length", "0");
hcon.setRequestProperty("Connection", "close");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.isValidating();
Document document = builder.parse(hcon.openInputStream());
Element rootElement = document.getDocumentElement();
rootElement.normalize();
NodeList list = document.getElementsByTagName("item");
int i=0;
while (i<10){
Node item = list.item(i);
if(item.getNodeType() != Node.TEXT_NODE) {
NodeList itemChilds = item.getChildNodes();
int j=0;
while (j<10){
Node detailNode = itemChilds.item(j);
if(detailNode.getNodeType() != Node.TEXT_NODE) {
if(detailNode.getNodeName().equalsIgnoreCase("title")) {
ttl = new LabelField(getNodeValue(detailNode)) {
public void paint(Graphics g) {
g.setColor(Color.BLUE);
super.paint(g);
}
};
from = new LabelField(r.getString(1), LabelField.FIELD_RIGHT|LabelField.USE_ALL_WIDTH);
ttl.setFont(Font.getDefault().derive(Font.BOLD));
from.setFont(Font.getDefault().derive(Font.BOLD));
add (from);
add (ttl);
} else if(detailNode.getNodeName().equalsIgnoreCase("description")) {
desc = new LabelField(getNodeValue(detailNode), 0, 70, USE_ALL_WIDTH);
add(desc);
} else if(detailNode.getNodeName().equalsIgnoreCase("dc:date")) {
date = new LabelField(getNodeValue(detailNode), 11, 5, USE_ALL_WIDTH) {
public void paint(Graphics g) {
g.setColor(Color.ORANGE);
super.paint(g);
}
};
add(date);
add(new SeparatorField());
} else if(detailNode.getNodeName().equalsIgnoreCase("pubDate")) {
date = new LabelField(getNodeValue(detailNode), 0, 22, USE_ALL_WIDTH) {
public void paint(Graphics g) {
g.setColor(Color.ORANGE);
super.paint(g);
}
};
add(date);
add(new SeparatorField());
} else {
System.out.println("not the node");
}
} else {
System.out.println("not text node");
}
j++;
}
}
i++;
BinNews bin = new BinNews();
bin.setProv(from.getText());
bin.setTitle(ttl.getText());
bin.setDesc(desc.getText());
bin.setDate(date.getText());
binN.addElement(bin);
}
setBinN(binN);
}
//setBinN(binN);
st.close();
d.close();
} catch (Exception e) {
add (new LabelField(e.toString(),LabelField.HCENTER|LabelField.USE_ALL_WIDTH));
System.out.println(e.toString());
}
}
public String getNodeValue(Node node) {
NodeList nodeList = node.getChildNodes();
Node childNode = nodeList.item(0);
return childNode.getNodeValue();
}
}
I try to store all data from an object called BinNews, to a vector called binN. But when I do debugging, I found that BinN has null value, because "binN.addElement(bin)" doesn't work.
Please advise.
First, you don't actually call setBinN until after the while(i < 10) loop completes. So when you say binN.addElement(bin) then binN will be null.
However your setBinN(binN) call doesn't make sense because you're passing in binN and then setting it to itself which isn't going to do anything.
What you can do is have binN = new Vector(); at the top of the constructor and then it won't be null later on. I don't think the setBinN call will be necessary later on if you're adding the BinNews objects straight to binN.

How to sort search dictionary result based on frequency in j2me

This is my dictionary format:
word Frequency
Gone 60
Goes 10
Go 30
So far the system returns words eg starting with 'g' as go30, goes10, gone60 as a list.
(alphabetically). I want to increase the accuracy of the system so that the search result is based on frequency. Words with high frequencies appear first. kindly help.
Here is the Text midlet class that reads the dictionary line by line.
public class Text extends MIDlet {
// Fields
private static final String[] DEFAULT_KEY_CODES = {
// 1
".,?!'\"1-()#/:_",
// 2
"ABC2",
// 3
"DEF3",
// 4
"GHI4",
// 5
"JKL5",
// 6
"MNO6",
// 7
"PQRS7",
// 8
"TUV8",
// 9
"WXYZ9",
};
//Initializing inner Classes
public ComposeText() {
cmdHandler = new CommandHandler();
lineVector = new Vector();
}
//Calling All InitMethods, setting Theme, Show MainForm
public void startApp() {
Display.init(this);
setTheme();
initCmd();
initMainGui();
mainFrm.show();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
//Initializing all the Commands
public void initCmd() {
exitCmd = new Command("Exit");
selectCmd = new Command("Ok");
cancelCmd = new Command("Cancel");
predCmd = new Command("Prediction");
sendCmd = new Command("Send");
tfPredArea = new TextField();
//check dictionary
try {
readFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
//Initiating MainScreen
public void initMainGui() {
mainFrm = new Form("Compose Text");
mainFrm.setLayout(new BorderLayout());
mainFrm.setLayout(new CoordinateLayout(150, 150));
mainFrm.addCommand(exitCmd);
mainFrm.addCommand(predCmd);
mainFrm.addCommand(sendCmd);
mainFrm.addCommandListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == predCmd){
initPredGui();
} else if(ae.getSource() == exitCmd){
destroyApp(true);
notifyDestroyed();
}
}
});
// To : 07xxxxxxxxxx
Dimension d1 = new Dimension(130, 20);
lbTo = new Label("To:");
lbTo.setX(10);
lbTo.setY(10);
tfTo = new TextField();
tfTo.setReplaceMenu(false);
tfTo.setConstraint(TextField.NUMERIC);
tfTo.setInputModeOrder(new String[]{"123"});
tfTo.setMaxSize(13);
tfTo.setX(40);
tfTo.setY(10);
tfTo.setPreferredSize(d1);
//Message : Compose Text
Dimension d2 = new Dimension(135, 135);
lbSms = new Label("Message:");
lbSms.setX(5);
lbSms.setY(40);
tfSms = new TextField();
tfSms.setReplaceMenu(false);
tfSms.setX(40);
tfSms.setY(40);
tfSms.setPreferredSize(d2);
//add stuff
mainFrm.addComponent(lbTo);
mainFrm.addComponent(lbSms);
mainFrm.addComponent(tfTo);
mainFrm.addComponent(tfSms);
}
//Initiating FilterSelection Screen
public void initPredGui() {
predForm = new Form("Prediction on");
predForm.setLayout(new CoordinateLayout(150, 150));
predForm.addCommand(cancelCmd);
predForm.addCommand(selectCmd);
//textfied in prediction form
final Dimension d5 = new Dimension(200, 200);
tfPredArea = new TextField();
tfPredArea.setReplaceMenu(false);
tfPredArea.setX(10);
tfPredArea.setY(10);
tfPredArea.setPreferredSize(d5);
predForm.addComponent(tfPredArea);
final ListModel underlyingModel = new DefaultListModel(lineVector);
// final ListModel underlyingModel = new
DefaultListModel(tree.getAllPrefixMatches(avail));
// this is a list model that can narrow down the underlying model
final SortListModel proxyModel = new SortListModel(underlyingModel);
final List suggestion = new List(proxyModel);
tfPredArea.addDataChangeListener(new DataChangedListener() {
public void dataChanged(int type, int index) {
int len = 0;
int i = 0;
String input = tfPredArea.getText();
len = tfPredArea.getText().length();
//ensure start search character is set for each word
if (!(len == 0)) {
for (i = 0; i < len; i++) {
if (input.charAt(i) == ' ') {
k = i;
}
}
String currentInput = input.substring(k + 1, len);
proxyModel.filter(currentInput);
}
}
});
Dimension d3 = new Dimension(110, 120);
suggestion.setX(80);
suggestion.setY(80);
suggestion.setPreferredSize(d3);
predForm.addComponent(suggestion);
suggestion.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String string = suggestion.getSelectedItem().toString();
if (tfPredArea.getText().charAt(0) == 0) {
tfPredArea.setText(string);
}
else if (tfPredArea.getText().length() == 0) {
tfPredArea.setText(string);
} else {
tfPredArea.setText(tfPredArea.getText() + string);
}
}
});
predForm.addCommandListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == addCmd) {
newDictionaryFrm.show();
} else {
mainFrm.show();
}
}
});
predForm.show();
}
//Setting Theme for All Forms
public void setTheme() {
try {
Resources r = Resources.open("/theme.res");
UIManager.getInstance().setThemeProps(r.getTheme(
r.getThemeResourceNames()[0]));
} catch (java.io.IOException e) {
System.err.println("Couldn't load the theme");
}
}
//Inner class CommandHandler
public class CommandHandler implements ActionListener {
public void actionPerformed(ActionEvent ae) {
//cancelCommand from predictionForm
if (ae.getSource() == cancelCmd) {
if (edit) {
mainFrm.show();
// clearFields();
} else if (ae.getSource() == selectCmd){
tfPredList.addDataChangeListener(model);
predForm.show();
}
else{}
}
}
}
// method that reads dictionary line by line
public void readFile() throws IOException {
tree = new Trie();
InputStreamReader reader = new InputStreamReader(
getClass().getResourceAsStream("/Maa Corpus.txt-01-ngrams-Alpha.txt"));
String line = null;
// Read a single line from the file. null represents the EOF.
while ((line = readLine(reader)) != null) {
// Append to a vector to be used as a list
lineVector.addElement(line);
}
}
public String readLine(InputStreamReader reader) throws IOException {
// Test whether the end of file has been reached. If so, return null.
int readChar = reader.read();
if (readChar == -1) {
return null;
}
StringBuffer string = new StringBuffer("");
// Read until end of file or new line
while (readChar != -1 && readChar != '\n') {
// Append the read character to the string.
// This is part of the newline character
if (readChar != '\r') {
string.append((char) readChar);
}
// Read the next character
readChar = reader.read();
}
return string.toString();
}
}
}
The SortListModel Class has a filter method that gets prefix from the textfield datachangeLister
class SortListModel implements ListModel, DataChangedListener {
private ListModel underlying;
private Vector filter;
private Vector listeners = new Vector();
public SortListModel(ListModel underlying) {
this.underlying = underlying;
underlying.addDataChangedListener(this);
}
private int getFilterOffset(int index) {
if(filter == null) {
return index;
}
if(filter.size() > index) {
return ((Integer)filter.elementAt(index)).intValue();
}
return -1;
}
private int getUnderlyingOffset(int index) {
if(filter == null) {
return index;
}
return filter.indexOf(new Integer(index));
}
public void filter(String str) {
filter = new Vector();
str = str.toUpperCase();
for(int iter = 0 ; iter < underlying.getSize() ; iter++) {
String element = (String)underlying.getItemAt(iter);
if(element.toUpperCase().startsWith(str)) // suggest only if smthing
{
filter.addElement(new Integer(iter));
}
}
dataChanged(DataChangedListener.CHANGED, -1);
}
public Object getItemAt(int index) {
return underlying.getItemAt(getFilterOffset(index));
}
public int getSize() {
if(filter == null) {
return underlying.getSize();
}
return filter.size();
}
public int getSelectedIndex() {
return Math.max(0, getUnderlyingOffset(underlying.getSelectedIndex()));
}
public void setSelectedIndex(int index) {
underlying.setSelectedIndex(getFilterOffset(index));
}
public void addDataChangedListener(DataChangedListener l) {
listeners.addElement(l);
}
public void removeDataChangedListener(DataChangedListener l) {
listeners.removeElement(l);
}
public void addSelectionListener(SelectionListener l) {
underlying.addSelectionListener(l);
}
public void removeSelectionListener(SelectionListener l) {
underlying.removeSelectionListener(l);
}
public void addItem(Object item) {
underlying.addItem(item);
}
public void removeItem(int index) {
underlying.removeItem(index);
}
public void dataChanged(int type, int index) {
if(index > -1) {
index = getUnderlyingOffset(index);
if(index < 0) {
return;
}
}
for(int iter = 0 ; iter < listeners.size() ; iter++) {
((DataChangedListener)listeners.elementAt(iter)).dataChanged(type, index);
}
}
}

Sharepoint 2010 custom webpart paging

I am trying to implement simple paging on my sharepoint webpart. I have a single news articles list which has some simple columns. I want to be able to have then five on a page and with some numerical paging at the bottom. I have gone through the net trying to understand splistitemcollectionposition but with no luck. If anyone can help please can you give me a simple code example or some guidanc
Many thanks
Chris
I would suggest using SPDataSource and a SPGridView, together they will implement paging and many other cool features with minimal or no code.
Use this a a guide for some of the classes/methods/properties you might need to use to get paging to work. Be aware that this code does not compile, i have just pulled together various code snippets that i have in my own list results framework, which includes paging, sorting, grouping and caching. It should be enough to get you started though.
public class PagedListResults : System.Web.UI.WebControls.WebParts.WebPart {
protected SPPagedGridView oGrid;
protected override void CreateChildControls() {
this.oGrid = new SPPagedGridView();
oGrid.AllowPaging = true;
oGrid.PageIndexChanging += new GridViewPageEventHandler(oGrid_PageIndexChanging);
oGrid.PagerTemplate = null; // Must be called after Controls.Add(oGrid)
oGrid.PagerSettings.Mode = PagerButtons.NumericFirstLast;
oGrid.PagerSettings.PageButtonCount = 3;
oGrid.PagerSettings.Position = PagerPosition.TopAndBottom;
base.CreateChildControls();
}
public override void DataBind() {
base.DataBind();
SPQuery q = new SPQuery();
q.RowLimit = (uint)info.PageSize;
if (!string.IsNullOrEmpty(info.PagingInfoData)) {
SPListItemCollectionPosition pos = new SPListItemCollectionPosition(info.PagingInfoData);
q.ListItemCollectionPosition = pos;
} else {
//1st page, dont need a position, and using a position breaks things
}
q.Query = info.Caml;
SPListItemCollection items = SPContext.Current.List.GetItems(q);
FilterInfo info = null;
string tmp = "<View></View>";
tmp = tmp.Replace("<View><Query>", string.Empty);
tmp = tmp.Replace("</Query></View>", string.Empty);
info.Caml = tmp;
info.PagingInfoData = string.Empty;
info.CurrentPage = oGrid.CurrentPageIndex;
info.PageSize = oGrid.PageSize;
if (oGrid.PageIndex == 0 || oGrid.CurrentPageIndex == 0) {
//do nothing
} else {
StringBuilder value = new StringBuilder();
value.Append("Paged=TRUE");
value.AppendFormat("&p_ID={0}", ViewState[KEY_PagingPrefix + "ID:" + oGrid.PageIndex]);
info.PagingInfoData = value.ToString();
}
int pagecount = (int)Math.Ceiling(items.Count / (double)oGrid.PageSize);
for (int i = 1; i < pagecount; i++) { //not always ascending index numbers
ResultItem item = items[(i * oGrid.PageSize) - 1];
ViewState[KEY_PagingPrefix + "ID:" + i] = item.ID;
}
oGrid.VirtualCount = items.Count;
DateTime time3 = DateTime.Now;
DataTable table = new DataTable("Data");
DataBindListData(table, items);
this.oGrid.DataSource = table;
this.oGrid.DataBind();
this.oGrid.PageIndex = oGrid.CurrentPageIndex; //need to reset this after DataBind
}
void oGrid_PageIndexChanging(object sender, GridViewPageEventArgs e) {
oGrid.PageIndex = e.NewPageIndex;
oGrid.CurrentPageIndex = oGrid.PageIndex;
}
}
public class FilterInfo {
public string Caml;
public string PagingInfoData;
public int CurrentPage;
public int PageSize;
}
public class SPPagedGridView : SPGridView {
protected override void InitializePager(GridViewRow row, int columnSpan, PagedDataSource pagedDataSource) {
pagedDataSource.AllowCustomPaging = true;
pagedDataSource.VirtualCount = virtualcount;
pagedDataSource.CurrentPageIndex = currentpageindex;
base.InitializePager(row, columnSpan, pagedDataSource);
}
private int virtualcount = 0;
public int VirtualCount {
get { return virtualcount; }
set { virtualcount = value; }
}
private int currentpageindex = 0;
public int CurrentPageIndex {
get { return currentpageindex; }
set { currentpageindex = value; }
}
}
check out my post on how to page using SPListItemCollectionPosition, I did a component to page over lists, maybe it can help -> http://hveiras.wordpress.com/2011/11/07/listpagert-using-splistitemcollectionposition/

Resources