Quantcast
Channel: Visual C# forum
Viewing all 31927 articles
Browse latest View live

Why do non-English characters show up as ??? in one table, but correctly in another?

$
0
0

Hello,

I'm using SQL Server 2008 R2, and have two tables, both of which contain fields of type nvarchar(max). If I insert data into these tables using Query Analyser, and include non-English characters, one table stores them correctly, and the other stores them as question marks.

As far as I can see, the nvarchar(max) fields both tables look the same (apart from the name).

The database collation is Latin1_General_CI_AS if that helps.

I'm puzzled why one table works and the other doesn't. Anyone any ideas? Thanks


FREE custom controls for Lightswitch! A collection of useful controls for Lightswitch developers. Download from the Visual Studio Gallery.

If you're really bored, you could read about my experiments with .NET and some of Microsoft's newer technologies athttp://dotnetwhatnot.pixata.co.uk/


How can i use a method from library class project User Control in my windows forms project to upload files ?

$
0
0

In the library class project user control code i have this:

void menuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.Text == "Upload")
            {
                UploadDirectoryToFtp(e.ClickedItem.Text);
            }
        }

        private string UploadDirectoryToFtp(string directorytoupload)
        {
            return directorytoupload;
        }

In this case it's directories in directorytoupload there is a directory name i selected.

The first thing is that i need to upload the whole directory including sub directories and all files.

So on the ftp server i will have the directory and all files.

How to upload the directory and sub directories and files  do i need to use recursive and add all the sub directories and files to a List<string> ?

Now the method return the directory name only.

In the windows forms project after i'm adding the dll to the toolbox and drag it to my form1 designer i see myh ard disk drives and all files like windows explorer. Then i select a directory right click and Upload:

In the form1 windows forms application i have a backgroundworker i'm starting it with a button click:

private void btnUpload_Click(object sender, EventArgs e)
		{
			if(this.ftpProgress1.IsBusy)
			{
				this.ftpProgress1.CancelAsync();
				this.btnUpload.Text = "Upload";
			}
			else
			{
				FtpSettings f = new FtpSettings();
				f.Host = this.txtHost.Text;
				f.Username = this.txtUsername.Text;
                f.Password = this.txtPassword.Text;
				f.TargetFolder = this.txtDir.Text;
                f.SourceFile = this.txtUploadFile.Text;
				f.Passive = this.chkPassive.Checked;
				try
				{
					f.Port = Int32.Parse(this.txtPort.Text);
				}
				catch { }
				this.toolStripProgressBar1.Visible = true;
				this.ftpProgress1.RunWorkerAsync(f);
				this.btnUpload.Text = "Cancel";
			}
		}

And the upload class:

using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace FTP_ProgressBar
{
    public partial class FtpProgress : BackgroundWorker
    {
        private long FileSize = 0;
        private string FileSizeDescription;
        public static string ConnectionError;
        public static string ftp;
        private FtpSettings f;
        private FtpWebRequest ftpRequest;
        private FtpWebResponse ftpResponse1;
        public static DirectoryInfo d;
        public static string[] files;
        public static FileInfo[] dirflist;
        private string rootDirectory = "root";
        private string ftpcontentmaindirectory = @"c:\myftpdownloads";
        private string ftpcontentdir;
        private string hostDirectory = "ftp.newsxpressmedia.com";
        private string UserName = "newsxpressmediacom";
        private string Password = "Ynnad-1972";
        private DateTime DownloadStart;

        public FtpProgress()
        {
            InitializeComponent();
        }

        public FtpProgress(IContainer container)
        {
            DownloadStart = DateTime.Now;
            ftpcontentdir = Path.Combine(ftpcontentmaindirectory, rootDirectory);
            if (!Directory.Exists(ftpcontentdir))
                Directory.CreateDirectory(ftpcontentdir);
            container.Add(this);
            InitializeComponent();
        }

        private void FtpProgress_DoWork(object sender, DoWorkEventArgs e)
        {

            //FileInfoUploadFiles(sender, e);
            StringArrayUploadFiles(sender, e);
        }



        public static string GetFileSize(long numBytes)
        {
            string fileSize = "";

            if (numBytes > 1073741824)
                fileSize = String.Format("{0:0.00} Gb", (double)numBytes / 1073741824);
            else if (numBytes > 1048576)
                fileSize = String.Format("{0:0.00} Mb", (double)numBytes / 1048576);
            else
                fileSize = String.Format("{0:0} Kb", (double)numBytes / 1024);

            if (fileSize == "0 Kb")
                fileSize = "1 Kb";
            return fileSize;
        }

        private void StringArrayUploadFiles(object sender, DoWorkEventArgs e)
        {
            try
            {
                foreach (string txf in files)
                {
                    string fn = txf;
                    BackgroundWorker bw = sender as BackgroundWorker;
                    f = e.Argument as FtpSettings;
                    if (f.TargetFolder != "")
                        createDirectory(f.TargetFolder);
                    string UploadPath = String.Format("{0}/{1}{2}", f.Host, f.TargetFolder == "" ? "" : f.TargetFolder + "/", Path.GetFileName(fn));
                    if (!UploadPath.ToLower().StartsWith("ftp://"))
                        UploadPath = "ftp://" + UploadPath;
                    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(UploadPath);
                    request.UseBinary = true;
                    request.UsePassive = f.Passive;
                    request.Method = WebRequestMethods.Ftp.UploadFile;
                    request.Timeout = 300000;
                    request.Credentials = new NetworkCredential(f.Username, f.Password);
                    long FileSize = new FileInfo(fn).Length;//f.SourceFile).Length;
                    string FileSizeDescription = GetFileSize(FileSize);
                    int ChunkSize = 4096, NumRetries = 0, MaxRetries = 50;
                    long SentBytes = 0;
                    byte[] Buffer = new byte[ChunkSize];
                    using (Stream requestStream = request.GetRequestStream())
                    {
                        using (FileStream fs = File.Open(fn, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            int BytesRead = fs.Read(Buffer, 0, ChunkSize);
                            while (BytesRead > 0)
                            {
                                try
                                {
                                    if (bw.CancellationPending)
                                        return;

                                    requestStream.Write(Buffer, 0, BytesRead);

                                    SentBytes += BytesRead;

                                    string SummaryText = String.Format("Transferred {0} / {1}", GetFileSize(SentBytes), FileSizeDescription);
                                    bw.ReportProgress((int)(((decimal)SentBytes / (decimal)FileSize) * 100), SummaryText);
                                }
                                catch (Exception ex)
                                {
                                    Debug.WriteLine("Exception: " + ex.ToString());
                                    if (NumRetries++ < MaxRetries)
                                    {
                                        fs.Position -= BytesRead;
                                    }
                                    else
                                    {
                                        throw new Exception(String.Format("Error occurred during upload, too many retries. \n{0}", ex.ToString()));
                                    }
                                }
                                BytesRead = fs.Read(Buffer, 0, ChunkSize);
                            }
                        }
                    }
                    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                        System.Diagnostics.Debug.WriteLine(String.Format("Upload File Complete, status {0}", response.StatusDescription));
                }
                //}
            }
            catch (WebException ex)
            {
                switch (ex.Status)
                {
                    case WebExceptionStatus.NameResolutionFailure:
                        ConnectionError = "Error: Please check the ftp address";
                        break;
                    case WebExceptionStatus.Timeout:
                        ConnectionError = "Error: Timout Request";
                        break;
                }
            }
        }

In the bottom:

public class FtpSettings
    {
        public string Host, Username, Password, TargetFolder, SourceFile;
        public bool Passive;
        public int Port = 21;
    }

What i need it to do is two things.

First when i select the directory in the library class project it should collect all sub directories and all files if there are any in the selected directory. And add all of them to a List.

Second thing after selected the directory and collected all sub directories and files it should start the backgroundworker automatic and upload all the directory content to the ftp server. So in the end on my ftp server i will see the directory and inside the sub directories files...like it is on my hard disk.

Calculating Exponential Moving Average from comma text file

c# loop in custom list

$
0
0

hi to all,

i have this class:

class Order
    {
        Int32 _IndexNumber;
        String _RoomTypeCode;
        Int32 _NumberOfUnits;

        public Order(
                Int32 IndexNumber,
                String RoomTypeCode,
                Int32 NumberOfUnits
            )
        {
            this._IndexNumber = IndexNumber;
            this._RoomTypeCode = RoomTypeCode;
            this._NumberOfUnits = NumberOfUnits;
        }
    }

i am creating a custom list like this:

private void collectData(XmlDocument doc)
{
	XmlNodeList infos = doc.GetElementsByTagName("Reservations");
	List<Order> myOrderList = new List<Order>();

	foreach (XmlElement MainElem in infos)
	{
		Int32 IndexNumber = 123;;
		String RoomTypeCode = "asd";
		Int32 NumberOfUnits = 456;


		myOrderList.Add(new Order(IndexNumber,
			RoomTypeCode,
			NumberOfUnits,
			AgeQualifyingCode
			)
			);

	}

	Save2DB(myOrderList);
}

in my Save2DB method why i cannot see the Order attributes in my loop?

private void Save2DB(List<Order> _OrdList)
{
	for (int i = 0; i < _OrdList.Count; i++)
	{
		string myRoomTypeCode = _OrdList[0].
	}
}

What i am doung wrong?

Thanks in advance

parse and tryparse

$
0
0
When to use Parse() and When to use tryparse() ?

S.K Nayak

Will the Desktop Application written in Visual Studio 2013 and Windows 8.1 support in Windows 7 Ultimate?

$
0
0

Hello,

I have recently updated in Windows 8.1 and Visual Studio 2013. As per as I know Visual Studio 2013 Ultimate is not supported in Windows 7. So my question is: Will the application written in Visual Studio 2013 Ultimate (using Visual C#) support (Setup and Run) in Windows 7?

- Thanks

C sharp ADODB Recordset Datatable/DataRow Method Extensions

$
0
0

I am trying to write or reuse c sharp common method extension/helpers using only datatables and datarows.

I am trying to write method extensions visual basic 6.0 recordset properties using C sharp. We are migrating from VB 6 to C sharp. We moving from recordsets to disconnected datatables.

I want write extension for the methods b recordset properties below. Can someone give me suggestions with method and input parameters.

getvalue, setvalue, sort, BOF, EOF, absolutionPosition, DeleteRow, HasRows, UpdateRows, Open, Find, AddNew, MoveFirst, MoveNext, MovePrevious, MoveLast, Filter, Index, RecordCount, Copy, Save

Async / await - I just don't get it

$
0
0

I've been programming in C# for 10 years.  Have done many years of multi-threaded programming with threads, thread pools and most recently with Task<T>.  I fully understand tasks, ContinueWith(), cancellation, etc.  Today, I decided to try and understand what "async" is all about.  I read: Asynchronous Programming  and tried out a program:

	class Program {
		static void Main(string[] args) {

			try {
				AsyncTester tester = new AsyncTester();
				tester.Test1();
			}
			catch (Exception e) {
				Console.WriteLine("Exception:{0}\n{1}", e.Message, e.StackTrace);
			}
			finally {
				Console.WriteLine("<CR> to exit...");
				Console.ReadLine();
			}
		}
	}

...

	public class AsyncTester {

		public async void Test1() {
			float seconds = await WaitForTimeout(3000);
			Console.WriteLine("{0} seconds", seconds);
		}

		public async Task<float> WaitForTimeout(int milliseconds) {
			Stopwatch timer = new Stopwatch();
			timer.Restart();
			Task delay1 = Delay(milliseconds);
			await delay1;
			timer.Stop();
			return (float) timer.Elapsed.TotalSeconds;
		}

		private Task Delay(int milliseconds) {
			return new Task(() => Thread.Sleep(milliseconds));
		}
	}

I expected the Test1() method to delay for 3 seconds and then print the time it actually took.  Instead, it blows right through Test1() and returns.  I thought the "await" keyword would cause it to wait for the result.  If I take out the "async" keyword in front of Test1(), it won't compile.

Again, I just don't understand why I would ever use async/await.  The documentation says that this is a "simplified" approach.  Until someone can explain to me what this does, I'll stick to Tasks.


Creating a generic class that can read from the database

$
0
0

I do not have a lot of C# experience but would like to create a generic class that can read data from the database, I have my connection string in the web.config file and I would like to implement this class on the following class:

public Class Horse : Animals

{


	override void DoAge()

	{

		this.age +=2;

	}

}
Thank you in advance


Detect flash swf file opened in another form

$
0
0

Hi,

i have problem, i need get acces of loaded swf file from another running application/window, i have window hwnd and path for swf file, many thanks for reply on this problem.

is real acces of flash movie of another application ?

Hello World on Console ?

$
0
0

//

//    -------------------------------   Do you see anything in the console window?
//    ----------------            Does your console window stay on the screen or flash by?

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
// See  http://msdn.microsoft.com/en-us/library/aa288468(VS.71).aspx#pinvoke_example1
namespace SimpleTest
{
    class Program
    {
        [DllImport("msvcrt.dll")]    // Microsoft VC Runtime
        public static extern int puts(
            [MarshalAs(UnmanagedType.LPStr)]
             string m);

        [DllImport("msvcrt.dll")]
        internal static extern int _flushall();

        [DllImport("msvcrt.dll")]
        internal static extern int getchar();

        //  [DllImport("ftnTimesTwo.dll")]
        //  internal static extern ftnTimesTwo(Real m,Int n,Real mDoubled);
        public static void Main()
        {
            puts("Hello World!");
            puts("Hello World!");
            puts("Hello World!");
            puts("Hello World!");
            puts("Hello World!");
            
            getchar();

            _flushall();
        }
    }
}


                 

Bob

datagrideview

$
0
0

hi

i have one form and i enter these code in    private void Form1_Load(object sender, EventArgs e)

            string[] row = new string[] { "1", "Product 1", "1000" };
            dataGridView1.Rows.Add(row);

             row = new string[] { "2", "Product 2", "2000" };
            dataGridView1.Rows.Add(row);

so when i run program datagrideview with information above display.

at this time when program is runned we can add information by click on last rows of datagrideview too.

how can i get information that i add by click datagrideview and for example show in lable.

How to work a program using SQL TRIGGER

$
0
0

Hi Guys ;

I want to do this ,

We are using a program and I am listening to program with TRIGGER and I want to When someone record 10 items to program THEN I want to CALL a external program in my trigger

SO

DECLARE @RESULT VACHAR(10)=(SELECT TOP 1 VALUE FROM TABLE WHERE AMOUNT=10)

IF @RESULT<>0

exec master.dbo.xp_cmdshell 'cmd /C "C:\temp\warn\clean.bat"'

But doesn't work  , I want to only CALL external program in TRIGGER .

Lookup non-existent rows in MySQL table and then update another table with the value if not found

$
0
0

I wanted to write an SQL statement that would:

- Count the number of rows in the table `booking` that are open and where the `booking.postcode` is "MK"
- Take a note of the plot (in `booking.plot_id`), and then update the table `plot.jobs` with the value count

Example 1a: For example running the SQL query when `booking` table has the following rows:

Would see the following highlighted values in `plot.jobs` being updated to 1:

I managed to resolve it with this code so far (note I am using Connector/Net):

    public void RefreshPlot()
    {
    	string query ="SELECT Count(*) AS count, plot_id FROM booking WHERE postcode='MK' AND status='open' GROUP BY plot_id";
    	var cmd = new MySqlCommand(query, _connection);
    	var da = new MySqlDataAdapter(cmd);
    	var dtCounts = new DataTable();
    	da.Fill(dtCounts);

    	if (dtCounts.Rows.Count > 0)
    	{
    		query = "UPDATE plot SET jobs = @jobCount WHERE plot_id = @plotID AND postcode='MK'";
    		cmd = new MySqlCommand(query, _connection);
    		foreach (DataRow row in dtCounts.Rows)
    		{
    			cmd.Parameters.Clear();
    			cmd.Parameters.AddWithValue("@jobCount", int.Parse(row["count"].ToString()));
    			cmd.Parameters.AddWithValue("@plotID", int.Parse(row["plot_id"].ToString()));
    			cmd.ExecuteNonQuery();
    		}
    	}
    	else if ((dtCounts.Rows.Count == 0))
    	{
    		query = "UPDATE plot SET jobs=0 WHERE postcode='MK'";
    		cmd = new MySqlCommand(query, _connection);
    		cmd.ExecuteNonQuery();
    	}
    	CloseConnection();
    }

However, if we go back to Example 1a, I am finding that if I go into the `booking` table and delete a row, it does not reflect when the SQL statement is run i.e. the `plot` table no accurately longer reflects the `booking` table, because it does not realise that the row is deleted. 

Example 1b: If we delete the row with `plot.id=1` and `plot.plot_id=4`, then `booking.plot_id` should go back to being 0. Currently it doesn't...

How would I update my SQL statement to better reflect this? In a sense, it should check for "non-existent" rows, i.e. the impact that the row `plot.plot_id=4` & `plot.id=1` (inExample 1b) has on `booking.plot_id` when deleted? 

how to set bind to more DropDownList in web application using c#

$
0
0

hi all,

i have 3 class

1- Category Class

        public Int32 CategoryID { get; set; }
        public String CategoryName { get; set; }
        public List<SubCategory> ListSubCategory { get; set; }

2- SubCategory Class

        public Int32 SubCategoryID { get; set; }
        public String SubCategoryName { get; set; }
        public List<Item> ListItem { get; set; }

3- Item Class

        public Int32 ItemID{ get; set; }
        public String ItemName{ get; set; }

i want to make DropDownList  Dynamic change after user change category DropDownList  or SubCategory DropDownList  in web application

2- SubCategory Class

        public Int32 SubCategoryID { get; set; }
        public String SubCategoryName { get; set; }
        public List<Item> ListItem { get; set; }

2- SubCategory Class

        public Int32 SubCategoryID { get; set; }
        public String SubCategoryName { get; set; }
        public List<Item> ListItem { get; set; }


NullReferenceException error

$
0
0

I have a question on NullReerenceException.  I start off and say I am a complete novice like I just started like 2 - 3 weeks ago. 

I was watching a tutorial for dice game, I got it from YouTube great video.  Here's the code:

#region Using Statements
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
#endregion

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        #region Declaration

        Image[] diceImages;
        int[] dice;
        Random rand;





        #endregion

        #region Initialization

        public Form1()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {
            diceImages = new Image[6];
            diceImages[1] = Properties.Resources.dice_1;
            diceImages[2] = Properties.Resources.dice_2;
            diceImages[3] = Properties.Resources.dice_3;
            diceImages[4] = Properties.Resources.dice_4;
            diceImages[5] = Properties.Resources.dice_5;
            diceImages[6] = Properties.Resources.dice_6;

            dice = new int[6] { 0, 0, 0, 0, 0, 0, };
            rand = new Random();
        }
        #endregion

        #region Private Methods

        private void btn_Roll_Dice_Click(object sender, EventArgs e)
        {
            RollDice();

        }

        private void RollDice()
        {
            for (int i = 0; i <= dice.Length; i++)
                dice[2] = rand.Next(1, 6);
//Right at the "= 0; " part is where I get the NullReferenceException error. Red squiggly line under ; part

            lbl_Die1.Image = diceImages[dice[1]];
            lbl_Die1.Image = diceImages[dice[2]];
            lbl_Die1.Image = diceImages[dice[3]];
            lbl_Die1.Image = diceImages[dice[4]];
            lbl_Die1.Image = diceImages[dice[5]];
            lbl_Die1.Image = diceImages[dice[6]];


        }
        #endregion
    }
}
I thought the code would work, seems like I have what the labels do.  Any pointers would be greatly appreciated.  Again just learning for the last 20 days here.  I do subscribe to Channel9 and go to MSDN but some of the terms I have to research it to understand. But thanks for helping.

how to put Custom Header value in Http request without a key ?

$
0
0

Hi, I need to put a custom value in HttpWebRequest header without a key for it. HttpRequest.Headers is a NameValue collection and the server doesn't honor an header entry without a Name. Any help is highly appreciated.


Eg: my Http Header content should be  (I am able to do this in Fiddler, but not in C#):

User-Agent: SSL TestApp
Content-Type: x-Visa-II/x-auth

82D0.99999503U

- San

System.Windows.Forms.WebBrowser loading pdf with page number parameter

$
0
0

I am loading pdf into System.Windows.Forms.WebBrowser in c# windows application using below code. On the first time load the pdf is loaded without any problems but when I call this on button click event for second time with "#page=2" parameter I see a dark grey area and no pdf.

What I want is that when the button is clicked WebBrowser control should navigate to page 2 of the document.

private System.Windows.Forms.WebBrowser ctlwebBrow1 = new System.Windows.Forms.WebBrowser();
pdfPath=@"D:\\Projects\\ProjectDialog\\bin\\Debug\\Form_GENERAL_datafilled.pdf"
     ctlwebBrow1.Navigate("about:blank");
     if (ctlwebBrow1.Document != null)
             ctlwebBrow1.Document.Write(string.Empty);

     ctlwebBrow1.DocumentText = "<html></html>";
     //ctlwebBrow1.Navigate(pdfPath); // THIS WORKS FINE AND LOADS THE PDF
     ctlwebBrow1.Navigate(pdfPath + "#page=3");// THIS IS NOT WORKING, GREY AREA SHOWN INSTED OF PDF
     ctlwebBrow1.Dock = DockStyle.Fill;

Thanks & Regards

Sumit

Windows form controls reposition when DPI changes

$
0
0

Hi,

I have a windows form that has one image with a few labels and textboxes. I designed the UI with DPI in the default setting and everything looks exactly the way I want it. When I change the DPI to 125%, the controls start overlapping each other and it looks terrible/unusable. I have tried setting the form's AutoScaleMode from None, Font, DPI, and inherit. It looks like the controls reposition and do not resize. Even though each option is a little different, changing only this one property is definitely not the solution. I checked the other controls and they do not have an AutoScaleMode property. I am using Visual Studio 2012 Pro to develop this app.

I have seen many conversations about this issue but I have yet to find a solid solution. Is there some standard way to handle this anomaly?

Thanks,

Rob

TopTrumps - Using a Player class which holds the hands for Players 1 and 2

$
0
0

So, I decided to try and make a game of Top Trumps using C#, and bearing in mind I've only been using Visual Studio for 3 months now, I'm no pro.

I've been advised to use a Player class, which can then hold the cards for both Player 1 and Player 2's hands. By doing this, I will be able to remove cards when someone wins it.

The issue is I don't really know how to go about doing this.

Also, as I'm new here and to coding, I don't really know what to post code wise, as well as terminology wise.

Here's the whole program:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TopTrumps
{
    public partial class Form1 : Form
    {

        Random RandomNumbers = new Random();       //Initialise Random number generator

        Deck mDeck = new Deck();

        Player mPlayer1 = new Player();
        Player mPlayer2 = new Player();


        public Form1()
        {
            InitializeComponent();
            mPlayer1.mPlayerHand;
            mPlayer2.mPlayerHand;

        }


        int GetRandomCardIndex()     //Get a random card array index from the deck
        {
            return RandomNumbers.Next() % mDeck.mCards.Count;       //Limit number to size of array
        }

        void ShuffleDeck()
        {
            for (int i = 0; i < 100; i++)
            {
                int FirstCard;
                int SecondCard;
                Card TempCard;

                FirstCard = GetRandomCardIndex();
                SecondCard = GetRandomCardIndex();

                TempCard = mDeck.mCards[FirstCard];
                mDeck.mCards[FirstCard] = mDeck.mCards[SecondCard];
                mDeck.mCards[SecondCard] = TempCard;

            }

        }


        public class Card
        {
            public string mCarName = "Dodge Viper SRT-10";
            public int mTopSpeed = 100;
            public float m0_60 = 0.0F;
            public int mBHP = 200;
            public int mCapacity = 250;
            public int mWeight = 5;

            public Card()
            {

            }
            public Card(string tCarName, int tTopSpeed, float t0_60, int tBHP, int tCapacity, int tWeight)
            {
                mCarName = tCarName;
                mTopSpeed = tTopSpeed;
                m0_60 = t0_60;
                mBHP = tBHP;
                mCapacity = tCapacity;
                mWeight = tWeight;
            }

            //Method to return a string descrivbing the details of the Car
            public string CarDetails()
            {
                return "CarName: " + mCarName + "\nTopSpeed: " + mTopSpeed + "\n0-60: " + m0_60 + "\nBHP: " + mBHP + "\nCapacity:" + mCapacity + "\nWeight:" + mWeight + "\n\n";
            }
        }

        public class Deck
        {
            public List<Card> mCards = new List<Card>();
            //NAMES OF ALL THE CARDS IN THE DECK
            public string[] mAR_ST_CarName = { "Dodge Viper SRT-10", "Bugatti Veyron", "Porsche GT3 RS","Lamborghini Gallardo", "Mercedes SL55 AMG", "Ferarri F40","Noble M12", "Lamborghini Countach", "Porsche 959", "Corvette ZO6","BMW M3 CSL", "AC Cobra", "Honda NSX Type R", "Caterham R500","Lotus Esprit", "Saleen S7", "Jaguar XJ220", "Koenigsnegg CC8S","Mclaren F1", "Maserati MC12", "Mitsubushi Evo VIII", "Subaru Impreza","Aston Martin DB9", "Ferarri Enzo", "Ferrari 360 Stradale", "Radical SR3 Turbo","Ford GT", "Porsche Carrera GT", "TVR Tuscan S", "Bentley Continental GT","Pagani Zonda C12S", "Mercedes SLR Mclaren" };
            //EVERY TOP SPEED FOR EVERY CAR IN THE DECK
            public int[] mAR_ST_TopSpeed = { 189, 252, 190, 192, 155, 201, 170, 185, 197,
                                                  172, 155, 160, 168, 145, 175, 239, 217, 235,
                                                  240, 205, 148, 155, 186, 218, 188, 160, 200,
                                                  205, 185, 196, 215, 207 };
            //EVERY 0-60 TIME FOR EVERY CAR IN THE DECK
            public float[] mAR_ST_0_60 = { 4, 2.8F, 4.3F, 4.1F, 4.6F, 3.9F, 3.9F, 4.8F, 3.9F,
                                              4.3F, 4.6F, 4.2F, 4.6F, 3.5F, 4.3F, 3.3F, 3.6F, 4.2F,
                                              3.2F, 3.7F, 4.9F, 4.5F, 4.9F, 3.4F, 4F, 3.2F, 3.8F,
                                              3.7F, 3.8F, 4.8F, 3.8F, 3.7F };
            //EVERY BHP VALUE FOR EVERY CAR IN THE DECK
            public int[] mAR_ST_BHP = { 500, 987, 381, 493, 493, 478, 352, 455, 450,
                                             405, 360, 485, 276, 230, 350, 550, 542, 655,
                                             627, 622, 276, 316, 450, 650, 425, 320, 500,
                                             604, 400, 552, 542, 617 };
            //EVERY CAPACITY VALUE FOR EVERY CAR IN THE DECK
            public int[] mAR_ST_Capacity = { 8285, 7993, 3600, 4961, 5493, 2936, 2968, 5167, 2851, 5665,
                                                   3246, 6997, 3179, 1796, 3506, 7008, 3500, 4700, 6064, 5998,
                                                   1997, 1994, 5935, 5998, 3586, 1500, 5409, 5733, 3996, 5998,
                                                   7010, 5439 };
            //EVERY WEIGHT FOR EVERY CAR IN THE DECK
            public int[] mAR_ST_Weight = { 1542, 1600, 1650, 1520, 1880, 1100, 1080, 1447, 1450, 1413, 1460,
                                                1148, 1270, 460, 1300, 1247, 1456, 1275, 1137, 1335, 1410, 1470,
                                                1750, 1365, 1280, 325, 1519, 1380, 1100, 2385, 1250, 1693 };

           public Deck()
            {
               for (int i = 0; i < 32; i++)
               {
                   mCards.Add(new Card());
                   mCards[i].mCarName = mAR_ST_CarName[i];
                   mCards[i].mTopSpeed = mAR_ST_TopSpeed[i];
                   mCards[i].m0_60 = mAR_ST_0_60[i];
                   mCards[i].mBHP = mAR_ST_BHP[i];
                   mCards[i].mCapacity = mAR_ST_Capacity[i];
                   mCards[i].mWeight = mAR_ST_Weight[i];
               }
            }

        }

        public class Player
        {
            public List<Card> mPlayerHand = new List<Card>();
        }



        //BUTTON FOR PLAYER 1 FOR THEIR CARDS
        private void buttonPlayer1_Click(object sender, EventArgs e)
        {

            ShuffleDeck();

            for (int i = 0; i < 16; i++)
            {

            comboBoxPlayer1.Items.Add(mdeck)
                //comboBoxPlayer1.Items.Add(mDeck.mCards[i].mCarName);
               // mDeck.mCards.Remove(mDeck.mCards[i]);
            }
            comboBoxPlayer1.SelectedIndex = 0;
            buttonPlayer1.Enabled = false;                  //This kills the button after 1 click
        }

        //LISTBOX FOR PLAYER 1. DISPLAYS THE ATTRIBUTES
        private void listBoxPlayer1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        //DROPDOWN FOR PLAYER 1. DISPLAYS CARDS
        private void comboBoxPlayer1_SelectedIndexChanged(object sender, EventArgs e)
        {
            listBoxPlayer1.Items.Clear();
            listBoxPlayer1.Items.Add(mDeck.mAR_ST_TopSpeed[comboBoxPlayer1.SelectedIndex] + " mph");
            listBoxPlayer1.Items.Add(mDeck.mAR_ST_0_60[comboBoxPlayer1.SelectedIndex] + " seconds");
            listBoxPlayer1.Items.Add(mDeck.mAR_ST_BHP[comboBoxPlayer1.SelectedIndex] + " BHP");
            listBoxPlayer1.Items.Add(mDeck.mAR_ST_Capacity[comboBoxPlayer1.SelectedIndex] + " CC");
            listBoxPlayer1.Items.Add(mDeck.mAR_ST_Weight[comboBoxPlayer1.SelectedIndex] + " Kg");
        }

        //PLAYER 2 BUTTON FOR THEIR CARDS
        private void buttonPlayer2_Click(object sender, EventArgs e)
        {

            ShuffleDeck();

            for (int i = 16; i < 32; i++)
            {
                comboBoxPlayer2.Items.Add(mDeck.mCards[i].mCarName);
            }
            comboBoxPlayer2.SelectedIndex = 0;
            buttonPlayer2.Enabled = false;              //This kills the button after 1 click
        }

        //LISTBOX FOR PLAYER 2. DISPLAYS THE ATTRIBUTES
        private void listBoxPlayer2_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        //DROPDOWN MENU FOR PLAYER 2. DISPLAYS CARDS
        private void comboBoxPlayer2_SelectedIndexChanged(object sender, EventArgs e)
        {
            listBoxPlayer2.Items.Clear();
            listBoxPlayer2.Items.Add(mDeck.mAR_ST_TopSpeed[comboBoxPlayer2.SelectedIndex] + " mph");
            listBoxPlayer2.Items.Add(mDeck.mAR_ST_0_60[comboBoxPlayer2.SelectedIndex] + " seconds");
            listBoxPlayer2.Items.Add(mDeck.mAR_ST_BHP[comboBoxPlayer2.SelectedIndex] + " BHP");
            listBoxPlayer2.Items.Add(mDeck.mAR_ST_Capacity[comboBoxPlayer2.SelectedIndex] + " CC");
            listBoxPlayer2.Items.Add(mDeck.mAR_ST_Weight[comboBoxPlayer2.SelectedIndex] + " Kg");
        }




    }
}

Im not expecting code answers, but any pointers or tips would be greatly appreciated.

Viewing all 31927 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>