• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

Kinitari

Black Canada Mafia
Holy fuck, I just struggled for hours on a problem with datagridview - such a rudimentary problem too, but I am so tired today I didn't realize.

Quick summary so I don't try to sound too smart and fuck up my meaning, ran a foreach loop on datagridviewrows, basically doing some simple read and compare coding on a particular column for about 10,000 entries. For some reason I kept getting an 'object is not instantiated' error, and for the longest time I thought it was talking about my datagridview object in general - then I realized it probably meant the few entries that were null - I wasn't doing any exception handling for that (duh).

Anyhoo, that I figured out quickly, the next part should have been arguably easier to figure out, but I spent the rest of my day (mind you, a pretty lazy day) trying to figure it out - it kept giving me the error except it was slightly different, I noticed my program was doing -something- but still giving me the error. I couldn't figure it out until I finally realized that the last row in my datagridview was the 'new row' thinger. It kept hanging on that for some reason, even with my error handling.

I just switched to a for (i) loop and told it to count up to the second last entry, and all is well now. I just wish I didn't take so long (probably like 2 actual hours was spent on this) and I am positive there is a way around it with a foreach loop, I just have no idea what it would be, and I don't want to put in the effort figuring it out now.

I'm still new at programming guys :(.
 

dabig2

Member
I think what I did was that I imagined goTime as being a static method like main, which was why I was thinking I had to use the instance of Primes in order to call isPrime(i). Silliness :p

I hadn't heard of the implicit parameter of the instance being passed to methods though. Thanks for the info. :eek:

That parameter must be how you can reference the instance that called the method by using "this" within the method, then?

I should mention that the passing this to every method isn't entirely true, at least not what you'll see from most sources. I was taught it that way by a teacher some moons ago who thought it would be easier to comprehend what was really going on under the hood.

What you'll see in most texts is that the "this" parameter is a hidden variable of the class itself and is available to every method automatically as soon as the object is instantiated in memory. So that's why any method you have who wants to access an instance variable can say "this.a = 3" if your instance variable is int a and so on.

So technically no passing of the reference variable from class method to class method as it's not needed. They all can access that class variable equally at any time.
 
I should mention that the passing this to every method isn't entirely true, at least not what you'll see from most sources. I was taught it that way by a teacher some moons ago who thought it would be easier to comprehend what was really going on under the hood.

It depends upon the language semantics, native representation, and ABI. For a compiled language like C++ the 'this' pointer is actually passed as an argument for instance methods (eg, not class methods as you point out). Imagine a theoretical, PPC-like machine where there are 32 general-purpose registers, and the ABI declares that the first argument to a method call begins at r3 and extends to r8 where-after it spills arguments to the stack, r9 through r32 are marked volatile, and r1 is reserved for return values. Imagine a source code that looks like:

Code:
class foo
{
public:
    int x;
    int y;
    int add() const { return x + y; }
};

int main( int argc, char* argv[] )
{
   foo f;
   f.x = 1;
   f.y = 2;
   return f.add();
}

The compiled representation might look like, sans inlining, compile time sub-expression optimization, etc:

Code:
foo_addAt:
0x8000000      load r9, 0(r3)
0x8000004      load r10, 4(r3)
0x8000008      add r1, r9, r10
0x800000C     ret
main:
0x8000010      sub sp, sp, 8
0x8000014      mov r3, sp
0x8000018      xor r9, r9, r9
0x800001C     addi r9, 1
0x8000020      xor r10, r10, r10
0x8000024      addi r10, 2
0x8000028      store 0(r3), r9
0x800002C     store 4(r3), r10
0x8000030      call 0x8000000
0x8000034     ret
Eg, make space on the stack for an 8 byte structure, load immediates because they're known at compile time, store them to memory (eg, the stack in this case), call our method. The method loads the members based on the implicit this pointer passed as the first argument in r3, calculates the result and places it into r1. The caller knows it's just returning the result of the method invocation so it leaves r1 untouched when it returns to _init or whatever.

An optimizing compiler will of course just change this to:

Code:
0x8000000      xor r1, r1, r1
0x8000004      addi r1, 3
0x8000008      ret

Since it can evaluate the expression tree entirely at compile-time.
 

usea

Member
100% C# newbie and I've completed two basic C++ courses.
Here are some pages that aim to introduce C# to C++ programmers
http://msdn.microsoft.com/en-us/library/yyaad03b(VS.80).aspx
http://geekswithblogs.net/BlackRabb...ings-c-developers-learning-c-should-know.aspx
http://www.andymcm.com/csharpfaq.htm

If you have any questions, even tiny ones, feel free to post here. Though you could probably find answers more quickly with google / stackoverflow.

I don't know about you, but I learn best by example. I'd recommend either looking at some basic examples and toying with them, or attempting to write something simple.

Some examples:
http://www.csharp-examples.net/
http://msdn.microsoft.com/en-us/library/vstudio/k1sx6ed2.aspx
http://www.dotnetperls.com/class
 

Exuro

Member
I don't know about you, but I learn best by example. I'd recommend either looking at some basic examples and toying with them, or attempting to write something simple.

Some examples:
http://www.csharp-examples.net/
http://msdn.microsoft.com/en-us/library/vstudio/k1sx6ed2.aspx
http://www.dotnetperls.com/class
This is really nice. I'll be checking this out so more when I have some time. I feel I learn best by taking already made code and messing around with it to see what's doing what.
 

Realyn

Member
Hello,

I just started reading a book on C++ today. So far I'm 100 pages in. At this point I wanted to create a programm to check whether a random number is a prime number or not.

And well I'm stuck. I even think I know why, but dunno how to fix it.

Code:
// Primzahl.cpp : Definiert den Einstiegspunkt für die Konsolenanwendung.
//

#include <iostream>
using namespace std;



// Hauptprogramm
int main ()
{
	// Variablen
	int Prime_number;
	int Result = 0;

	// Abfragen
	cout << "Please enter  possible prime number: ";
	cin >> Prime_number;

	// Rechnen

	for (int i=2; i <= Prime_number ; i++)
	{
		// Auf Kommastelle prüfen
	
		if (Prime_number%i == 0)
		{	
			Result +=1;
		}
		cout << Result;

	}
	
	return 0;
}
What I want: to use Result as a counter. If it outputs 1 the number is a prime number, everything above 1 and it's not. Or change i to 1 and the minimum required number to 2.

Aaand my problem, as you have probably figured, is: If I enter 7 the console gives me: 1111112 and I even understand why. The for loop happened 7 times for i=1-7. For 1-6 the output was 1 each time. The seventh time the output was 2 for 1 and 7 as positive divisors.

Aaand my problem, as you have probably figured, is: If I enter 7 the console gives me: 000001 and I even understand why. The for loop happened 6 times for i=2-7. For 2-6 the output was 0 each time. The sixth time the output was 1 for 7 as positive divisor.




So yeah, I guess I need to extract Result out of the for loop and add something like

Code:
if(extracted_result == 1)
    cout << "You got a prime number!" << endl;
else
    cout << "No luck" <<endl;

Appreciate it if someone could help and comment on my idea in general.

edit: Actually i=1 won't work at all. I'm dumb. So it has to be 2.

edit2: oh dear. 00001 is the same as 1 .... Good to know.

Code:
// Primzahl.cpp : Definiert den Einstiegspunkt für die Konsolenanwendung.
//

#include <iostream>
using namespace std;



// Hauptprogramm
int main ()
{
	// Variablen
	int Prime_number;
	int Result = 0;

	// Abfragen
	cout << "Please enter Prime Number: ";
	cin >> Prime_number;

	// Rechnen

	for (int i=2; i <= Prime_number ; i++)
	{
		// Auf Kommastelle prüfen
	
		if (Prime_number%i == 0)
		{	
			Result +=1;
		}
		

	}
	
	if(Result == 1)
    cout << "You got a prime number!" << endl;
	else
    cout << "No luck" <<endl;

	return 0;
}

works :)
 

squidyj

Member
Best advice I can ever give anyone after the program I just turned in:

NEVER

WAIT

UNTIL

THE

LAST

MINUTE.

EVER.

I hate myself right now.

This is why I spend all day every day in the lab. Except for the weekends where I code on my laptop. That x86 tetris program took way more effort than I wanted to spend on it.

This x86 course and graphics course are kind of painful but I'm looking forward to graphics assignment 3 ray-tracing.
I'm still trying to come to grips with algorithms for traversing a ray through an octree though. Something something hashing?
 

Karl2177

Member
So I'm back again with a different holdup. I have a private recursive method that returns an int with an upper bound specified in the parameters. The issue is if you enter a value that is the upper bound, it repeats the scan.next() indefinitely. Game is a custom class, but for simplicity's sake, it could be replaced with int. The variable series is an array of Games, but again, int can work.

Here's the private method:
Code:
private int bound(int input, int bound) {
		Scanner scan = new Scanner(System.in);
		if (input >= bound || input < 0) {
			while (scan.hasNextInt()) {
				input = scan.nextInt();
				bound(input, bound);
			}

		}
		scan.close();
		return input;
	}

Then the public method that calls it. Basically, the only part really needed is the catch clause:
Code:
public void setGame(Game game, int seriesPos) {
		int index = seriesPos;
		try {
			series[index] = game;
			if (game.winner() == redteam) {
				redScore++;
			} else if (game.winner() == blueteam) {
				blueScore++;
			}
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("Please input a new index value for the series: ");
			Scanner scanner = new Scanner(System.in);
			while (scanner.hasNextInt()) {
				System.out.println("Please input a new index value for the series: ");
				index = bound(scanner.nextInt(), series.length);
				if (index < series.length && index > 0) {
					scanner.close();
					break;
				}
			}
			setGame(game, index);
		}
	}
 

Nesotenso

Member
I was hoping someone would help me with the following questions and point me in the right direction.

I know Ruby has similarities to Perl. I hope to get started on both.

-anyone have good additional resources for Ruby( besides codeacademy) and Perl ?

-How difficult is perl and how long does it take to get a handle on it ?
 

Randdalf

Member
Thought you guys might be interested in a thread I set up for Parallella. For anyone who hasn't heard of it, it's a $99 Raspberry Pi-style board with a 16-core processor, and it's currently on Kickstarter ($695k of $750k currently funded with 26 hours to go, should just about reach the target at current pace). Really interesting tech behind it, and it's perfect for folks (like me) who want something relatively cheap to learn parallel programming on.

Did a course on concurrency at university last year in a (horrible) language called XC, which was basically C with lots of features not present and with syntax for creating threads and then creating a message passing system between those threads. It got terribly confusing sometimes, and deadlocking is annoying to deal with as well.
 

mltplkxr

Member
I was hoping someone would help me with the following questions and point me in the right direction.

I know Ruby has similarities to Perl. I hope to get started on both.

-anyone have good additional resources for Ruby( besides codeacademy) and Perl ?

-How difficult is perl and how long does it take to get a handle on it ?

Programming Ruby - The Pragmatic Programmer's Guide :
http://www.ruby-doc.org/docs/ProgrammingRuby/

Why's (poignant) Guide:
http://en.wikipedia.org/wiki/Why's_(poignant)_Guide_to_Ruby
 

butzopower

proud of his butz
thanks, any suggestions for perl ?

In most ways, Ruby really does everything perl does but better (syntactically I mean). You could learn both, but you're probably going to get a lot more mileage out of Ruby these days. Sorry that's not a book suggestion, and just a suggestion overall.
 

f0rk

Member
I have some Fortran code I need to run and mess around with a bit for my maths degree final year project. What's the best program (a compiler right?) for a beginner on Windows 7?
 
I'm currently learning Java at school, but I wanted to know what are some other programming languages I should learn?

It doesn't matter that much. Learn data structures and algorithms. Write code and solve problems. If you're really concerned with learning how the structure of a language and its semantics changes the experience of programming, you should learn an imperative language (C), a functional language (SML), and a logical language (Lambda Prolog).
 

Nesotenso

Member
In most ways, Ruby really does everything perl does but better (syntactically I mean). You could learn both, but you're probably going to get a lot more mileage out of Ruby these days. Sorry that's not a book suggestion, and just a suggestion overall.

I personally would only learn Ruby.
Then move onto another programming language other than Perl because it's mainly the same thing.

thing is most of the vlsi ic design jobs I am looking at have preferences of coding experience in Perl but thanks for the suggestions.
 
In most ways, Ruby really does everything perl does but better (syntactically I mean). You could learn both, but you're probably going to get a lot more mileage out of Ruby these days. Sorry that's not a book suggestion, and just a suggestion overall.
perl can do recursive expression matching. e.g. you can programmatically parse/modify source code without writing a parser. Suck it down, Ruby!
 
You can simply write it like this.

Code:
<? if ($foo) : ?>
  <i>Foo</i>
<? else ?>
  <b>Bar</b>
<? endif; ?>

Short tags (meaning <? instead of <?php) are common.

my point is more the kind of horrific things that you find other programmers have done, it's possible to write some really unreadable PHP without even really trying ;) re: Short tags, they were explicitly disallowed in the course I just did, it's possible the uni has it disabled in php.ini which would mean an instant fail on that assignment if it didn't work on the school server. So i'm a long-tag man.
 

r1chard

Member
That's actually really cool, at first I didn't even realize it was interactive :D

Also what's the better web framework? Django or Ruby on Rails?
I'm leaning towards Django because the first impression was better, am I right?
They are pretty similar in capabilities, though the exact philosophies and mechanisms differ a bit. It really boils down to whether you would prefer to be coding in Ruby or in Python.

I found a comparison in the Googles from last year. Being a year old it's probably a bit out of date in some respects.
 
I need help :

So, I have folders named bin, build, and src. In src there's a file called HelloWorld.java, which I have successfuly compiled by launching the script ./bin/compile.sh so now I have a file called ./build/HelloWorld.class.

The problem is that I have a script called ./bin/run.sh that I'm supposed to use to run HelloWorld.class but it doesn't work. Here's the code (as written in my teacher's website):

Code:
#!/bin/sh
# Runs compiled Java files
java -cp ./build $*

When I enter
Code:
bash bin/run.sh
the following text appears:

Code:
computer@computer-1215N:~/Java/projet$ bash bin/run.sh
Syntaxe : java [-options] class [args...]
           (pour l'exécution d'une classe)
   ou  java [-options] -jar jarfile [args...]
           (pour l'exécution d'un fichier JAR)
où les options comprennent :
    -d32	  utilisez le modèle de données 32 bits s'il est disponible
    -d64	  utilisez le modèle de données 64 bits s'il est disponible
    -client	  pour sélectionner la machine virtuelle "client"
    -server	  pour sélectionner la machine virtuelle "server"
    -hotspot	  est un synonyme pour la machine virtuelle "client"  [en phase d'abandon]
                  La machine virtuelle par défaut est server,
                  car vous exécutez une machine de classe de serveur.


    -cp <class search path of directories and zip/jar files>
    -classpath <class search path of directories and zip/jar files>
                  Liste de répertoires, d'archives JAR et
                   d'archives ZIP séparés par des :, dans laquelle rechercher les fichiers de classe.
    -D<name>=<value>
                  définition d'une propriété système
    -verbose[:class|gc|jni]
                  activation de la sortie en mode verbose
    -version      impression de la version du produit et fin de l'opération
    -version:<value>
                  exécution de la version spécifiée obligatoire
    -showversion  impression de la version du produit et poursuite de l'opération
    -jre-restrict-search | -no-jre-restrict-search
                  inclusion/exclusion des environnements JRE privés de l'utilisateur dans la recherche de version
    -? -help      impression du message d'aide
    -X            impression de l'aide sur les options non standard
    -ea[:<packagename>...|:<classname>]
    -enableassertions[:<packagename>...|:<classname>]
                  activation des assertions avec la granularité spécifiée
    -da[:<packagename>...|:<classname>]
    -disableassertions[:<packagename>...|:<classname>]
                  désactivation des assertions avec la granularité spécifiée
    -esa | -enablesystemassertions
                  activation des assertions système
    -dsa | -disablesystemassertions
                  désactivation des assertions système
    -agentlib:<libname>[=<options>]
                  chargement de la bibliothèque d'agent natif <libname>, par exemple -agentlib:hprof
                  voir également, -agentlib:jdwp=help et -agentlib:hprof=help
    -agentpath:<pathname>[=<options>]
                  chargement de la bibliothèque d'agent natif via le chemin d'accès complet
    -javaagent:<jarpath>[=<options>]
                  chargement de l'agent du langage de programmation Java, voir java.lang.instrument
    -splash:<imagepath>
                  affichage de l'écran d'accueil avec l'image spécifiée
Voir http://www.oracle.com/technetwork/java/javase/documentation/index.html pour plus de détails.
computer@computer-1215N:~/Java/projet$

Apparently, the syntax of my command is wrong, but when I enter

Code:
java -cp ./build/ HelloWorld
the program runs flawlessly.

How do I make run.sh work as intended?
 
Apparently, the syntax of my command is wrong, but when I enter

Code:
java -cp ./build/ HelloWorld
the program runs as flawlessly.

How do I make run.sh work as intended?

The probably is you are not specifying the program name with your script.

$* just passes the value you pass to the script verbatim.

It should be
Code:
bash bin/run.sh HelloWorld
or even
Code:
bin/run.sh HelloWorld

assuming the script has executable permissions. The first line already says what shell to use.
 
The probably is you are not specifying the program name with your script.

$* just passes the value you pass to the script verbatim.

It should be
Code:
bash bin/run.sh HelloWorld
or even
Code:
bin/run.sh HelloWorld

assuming the script has executable permissions. The first line already says what shell to use.
It works. Thank you very much.
 

warpony663

Neo Member
I'm really struggling with this task we were given in our C# class

There is a list box with the names of all the files in a directory, when the user clicks on the list box the relevant image is loaded and displayed "in a suitable component".

I have no idea what the suitable component would be as I can't use a picture box as we are using ASP.net and cant figure out how to code for when someone clicks.
 
I'm sorry but I have another problem (I'm very new to Java). I have ./src/fr/crim/a2012/i18n/HelloWorld.java, and here's the code:

Code:
package fr.crim.a2012.i18n
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

And here's my compiling script, ./bin/compile.sh:

Code:
#!/bin/sh
javac -encoding UTF-8 build src/fr/crim/a2012/i18n/*.java

When I run that script, it does create the file ./build/fr/crim/a2012/i18n/HelloWorld.class but I can't run it. Here's what I get:

Code:
computer@computer-1215N:~/Java/projet$ java -cp ./build/fr/crim/a2012/i18n/ HelloWorld

Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld (wrong name: fr/crim/a2012/i18n/HelloWorld)
	at java.lang.ClassLoader.defineClass1(Native Method)
	at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
	at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
	at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
	at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
	at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
	at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
	at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:480)

computer@computer-1215N:~/Java/projet$
 

mackattk

Member
I have a quick question, and hopefully there is a simple solution to it. How do I pass a string into a void function? The assignment the teacher gave is that that display for each line item needs to be in a void function.
This is what I have so far:

Code:
#include<iostream>
#include<iomanip>
using namespace std;

double calcComm(double sales, double base, double percent)
{
    if(sales>base)
      return (sales-base)*percent;
    else
        return 0;
}

void output(string, double, double)

int main(){
    int salesmanNum;
    double baseSalary, SmartPhones, ServiceContracts, Accessories, MaintContracts, totalCommission;
	double PhoneCommission, ServiceCommission, AccessCommission, MaintComission;

	cout<<"Please Enter Salesman Identification or -999 to Terminate  ";
    cin>>salesmanNum;
    while(salesmanNum!=-999)
	{
	    cout<<"Please Enter Salesman Base Salary                          ";
	    cin>>baseSalary;

		cout<<"Please Enter Smart Phones Sales                            ";
		cin>>SmartPhones;

		cout<<"Please Enter Service Contracts Sales                       ";
		cin>>ServiceContracts;

		cout<<"Please Enter Accessories Sales                             ";
		cin>>Accessories;

		cout<<"Please Enter Maintenance Contracts Sales                   ";
		cin>>MaintContracts;

		PhoneCommission=calcComm(SmartPhones,6000.00,.25);
		ServiceCommission=calcComm(ServiceContracts,3500.00,.10);
		AccessCommission=calcComm(Accessories,2000.00,.05);
		MaintComission=calcComm(MaintContracts,500.00,.07);
		totalCommission=PhoneCommission+ServiceCommission+AccessCommission+MaintComission;
		
		cout << setprecision(2) << fixed;
		cout<<"\n\t\t  My Phone Company" << endl;
		cout <<"\t\tCommission Statement" << endl;
		cout <<"\t\t Salesman Number "<<salesmanNum;
		cout<<"\n\t********************************";
		cout<<setw(21)<<"\nProduct\t\t\tSales Amount\t        Commission";

		output("Smart Phones", SmartPhones,PhoneCommission);
		output("Service Contracts", ServiceContracts, ServiceCommission);
		output("Accessories", Accessories, AccessCommission);
		output("MaintenanceContracts", MaintContracts, MaintComission);

		cout<<setw(21)<<"\n\nTotal Commission\t"<<setw(11)<<"\t\t"<<right<<totalCommission;
		cout<<setw(21)<<"\nBase Pay\t\t"<<setw(11)<<"\t\t"<<right<<baseSalary;
		cout<<setw(21)<<"\nTotal Due\t\t"<<setw(11)<<"\t\t"<<right<<baseSalary+totalCommission<<endl<<endl;
		cout<<"\nPlease Enter Salesman Identification or -999 to Terminate  ";

		cout<<"\nPlease Enter Salesman Identification or -999 to Terminate  ";
		cin>>salesmanNum;
    }
	return 0;
}
	void output(string title, double salesdisplay, double commdisplay)
	{
		cout << endl;
		cout << title << salesdisplay << commdisplay;
	}

the final line " cout << title << salesdisplay << commdisplay;" is coming up with an error. I have been trying to figure this out for the past hour or two and haven't come up with a solution.

There error is "Error: no operator "<<" matches these operands"
 

Tantalus

Neo Member
I have a quick question, and hopefully there is a simple solution to it. How do I pass a string into a void function? The assignment the teacher gave is that that display for each line item needs to be in a void function.
This is what I have so far:

Adding #include<string> beneath your other includes should fix the error, but you'll also have to add a semicolon to the end of the line "void output(string, double, double)" to avoid getting another error (you are starting new line int main() when the previous line declaring "output" hasn't been ended correctly with a semicolon)
 

mackattk

Member
Adding #include<string> beneath your other includes should fix the error, but you'll also have to add a semicolon to the end of the line "void output(string, double, double)" to avoid getting another error (you are starting new line int main() when the previous line declaring "output" hasn't been ended correctly with a semicolon)

Thanks! It is ALWAYS something simple like that. I was banging my head against the wall trying to figure out what was going wrong. It made sense that it should work.
 

nOoblet16

Member
Is anyone here familiar with Maude Systems ?

I've searched literally everywhere I could and I've found little to no documentation/help over this POS topic. I've also been trying to install the Maude plugins for Eclipse and they don't see to work properly.

http://moment.dsic.upv.es/infocente...ic.issi.moment.mdt.help/html/gui/wizards.html

I've followed literally every steps mentioned in the link about under the installation process for the plugins but whenever I try to create a new project I get this:

9NK5h.jpg

instead of what's demonstrated in the tutorial which is this:

Because of which I am unable to select a new file container, and this means I can't even start writing my code cause it won't let me create a new maude project in the first place ! I'm unsure as per why we are suppose to study Maude in the first place ?
 

Chris R

Member
I'm really struggling with this task we were given in our C# class

There is a list box with the names of all the files in a directory, when the user clicks on the list box the relevant image is loaded and displayed "in a suitable component".

I have no idea what the suitable component would be as I can't use a picture box as we are using ASP.net and cant figure out how to code for when someone clicks.

So you have a list of images files sitting in a list box and want to display the image when the filename is clicked on?

If you are using ASP.Net then I'd suggest using the Image class and just set the ImageURL property of the control you are going to display into. As for handling the code for when someone clicks you want to look into the SelectedIndexChanged event of the Listbox. Finally, be careful of how you populate the listbox, as if you don't check to see if the page is posting back when you populate it things won't work how you are intending (losing whatever is currently selected, images not displaying, ect).
 

warpony663

Neo Member
So you have a list of images files sitting in a list box and want to display the image when the filename is clicked on?

Yeah thats exactly what I have. I've hacked at it for a bit but still have no idea why it isn't working. Barely used C# before this class and am struggling through the whole thing.

Heres the code, if anyone can see why it isn't working please let me know.

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace task3
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string path = "C:\\Users\\warpony\\Desktop\\task3\\test";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            System.IO.DirectoryInfo picture_folder = new System.IO.DirectoryInfo(path);
            FileInfo[] filePaths = picture_folder.GetFiles();
            int length = filePaths.Length;

            for (int i = 0; i <= length - 1; i++)
            {   
                string temp = Convert.ToString(filePaths.ElementAt(i));
                lst_pictures.Items.Add(temp);
            }
        }

        protected void lst_pictures_SelectedIndexChanged(object sender, EventArgs e)
        {
            string current = lst_pictures.SelectedItem.ToString();
            pictures_output.ImageUrl = current;
        }
    }
}
 

Karl2177

Member
So I'm back again with a different holdup. I have a private recursive method that returns an int with an upper bound specified in the parameters. The issue is if you enter a value that is the upper bound, it repeats the scan.next() indefinitely. Game is a custom class, but for simplicity's sake, it could be replaced with int. The variable series is an array of Games, but again, int can work.

Here's the private method:
Code:
snipped for size purposes

Then the public method that calls it. Basically, the only part really needed is the catch clause:
Code:
-snipped for size purposes

I solved this! Instead of sending the data that I needed bounded, I just set it to be a conditional statement inside of the public method that would repeat itself if it wasn't bounded.
 

Chris R

Member
Yeah thats exactly what I have. I've hacked at it for a bit but still have no idea why it isn't working. Barely used C# before this class and am struggling through the whole thing.

Heres the code, if anyone can see why it isn't working please let me know.

Again, you aren't checking for postback when you fill the listbox, causing you to repopulate the listbox everytime you postback. Add a check for

if (!Page.IsPostback)

and see if that improves your results.
 

warpony663

Neo Member
Again, you aren't checking for postback when you fill the listbox, causing you to repopulate the listbox everytime you postback. Add a check for

if (!Page.IsPostback)

and see if that improves your results.

Thanks man, got it to work.Changed the way I was writing the file names and changed the path of the folder. Don't know if its exactly what the lecturer wanted but it works at least.
 

usea

Member
Thanks man, got it to work.Changed the way I was writing the file names and changed the path of the folder. Don't know if its exactly what the lecturer wanted but it works at least.

A quick tip, you can put @ before a string to make it a verbatim string. Basically you won't have to escape the path separators.
So instead of
Code:
string path = "C:\\Users\\warpony\\Desktop\\task3\\test";
You could put
Code:
string path = @"C:\Users\warpony\Desktop\task3\test";

MSDN reference: http://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx
 
I hope someone can help me with this:

I want to play around with some Xbox Kinect data for some amateur sports analysis. If I don't have a whole lot of programming skill (know the extreme basics) is there a software environment in which I can hook up the Kinect, assign some points on a skeleton I want to keep track of, and read the resultant data (like speed, displacement, etc.)? Thanks.
 
I've got a question. I'm going a project on javascript, jquery, and xml/json data, and I can't get any of the jquery stuff to work.

Here's the code, and the professor had this work in class so I don't know what the deal is.

Code:
<html>
	<head>
		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
		<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/jquery-ui.min.us"></script>
		<script>
			$(document).ready(
				function() {
					$("img").click(
						function() {
							$(this).hide("explode", 5000);
						} );
				} );
		</script>
		
	</head>
	
	<body>
		<img src=*insert your own image file here* />
	</body>
</html>

I realize there's filler code in there for the image address so no need to call me on it
 
I believe the problem here is... in this case, the DOM isn't fully constructed when the script is called at the beginning (think of it like using a variable before it's initialized). When you refer to "img" in the jQuery function, it isn't there yet, at the time that script is executed.

Try moving the script call after the img tag.
 
Top Bottom