how to over come System out memory exception in windows phone 8? - xaml

I'm Developing windows phone 8 application.
In my application i'm using listbox.I bind listbox value form Webservice. Webservice return json format data's.
The webservice return 40 to 50 records.I bind all the values into listbox.
Everthing work fine.Only on first time run.
For example:-
My project page structure.
1.welcomepage
2.Menu Page (it contain six buttons. click on any one particular button it's redirect to sub-menupage)
3.Sub-menupage(Six different page present)
In menu page Hotels button is present . if hotels button is clicked it's navigate to Hotels Page.
Now my problem is:-
First Time - welcomepage -> Menu Page -> HotelSubmenu [List of hotels is bind in listbox from webservice]
Now I goback to Menupage by click on hardwareback button.Now it's in Menu page
If i click again the same Hotels button
It show me the error
e.ExceptionObject {system.OutofMemoryException:Insufficient memory to continue the execution of the program.
[System.outofmemoryException]
Data {system.Collections.ListDictionaryInternal}
HelpLink null
Hresult -2147024882
Message "insufficient memory to continue the execution of the program"
My C# code for bind values in listbox
public void commonbind()
{
try
{
this.loadimg.Visibility = System.Windows.Visibility.Visible;
loadcheck();
string common_url = "http://xxxxxx.com/Service/bussinesscitynamesub.php?bcatid=" + businessid + "&cityname=" + cityname + "&bsubid=" + filterid;
WebClient common_wc = new WebClient();
common_wc.DownloadStringAsync(new Uri(common_url), UriKind.Relative);
common_wc.DownloadStringCompleted += common_wc_DownloadStringCompleted;
}
catch (Exception ex)
{
}
}
void common_wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
lbbusiness.Items.Clear();
var common_val = e.Result;
if (common_val != "null\n\n\n\n")
{
lbopen = 2;
var jsonconvertvalue = JsonConvert.DeserializeObject<List<common_bindclass>>(common_val);
List<common_bindclass> ls = new List<common_bindclass>();
ls = jsonconvertvalue;
for (int i = 0; i < ls.Count; i++)
{
lbbusiness.Items.Add(ls[i]);
}
this.loadimg.Visibility = System.Windows.Visibility.Collapsed;
loadcheck();
}
else
{
if (lbopen == 0)
{
MessageBoxResult resultmsg = MessageBox.Show("No Result present based on your current Location! " + System.Environment.NewLine + "Now showing result without Location based", "Sorry!", MessageBoxButton.OK);
if (resultmsg == MessageBoxResult.OK)
{
lbbusiness.Items.Clear();
cityname = "";
**commonbind();**
}
else
{
NavigationService.GoBack();
}
}
else if (lbopen == 1)
{
MessageBox.Show("No Result Present In this Categories");
LPfilter.Open();
}
else if (lbopen == 2)
{
MessageBox.Show("No Result Present In this City");
Lpcity.Open();
}
}
}
catch (Exception ex)
{
}
}
I try with following method for solve the memory exception
Try1:-
Clear the List box value before bind every time.
Try2:-
Create the new list every time
common_bindclass bind = new common_bindclass();
foreach (common_bindclass bind in jsonconvertvalue)
{
lbbusiness.Items.Add(bind);
}
I change the above code to
List<common_bindclass> ls = new List<common_bindclass>();
ls = jsonconvertvalue;
for (int i = 0; i < ls.Count; i++)
{
lbbusiness.Items.Add(ls[i]);
}
MY Output For single List
But my try's not help for me .
any one tell me how to solve it. or alternate way .
How to find in which line the error occur .[I try with break point but it's not help me]

Related

How to avoid to fetch a list of followers of the same Twitter user that was displayed before

I'm very new at coding and I'm having some issues. I'd like to display the followers of followers of ..... of followers of some specific users in Twitter. I have coded this and I can set a limit for the depth. But, while running the code with a small sample, I saw that I run into the same users again and my code re-display the followers of these users. How can I avoid this and skip to the next user? You can find my code below:
By the way, while running my code, I encounter with a 401 error. In the list I'm working on, there's a private user, and when my code catches that user, it stops. Additionally, how can I deal with this issue? I'd like to skip such users and prevent my code to stop.
Thank you for your help in advance!
PS: I know that I'll encounter with a 429 error working with a large sample. After fixing these issues, I'm planning to review relevant discussions to deal with.
public class mainJava {
public static Twitter twitter = buildConfiguration.getTwitter();
public static void main(String[] args) throws Exception {
ArrayList<String> rootUserIDs = new ArrayList<String>();
Scanner s = new Scanner(new File("C:\\Users\\ecemb\\Desktop\\rootusers1.txt"));
while (s.hasNextLine()) {
rootUserIDs.add(s.nextLine());
}
s.close();
for (String rootUserID : rootUserIDs) {
User rootUser = twitter.showUser(rootUserID);
List<User> userList = getFollowers(rootUser, 0);
}
}
public static List<User> getFollowers(User parent, int depth) throws Exception {
List<User> userList = new ArrayList<User>();
if (depth == 2) {
return userList;
}
IDs followerIDs = twitter.getFollowersIDs(parent.getScreenName(), -1);
long[] ids = followerIDs.getIDs();
for (long id : ids) {
twitter4j.User child = twitter.showUser(id);
userList.add(child);
getFollowers(child, depth + 1);
System.out.println(depth + "th user: " + parent.getScreenName() + " Follower: " + child.getScreenName());
}
return userList;
}
}
I guess graph search algorithms can be implemented for this particular issue. I chose Breadth First Search algorithm because visiting root user's followers at first would be better. You can check this link to additional information about algorithm.
Here is my implementation for your problem:
public List<User> getFollowers(User parent, int startDepth, int finalDepth) {
List<User> userList = new ArrayList<User>();
Queue<Long> queue = new LinkedList<Long>();
HashMap<Long, Integer> discoveredUserId = new HashMap<Long, Integer>();
try {
queue.add(parent.getId());
discoveredUserId.put(parent.getId(), 0);
while (!queue.isEmpty()) {
long userId = queue.remove();
int discoveredDepth = discoveredUserId.get(userId);
if (discoveredDepth == finalDepth) {
continue;
}
User user = twitter.showUser(userId);
handleRateLimit(user.getRateLimitStatus());
if (user.isProtected()) {
System.out.println(user.getScreenName() + "'s account is protected. Can't access followers.");
continue;
}
IDs followerIDs = null;
followerIDs = twitter.getFollowersIDs(user.getScreenName(), -1);
handleRateLimit(followerIDs.getRateLimitStatus());
long[] ids = followerIDs.getIDs();
for (int i = 0; i < ids.length; i++) {
if (!discoveredUserId.containsKey(ids[i])) {
discoveredUserId.put(ids[i], discoveredDepth + 1);
User child = twitter.showUser(ids[i]);
handleRateLimit(child.getRateLimitStatus());
userList.add(child);
if (discoveredDepth >= startDepth && discoveredDepth < finalDepth) {
System.out.println(discoveredDepth + ". user: " + user.getScreenName() + " has " + user.getFollowersCount() + " follower(s) " + (i + 1) + ". Follower: " + child.getScreenName());
}
queue.add(ids[i]);
} else {//prints to console but does not check followers. Just for data consistency
User child = twitter.showUser(ids[i]);
handleRateLimit(child.getRateLimitStatus());
if (discoveredDepth >= startDepth && discoveredDepth < finalDepth) {
System.out.println(discoveredDepth + ". user: " + user.getScreenName() + " has " + user.getFollowersCount() + " follower(s) " + (i + 1) + ". Follower: " + child.getScreenName());
}
}
}
}
} catch (TwitterException e) {
e.printStackTrace();
}
return userList;
}
//There definitely are more methods for handling rate limits but this worked for me well
private void handleRateLimit(RateLimitStatus rateLimitStatus) {
//throws NPE here sometimes so I guess it is because rateLimitStatus can be null and add this conditional expression
if (rateLimitStatus != null) {
int remaining = rateLimitStatus.getRemaining();
int resetTime = rateLimitStatus.getSecondsUntilReset();
int sleep = 0;
if (remaining == 0) {
sleep = resetTime + 1; //adding 1 more second
} else {
sleep = (resetTime / remaining) + 1; //adding 1 more second
}
try {
Thread.sleep(sleep * 1000 > 0 ? sleep * 1000 : 0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
in this code HashMap<Long, Integer> discoveredUserId is used to prevent program checking same users repeatedly and storing in which depth we faced with this user.
and for private users, there is isProtected() method in twitter4j library.
Hope this implementation helps.

Sales force EMP connector, stops receiving notification after some time

I am performing a POC to check Streaming API stability, POC is as follows
Program 1 : subscribe to pushtopic created against Account object
Program 2 : create, update & delete single record after every 10 min interval
Both this programs were kept running for more than 12 hours (left overnight), after that I verified if all notification are received or not and found that after sometime (in this case it was nearly ~ 2 hours 45 min ) no notification were received, I repeated this twice and both case it stops getting notification after sometime.
Test code used
Streaming API client (using EMP connector)
public class SFPoc {
static Long count = 0L;
static Long Leadcount = 0L;
public static void main(String[] argv) throws Exception {
String userName = "<user_name>";
String password = "<pwd>";
String pushTopicName = "/topic/AccountPT";
String pushTopicNameLead = "/topic/Leadwhere";
long replayFrom = EmpConnector.REPLAY_FROM_EARLIEST;
String securityToken = "<token>";
BayeuxParameters custom = getBayeuxParamWithSpecifiedAPIVersion("37.0");
BayeuxParameters params = null;
try {
params = login(userName, password + securityToken, custom);
} catch (Exception e) {
e.printStackTrace();
}
Consumer<Map<String, Object>> consumer = event -> System.out.println(String.format("Received:\n%s ** Recieved at %s, event count total %s", event, LocalDateTime.now() , ++count));
Consumer<Map<String, Object>> consumerLead = event -> System.out.println(String.format("****** LEADS ***** Received:\n%s ** Recieved at %s, event count total %s", event, LocalDateTime.now() , ++Leadcount));
EmpConnector connector = new EmpConnector(params);
connector.start().get(10, TimeUnit.SECONDS);
TopicSubscription subscription = connector.subscribe(pushTopicName, replayFrom, consumer).get(10, TimeUnit.SECONDS);
TopicSubscription subscriptionLead = connector.subscribe(pushTopicNameLead, replayFrom, consumerLead).get(10, TimeUnit.SECONDS);
System.out.println(String.format("Subscribed: %s", subscription));
System.out.println(String.format("Subscribed: %s", subscriptionLead));
}
private static BayeuxParameters getBayeuxParamWithSpecifiedAPIVersion(String apiVersion) {
BayeuxParameters params = new BayeuxParameters() {
#Override
public String version() {
return apiVersion;
}
#Override
public String bearerToken() {
return null;
}
};
return params;
}
}
Code which is doing record create/update/delete periodically to generate events
import com.sforce.soap.enterprise.*;
import com.sforce.soap.enterprise.Error;
import com.sforce.soap.enterprise.sobject.Account;
import com.sforce.soap.enterprise.sobject.Contact;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
import java.time.LocalDateTime;
public class SFDCDataAdjustment {
static final String USERNAME = "<username>";
static final String PASSWORD = "<pwd&securitytoken>";
static EnterpriseConnection connection;
static Long count = 0L;
public static void main(String[] args) {
ConnectorConfig config = new ConnectorConfig();
config.setUsername(USERNAME);
config.setPassword(PASSWORD);
//config.setTraceMessage(true);
try {
connection = Connector.newConnection(config);
// display some current settings
System.out.println("Auth EndPoint: "+config.getAuthEndpoint());
System.out.println("Service EndPoint: "+config.getServiceEndpoint());
System.out.println("Username: "+config.getUsername());
System.out.println("SessionId: "+config.getSessionId());
// run the different examples
while (true) {
createAccounts();
updateAccounts();
deleteAccounts();
Thread.sleep(1 * 10 * 60 * 1000);
}
} catch (ConnectionException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// queries and displays the 5 newest contacts
private static void queryContacts() {
System.out.println("Querying for the 5 newest Contacts...");
try {
// query for the 5 newest contacts
QueryResult queryResults = connection.query("SELECT Id, FirstName, LastName, Account.Name " +
"FROM Contact WHERE AccountId != NULL ORDER BY CreatedDate DESC LIMIT 5");
if (queryResults.getSize() > 0) {
for (int i=0;i<queryResults.getRecords().length;i++) {
// cast the SObject to a strongly-typed Contact
Contact c = (Contact)queryResults.getRecords()[i];
System.out.println("Id: " + c.getId() + " - Name: "+c.getFirstName()+" "+
c.getLastName()+" - Account: "+c.getAccount().getName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// create 5 test Accounts
private static void createAccounts() {
System.out.println("Creating a new test Account...");
Account[] records = new Account[1];
try {
// create 5 test accounts
for (int i=0;i<1;i++) {
Account a = new Account();
a.setName("OptyAccount "+i);
records[i] = a;
}
// create the records in Salesforce.com
SaveResult[] saveResults = connection.create(records);
// check the returned results for any errors
for (int i=0; i< saveResults.length; i++) {
if (saveResults[i].isSuccess()) {
System.out.println(i+". Successfully created record - Id: " + saveResults[i].getId() + "At " + LocalDateTime.now());
System.out.println("************Event Count************" + ++count);
} else {
Error[] errors = saveResults[i].getErrors();
for (int j=0; j< errors.length; j++) {
System.out.println("ERROR creating record: " + errors[j].getMessage());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// updates the 5 newly created Accounts
private static void updateAccounts() {
System.out.println("Update a new test Accounts...");
Account[] records = new Account[1];
try {
QueryResult queryResults = connection.query("SELECT Id, Name FROM Account ORDER BY " +
"CreatedDate DESC LIMIT 1");
if (queryResults.getSize() > 0) {
for (int i=0;i<queryResults.getRecords().length;i++) {
// cast the SObject to a strongly-typed Account
Account a = (Account)queryResults.getRecords()[i];
System.out.println("Updating Id: " + a.getId() + " - Name: "+a.getName());
// modify the name of the Account
a.setName(a.getName()+" -- UPDATED");
records[i] = a;
}
}
// update the records in Salesforce.com
SaveResult[] saveResults = connection.update(records);
// check the returned results for any errors
for (int i=0; i< saveResults.length; i++) {
if (saveResults[i].isSuccess()) {
System.out.println(i+". Successfully updated record - Id: " + saveResults[i].getId() + "At " + LocalDateTime.now());
System.out.println("************Event Count************" + ++count);
} else {
Error[] errors = saveResults[i].getErrors();
for (int j=0; j< errors.length; j++) {
System.out.println("ERROR updating record: " + errors[j].getMessage());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// delete the 5 newly created Account
private static void deleteAccounts() {
System.out.println("Deleting new test Accounts...");
String[] ids = new String[1];
try {
QueryResult queryResults = connection.query("SELECT Id, Name FROM Account ORDER BY " +
"CreatedDate DESC LIMIT 1");
if (queryResults.getSize() > 0) {
for (int i=0;i<queryResults.getRecords().length;i++) {
// cast the SObject to a strongly-typed Account
Account a = (Account)queryResults.getRecords()[i];
// add the Account Id to the array to be deleted
ids[i] = a.getId();
System.out.println("Deleting Id: " + a.getId() + " - Name: "+a.getName());
}
}
// delete the records in Salesforce.com by passing an array of Ids
DeleteResult[] deleteResults = connection.delete(ids);
// check the results for any errors
for (int i=0; i< deleteResults.length; i++) {
if (deleteResults[i].isSuccess()) {
System.out.println(i+". Successfully deleted record - Id: " + deleteResults[i].getId() + "At " + LocalDateTime.now());
System.out.println("************Event Count************" + ++count);
} else {
Error[] errors = deleteResults[i].getErrors();
for (int j=0; j< errors.length; j++) {
System.out.println("ERROR deleting record: " + errors[j].getMessage());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Further updates got below mentioned error after which notification were
2017-03-09T19:30:28.346 ERROR [com.salesforce.emp.connector.EmpConnector] - connection failure, reconnecting
org.cometd.common.TransportException: {httpCode=503}
at org.cometd.client.transport.LongPollingTransport$2.onComplete(LongPollingTransport.java:278)
at org.eclipse.jetty.client.ResponseNotifier.notifyComplete(ResponseNotifier.java:193)
After this reconnect also happened and handshake also happened but error seems to be in resubscribe() EMP connector seems to be not able to resubscribe for some reason
Note I am using "resubscribe-on-disconnect" branch of EMP connetor
We have determined there was a bug on the server side in a 403 case. The Streaming API uses a session routing cookie and this cookie periodically expires. When it expires, the session is routed to another server, and this responds with a 403. In the current version, this 403 response does not include connect advice, and the client does not attempt to reconnect. This has been fixed and the fix is currently live. My understanding is that this should fix the reconnect problem exhibited by the clients.

JavaFX troubles with removing items from ArrayList

I have 2 TableViews (tableProduct, tableProduct2). The first one is populated by database, the second one is populated with selected by user items from first one (addMeal method, which also converts those to simple ArrayList). After adding/deleting few objects user can save current data from second Table to txt file. It seems to work just fine at beginning. But problem starts to show a bit randomly... I add few items, save it, delete few items, save it, everything is fine. Then after few actions like that, one last object stays in txt file, even though the TableView is empty. I just can't do anything to remove it and I get no errors...
Any ideas what's going on?
public void addMeal() {
productData selection = tableProduct.getSelectionModel().getSelectedItem();
if (selection != null) {
tableProduct2.getItems().add(new productData(selection.getName() + "(" + Float.parseFloat(weightField.getText()) + "g)", String.valueOf(Float.parseFloat(selection.getKcal())*(Float.parseFloat(weightField.getText())/100)), String.valueOf(Float.parseFloat(selection.getProtein())*(Float.parseFloat(weightField.getText())/100)), String.valueOf(Float.parseFloat(selection.getCarb())*(Float.parseFloat(weightField.getText())/100)), String.valueOf(Float.parseFloat(selection.getFat())*(Float.parseFloat(weightField.getText())/100))));
productlist.add(new productSimpleData(selection.getName() + "(" + Float.parseFloat(weightField.getText()) + "g)", String.valueOf(Float.parseFloat(selection.getKcal())*(Float.parseFloat(weightField.getText())/100)), String.valueOf(Float.parseFloat(selection.getProtein())*(Float.parseFloat(weightField.getText())/100)), String.valueOf(Float.parseFloat(selection.getCarb())*(Float.parseFloat(weightField.getText())/100)), String.valueOf(Float.parseFloat(selection.getFat())*(Float.parseFloat(weightField.getText())/100))));
}
updateSummary();
}
public void deleteMeal() {
productData selection = tableProduct2.getSelectionModel().getSelectedItem();
if(selection != null){
tableProduct2.getItems().remove(selection);
Iterator<productSimpleData> iterator = productlist.iterator();
productSimpleData psd = iterator.next();
if(psd.getName().equals(String.valueOf(selection.getName()))) {
iterator.remove();
}
}
updateSummary();
}
public void save() throws IOException {
File file = new File("C:\\Users\\Maciek\\Desktop\\test1.txt");
if(file.exists()){
file.delete();
}
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
Iterator iterator;
iterator = productlist.iterator();
while (iterator.hasNext()) {
productSimpleData pd;
pd = (productSimpleData) iterator.next();
bw.write(pd.toString());
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
bw.flush();
bw.close();
}
}
and yeah, I realize addMethod inside if statement looks scary but don't mind it, that part is allright after all...
You only ever check the first item in the productlist list to determine, if the item should be removed. Since you do not seem to write to the List anywhere without doing a similar modification to the items of tableProduct2, you can just do the same in this case.
public void deleteMeal() {
int selectedIndex = tableProduct2.getSelectionModel().getSelectedIndex();
if(selectedIndex >= 0) {
tableProduct2.getItems().remove(selectedIndex);
productlist.remove(selectedIndex);
}
updateSummary();
}
This way you also prevent issues, if there are 2 equal items in the list, which could lead to the first one being deleted when the second one is selected...
and yeah, I realize addMethod [...] looks scary
Yes, it does, so it's time to rewrite this:
Change the properties in productData and productSimpleData to float and don't convert the data to String until you need it as String.
if (selection != null) {
float weight = Float.parseFloat(weightField.getText());
float weight100 = weight / 100;
float calories = Float.parseFloat(selection.getKcal())*weight100;
float protein = Float.parseFloat(selection.getProtein())*weight100;
float carb = Float.parseFloat(selection.getCarb())*weight100;
float fat = Float.parseFloat(selection.getFat())*weight100;
ProductData product = new productData(
selection.getName() + "(" + weight + "g)",
calories,
protein,
carb,
fat);
productlist.add(new productSimpleData(product.getName(), calories, protein, carb, fat));
tableProduct2.getItems().add(product);
}
Also that this kind of loop can be rewritten to an enhanced for loop:
Iterator iterator;
iterator = productlist.iterator();
while (iterator.hasNext()) {
productSimpleData pd;
pd = (productSimpleData) iterator.next();
bw.write(pd.toString());
bw.newLine();
}
Assuming you've declared productlist as List<productSimpleData> or a subtype, you can just do
for (productSimpleData pd : productlist) {
bw.write(pd.toString());
bw.newLine();
}
furthermore you could rely on a try-with-resources to close the writers for you:
try (FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw)){
...
} catch (IOException e) {
e.printStackTrace();
}
Also there is no need to delete the file since java overwrites the file by default and only appends data if you specify this in an additional constructor parameter for FileWriter.

Mergefile requests in PDF Toolkit failing

New to Active PDF Toolkit, aattempting to merge up to 100 seperate PDFs into 1. Original PDFs are small, 1-4 pages, but testing has about 1/2 .MergeFile requests failing. Found a lot of pdtk options online, closest to address this issue had sample of just repeating the .MergeFile several times if its not successful, which helped but still getting failures after 500 attempts to .MergeFile and no exceptions are thrown. Hoping someone has another suggestion on how to merge more consistently or what to verify when Mergefile fails in order to fix the issue.
foreach (string pdfFileName in filesToMerge)
{
filesEnumerated++;
string fileName = Path.GetFileName(pdfFileName);
bool mergeSuccessful = false;
for (int i = 0; i < maxPdfMergeAttempts; i++)
{
if (!mergedFiles.Contains(fileName))
{
try
{
pdfMergeResult = pdfToolkit.MergeFile(Path.Combine(currentWorkingDirectory, fileName), 0, 0);
if (pdfMergeResult == 1)
{
mergedFiles.Add(fileName);
mergeSuccessful = true;
break;
}
}
catch (Exception ex)
{
string text2 = String.Format("PDF {0} could not be merged for {1}. MergeReturnCode was {2}.", fileName, ID, pdfMergeResult);
WriteToAppLog(text2);
}
}
}
if (!mergeSuccessful)
{
string text2 = String.Format("PDF {0} could not be merged for ID {1}.", fileName, ID, pdfMergeResult);
WriteToAppLog(text2);
filesEnumerated--;
}
}

SharePoint get current list item from a collection

ive made a small app using c# for sp 2010, what i am doing is getting items from a collection and viewing specific fields that i want to, the problem is when i click an item it shows me the details of every item assigned to the current user, how can i show only the details of the current item which the user clicks, below is my code...thanks
foreach (SPListItem myItem in myItemCollection)
{
if (myList.Fields.ContainsField("Title"))
{
EntreeListItemDetailNameValue l = lGrp.AddListItem<EntreeListItemDetailNameValue>();
SPField myField1 = myList.Fields.GetField("Title");
l.Name = myField1.Title;
try
{
l.Value = myField1.GetFieldValueAsText(myItem["Title"]);
}
catch
{
l.Value = "";
}
}
if (myList.Fields.ContainsField("Priority"))
{
EntreeListItemDetailNameValue l2 = lGrp.AddListItem<EntreeListItemDetailNameValue>();
SPField myField = myList.Fields.GetField("Priority");
l2.Name = myField.Title;
try
{
l2.Value = myField.GetFieldValueAsText(myItem["Priority"]);
}
catch
{
l2.Value = "";
}
You could use GetItemById()
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitemcollection.getitembyid.aspx
void list_Click(object sender, EventArgs e) {
int clickedid = 0; //get the id from the clicked item
ShowForm(); //show detail form
DataBind(clickedid); //databind detail form
}
void DataBind(int id) {
SPListItemCollection myItemCollection = showthing; //load the list items, query using SPQuery, or SPList.Items
SPListItem item = myItemCollection.GetItemById(id);
form.Title = item["Title"];
}