SEARCH YOUR SOLUTION HERE  

System.Data.Sqlclient.SqlException was unhandled

I'm writing code snippet in C# and using a Windows CE emulator in VS 2008 (even though it does not come with it you've to download and install CE emulator separately). But VS 2010 does not even let programming for mobile devices, so I've to use 2008.
After much searching, I figured out how can i establish a connection to our db (It's various with programming for CE devices than how I usually do it). I figured out the correct connection string and was able to add it. Then another error message... so I had to do more research to find out it needed SP1. VS2008 did, not SQL Server Compact... can not edit that as I've a later version installed already. So that error was gone. I can now add my db Objects, write queries, and even execute the code
But now it does not need to fill the data table, even though it can generate the table (with, I'm fairly certain, the correct info).
I am totally out of suggestions, and I have seen very much Google lately I'm getting kind of sick of it.
Pls assist if you can Even a link in the right direction would be comprehended.
Here's my error code (I wasn't sure if to post it in C# or SQL but going with SQL as that's the error, and I know that one of the kind mods will move it if it is in the wrong place)
This is created code, obviously. If you want need to view more just say so.
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Select, true)]
public virtual myDataSet.itemDataTable Receiveitem(string item) {
this.Adapter.SelectCommand = this.Commandcollection[0];
if ((item == null)) {
throw new global::System.ArgumentNullException("item");
}
else {
this.Adapter.SelectCommand.Parameters[0].Value = ((string)(item));
}
myDataSet.itemDataTable dataTable = new myDataSet.itemDataTable ();
this.Adapter.Fill(dataTable); exception thrown here

return dataTable;
Exception detail:
System.Data.Sqlclient.SqlException was unhandled
Message="SqlException"
Class=14
LineNumber=1
Number=18452
Procedure=""
Server="myServerName"
Source=".Net Sqlclient Data Provider"
State=1
Stacktrace:
at System.Data.Sqlclient.SqlConnection.onerror(SqlException exception, TdsParserState state)
at System.Data.Sqlclient.SqlInternalConnection.onerror(SqlException exception, TdsParserState state)
at System.Data.Sqlclient.TdsParser.ThrowExceptionAndWarning()
at System.Data.Sqlclient.TdsParser.Run(Runbehavior execute, SqlCommand cmdHandler, SqlDataReader dataStream)
at System.Data.Sqlclient.TdsParser.Run(Runbehavior execute)
at System.Data.Sqlclient.SqlInternalConnection.Login(Int32 timeout)
at System.Data.Sqlclient.SqlInternalConnection.OpenAndLogin()
at System.Data.Sqlclient.SqlInternalConnection..ctor(SqlConnection connection, Hashtable connectionOptions)
at System.Data.Sqlclient.SqlConnection.Open()
at System.Data.Common.DbDataAdapter.QuietOpen(IDbConnection connection, ConnectionState& originalState)
at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, Commandbehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, Commandbehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
at Test1.myDataSetTableAdapters.itemTableAdapter.Receiveitem(String item)
at Test1.Form1.is_valid_item()
at Test1.Form1.btnValid_Click(Object sender, EventArgs e)
at System.Windows.Forms.Control.onclick(EventArgs e)
at System.Windows.Forms.Button.onclick(EventArgs e)
at System.Windows.Forms.ButtonBase.WnProc(WM wm, Int32 wParam, Int32 lParam)
at System.Windows.Forms.Control._InternalWnProc(WM wm, Int32 wParam, Int32 lParam)
at Microsoft.AGL.Forms.EVL.EnterMainLoop(IntPtr hwnMain)
at System.Windows.Forms.Application.Run(Form fm)
at Test1.Program.Main()
update: server name has been changed to protect the innocent
This post has been updated by WabiSabi: 05 November 2012 - 03:44 PM
Posted On: Sunday, November 25, 2012 Total Views: 8
View Complete with Replies




Related Messages:

Re: VC# 2010 Express - RaceOnRCWCleanup was detected   (33 Views)
I have tried absolutely every thing that I can think of and find on google to receive rid of this memory type error message that keeps occurring when the software quits.
Error: An intend has been made to free an RCW that is in use. The RCW is in use on the active thread or another thread. Trying to free an in-use RCW can cause corruption or data loss.I have narrowed down where the error is coming from in the software but can not figure out how can i resolve it.
The following Form is what is causing this error when the main software form quits.
The Code snippet:Code snippet:
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;
using NiRDs.Global;
using Microsoft.VisualBasic;
namespace NiRDs.Forms.TabPageForms
{
public partial class frmBrowser : Form
{
private int ProgressTimerCount = 0;

public frmBrowser()
{
InitializeComponent();
}
private bool AbortingProp = false;
public AxSHDocVw.AxWebBrowser Page = new AxSHDocVw.AxWebBrowser();
public bool NewNavigate = false;
public ToolStripStatusLabel lblStatus = new ToolStripStatusLabel();
private void frmBrowser_FormClosing(Object sender System.Windows.Forms.FormClosingEventArgs e)
{
AbortingProp = true;
Page.Quit();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Page);
GC.Accumulate();
GC.WaitForPendingFinalizers();
}
private void tmrProgress_Tick(System.Object sender, System.EventArgs e)
{
try
{
if (Convert.ToBoolean(this.Tag) == true)
{
this.Icon = GlobalVariables.ProgressIcons[ProgressTimerCount];
}
ProgressTimerCount += 1;
if (ProgressTimerCount >= 8)
ProgressTimerCount = 0;
}
catch (Exception ex)
{
if (GlobalVariables.Abort == true || AbortingProp == true)
{
tmrProgress.Stop();
return;
}
throw new Exception("Error: " + ex.Message + Constants.vbCrLf + "Inner Exception: " + ex.InnerException.Message + Constants.vbCrLf + "Stacktrace: " + ex.Stacktrace + Constants.vbCrLf + "Sub: tmrProgress_Tick");
}
}
private void frmBrowser_Load(System.Object sender, System.EventArgs e)
{
tmrProgress.Tick += tmrProgress_Tick;
Page.Dock = DockStyle.Fill;

this.BrowserPanel.Controls.add(Page);

StatusBar.items.add(lblStatus);
Page.RegisterAsBrowser = true;
}
}
}
This is the code snippet that starts this form:Code:
private void cmdTest_Click(System.Object sender, System.EventArgs e)
{
frmBrowser f = new frmBrowser();
f.Display();
f.Page.GoHome();
}
And this is my applications EXITProcedure.Code:
private void EXITProcedure()
{
GlobalVariables.Abort = true; Abort all threads;
int x;

System.Environment.EXIT(0);
}Pls find a solution to this problem agrivating problem.
View Replies !
Re: Index was out of range   (3 Views)
Halloo....
I want ur assist badly
Pls do assist me to solve this error message...
I got this error after i save the first record and browse to the next record and then save.
Thanks Thanks....
"Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index"Code snippet:
private int _TaxCodeId;
private TaxCode _TaxCode;
protected void Page_Load(Object sender EventArgs e)
{
_TaxCodeId = AlwaysConvert.ToInt(Request.QueryString["TaxCodeId"]);
_TaxCode = TaxCodeDataSource.Load(_TaxCodeId);
if (_TaxCode == null) Response.Redirect("TaxCodes.aspx");
if ( Page.IsPostBack)
{
Caption.Text = string.Format(Caption.Text, _TaxCode.Name);
}
}
protected bool IsLinked(Object dataitem)
{
TaxRule rule = (TaxRule)dataitem;
return (rule.TaxRuleTaxCodes.IndexOf(rule.TaxRuleId, _TaxCodeId) > -1);
}
protected void Linked_CheckChanged(Object sender, EventArgs e)
{
CheckBox linked = (CheckBox)sender;
int taxRuleId = AlwaysConvert.ToInt(linked.Text);
TaxRule taxRule = TaxRuleDataSource.Load(taxRuleId);
if (linked.Checked)
{
ADD IF NOT FOUND
if (taxRule.TaxRuleTaxCodes.IndexOf(taxRuleId, _TaxCodeId) -1)
{
taxRule.TaxRuleTaxCodes.DeleteAt(index);
}
}
TaxRuleGrid.DataBind();
}
protected void SaveButton_Click(Object sender, EventArgs e)
{
_TaxCode.TaxRuleTaxCodes.DeleteAll();
foreach (GridViewRow gvr in TaxRuleGrid.Rows)
{
CheckBox Linked = gvr.FindControl("Linked") as CheckBox;
if (Linked.Checked)
{
int taxRuleId = (int)TaxRuleGrid.DataKeys[gvr.DataitemIndex].Value;
_TaxCode.TaxRuleTaxCodes.add(new TaxRuleTaxCode(taxRuleId, _TaxCodeId));
}
}
_TaxCode.Save();
SavedMessage.Visible = true;
SavedMessage.Text = string.Format(SavedMessage.Text, LocaleHelper.LocalNow);
}
View Replies !
Re: Kill a process that was started via another process   (6 Views)
Ok I've a service software that starts a process (with the Process.Start() method) but when I shutdown my service I can problem a Process.Kill() and it does indeed kill my process but it leaves any child processes open and that begins a runaway adventure with my processor.
In this case my Process.Path is pointing to a .bat file. Within that .bat is a statement to run java.exe. When I problem Process.Start() the .bat file is called and I can view Java starting and every thing works great. However when I problem a Process.Kill it only kills the .bat file and leaves Java.exe executing.
With out explicitly coding my process function to look for Java, Can some body pls advise me a way to kill all processes that my process started
View Replies !
I thought it was argS. Plural.  (8 Views)
As in more than one. I am attempting to parse CL options using Code snippet: static void Main(string[] args)
{
foreach(string arg in args)
{
System.Console.WriteLine(arg);
}
} So I execute my program
Myprogram "Arg1" "Arg2" "Arg3"
Output:
Arg1" Arg2 Arg3
Notice the odd ". Am I assuming some thing I should not be
View Replies !
Re: String was not recognized as a valid DateTime.   (6 Views)

I'm working with Windows applications in c#. I'm working with Dates for my software. when i changed the settings in the machine to canada I'm getting an error message "String wasn't recognized as a valid DateTime.".
I'm taking the data in DataView.There i can view the datecolumn with "21 03 06"
But when I'm filtering the row with "21 03 06" date It's displaying the above error "String wasn't recognized as a valid DateTime."
Pls advise me any solution if u have
View Replies !
Re: PInvokeStackImbalance was detected ??? Can some body help please?   (6 Views)
Can somebody tell me why Im getting this error
VB Code snippet:
using System;using System.collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Runtime.InteropServices;namespace Card_Test{ public partial class Form1 : Form { [DllImport("cards.dll")] private static extern bool cdtInit(ref int width ref int height); [DllImport("cards.dll")] private static extern bool cdtDraw(IntPtr hdc, int x, int y, int card, int mode, long color); private IntPtr hdc = new IntPtr(); public Form1() { InitializeComponent(); int iWidth = 100; int iHeight = 300; if ( cdtInit(ref iWidth, ref iHeight)) throw new Exception("cards.dll did not load"); } private void Form1_Load(Object sender, EventArgs e) { } private void Form1_Paint(Object sender, PaintEventArgs e) { base.OnPaint(e); hdc = e.Graphics.GetHdc(); Draw(); e.Graphics.ReleaseHdc(hdc); } private void Draw() { cdtDraw (hdc, 35, 10, 1, 0, 0); } }}

VB Code snippet:
PInvokeStackImbalance was detectedMessage: A call to PInvoke function 'Card Test Card_Test.Form1::cdtDraw' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.
View Replies !
FTP Trouble - An existing connection was forcibly closed by the remote host   (15 Views)
I got this class that deal with all FTP functionality and must admit, I don't know much how it work. I fundamentally just updated it a little bit for my own use, and seems to work fine.
Before I've been on a shared Win2K host, and the FTP functionality worked fine. But now we moved to a Win2K3 Dedicated server (yes, FTP to a remote server), this difficulty start occuring after FTP'in many files up. It work for a while, then start By this error message:

An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in system.dll
Extra info: An existing connection was forcibly closed by the remote host
The error occur on the line that reads:
in this code snippet: clientSocket.Send(cmdBytes, cmdBytes.Length, 0);
Code:
private void sendCommand(String command)
{
Byte[] cmdBytes = Encoding.ASCII.GetBytes((command+" r n").ToCharArray());
clientSocket.Send(cmdBytes, cmdBytes.Length, 0);
readReply();
}
I attached the class I'm using. For those looking for ftp functionality in their c# software, feel free to use it. Works (oops...worked) like a bomb for me.
View Replies !
Detecting that card was clicked with cards.dll?   (6 Views)
Does anybody have any solution how I can detect that card the user clicked on a card game when using cards.dll
I can't figure out how because it isn't an actual Object on the form but is drawn with the OnPaint event.http: www.vbforums.com showthread.p...46#post2417446
View Replies !
Socket.BeginReceive() error-An existing connection was forcibly closed  (16 Views)
Hello
I write host-client prorject using C#. It has been working well when I execute the host on Windows XP and client on Windows 7. But then I always receive connection error message when I execute both host and client on Windows XP. It throws exception on this function Socket.BeginReceive() and the exception error is "An existing connection was forcibly closed by the remote host"
Given below is the host code snippet:

private Socket gServerSocket;
private Socket gWorkerSocket;
private MainformGUI mainFormGuiObj;
private byte[] byteData;
public Dictionary clientMessageDictionary;
public void DisplayDebugMsg(bool error, string msg)
{
try
{
if (error == false)
System.Diagnostics.Debug.WriteLine(msg);
else
mainFormGuiObj.DelegateMsgBoxErrorText(msg);
}
catch (Exception err)
{
mainFormGuiObj.DelegateMsgBoxErrorText(err.Message);
}
}
public void BeginConnection()
{
DisplayDebugMsg(false, "inside BeginConnection()");
generate a TCP IP socket
gServerSocket = new Socket(AddressFamily.InterNetwork, socketType.Stream, ProtocolType.Tcp);
IPEndPoint represents a network computer in IP address and port number
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 3000);
bind the gSocketListener to the port
gServerSocket.Bind(ipLocal);
place a Socket in a listening state
gServerSocket.Listen(4);
gServerSocket.BeginAccept(new AsyncCallback(OnConnectedCallback), gServerSocket);
mainFormGuiObj.gDelegateDisplayMsgConnected("Testclient not connect", true);
}
private void OnConnectedCallback(IAsyncResult asyn)
{
try
{
DisplayDebugMsg(false, "inside OnConnectedCallback()");
Socket socket = (Socket)asyn.AsyncState;
gWorkerSocket = socket.EndAccept(asyn);
if (asyn.AsyncState == null)
DisplayDebugMsg(false, "asyn.AsyncState == null");
else
DisplayDebugMsg(false, "asyn.AsyncState not null");
if (gWorkerSocket.Connected)
{
mainFormGuiObj.gDelegateDisplayMsgConnected("Testclient connected", false);
DisplayDebugMsg(false, "client connected");
WaitForData(gWorkerSocket);
}
else
{
DisplayDebugMsg(false, "connection fail");
mainFormGuiObj.gDelegateDisplayMsgConnected("Testclient disconnected", true);
}
}
catch (SocketException error)
{
DisplayDebugMsg(true, "OnConnectedCallback(), " + error.Message);
}
catch (Exception exception)
{
DisplayDebugMsg(true, "OnConnectedCallback(), " + exception.Message);
}
}
private void WaitForData(Socket socket)
{
try
{
DisplayDebugMsg(false, "inside WaitForData()");

AsyncCallback asyncCallback = new AsyncCallback(DataReceivedCallBack);
socket.BeginReceive(byteData, 0, byteData.Length, socketFlags.None, asyncCallback, socket);
}
catch (Exception exception)
{
DisplayDebugMsg(true, "WaitForData(), " + exception.Message);
}
}
private void DataReceivedCallBack(IAsyncResult asyn)
{
try
{
DisplayDebugMsg(false, "inside DataReceivedCallBack()");
do some thing to data
}
catch (Exception exception)
{
handling bugs
}
}
When I execute host then after I execute client software, it calls this socket.BeginReceive(byteData, 0, byteData.Length, socketFlags.None, asyncCallback, socket) and that is when exception thrown, "An existing connection was forcibly closed by the remote host"
I have tried both secured and nonsecured wireless connections.
Pls provide any advice is possible,
View Replies !
Input String was in Incorrect Format thrown from datatable  (5 Views)
I keep getting a FormatException in the following code snippet block
OrderLine ordLine = new OrderLine();
Load all the 'finalized' dummyLines into a datatable (this will be used to loop by and set parameters later)
dTab = DAL.GetAllDummyLinesForOrder(setRealOrderFromDummy);
foreach (DataRow row in dTab.Rows)
{


'Receive' values from the datable and use them to SET the values in the OrderLineClass
ordLine.OrderLineID = SqlInt32.Parse(dTab.Columns["OrderLineID"].ToString()); Format Exception Being Thrown Here... WHY
ordLine.OrderID = SqlInt32.Parse(dTab.Columns["OrderID"].ToString());
ordLine.ProductID = SqlInt32.Parse(dTab.Columns["ProductID"].ToString());
ordLine.Quantity = SqlInt32.Parse(dTab.Columns["Quantity"].ToString());
ordLine.LineValue = SqlMoney.Parse(dTab.Columns["LineValue"].ToString());
ordLine.VatID = SqlInt32.Parse(dTab.Columns["VatID"].ToString());
Note IsActive is just hardcoded
ordLine.IsActive = "Y";
Add OrderLine With The Above Parameters
int x = DAL.AddOrderLine(ordLine);


}

Apologies for comments being messy, my ordLine is an instance class held in an external DLL. I've tried using:ordLine.OrderLineID = SqlInt32.Parse(dTab.Rows[0].ToString());
as well with no success. I've checked the value of the datable dTab, and it does infact have rows and columns, so no error message there right The column names used in the foreach loop are the same as those in the SQL db, and thier datatypes match those of the class properties I'm trying to set. Even if i put in a try....catch the end result is these rows are not commited to my db.
Given below is the code for the method DAL.AddOrderLine: Add Order Line
public int AddOrderLine(OrderLine orderLine)
{
using (SqlConnection dbConnection = new SqlConnection(DBConn))
{
int x;
SqlCommand dbCmd = new SqlCommand("uspAddOrderLine", dbConnection);
dbCmd.CommandType = CommandType.StoredProcedure;
dbCmd.Parameters.AddWithValue("@orderLineID", orderLine.OrderLineID);
dbCmd.Parameters.AddWithValue("@orderID", orderLine.OrderID);
dbCmd.Parameters.AddWithValue("@productID", orderLine.ProductID);
dbCmd.Parameters.AddWithValue("@quantity", orderLine.Quantity);
dbCmd.Parameters.AddWithValue("@orderLineValue", orderLine.LineValue);
dbCmd.Parameters.AddWithValue("@vatID", orderLine.VatID);
dbCmd.Parameters.AddWithValue("@isActive", orderLine.IsActive);
try
{
if (dbConnection.State == ConnectionState.Closed)
{
dbConnection.Open();
}
x = dbCmd.ExecuteNonQuery();
}
catch (SqlException e)
{
exc = new Exceptions();
exc.Exception = e;
logExc = new LogException();
logExc.LogExceptionToFile();
throw new ApplicationException("Error occured in the db and or connection");
}
Realease Resources
dbConnection.Close();
dbConnection.Dispose();
dbCmd.Dispose();
return x;
}
}
this is contained in a class in another (seperate) DLL.
Any assistance will be comprehended, I hope I've given enough info
View Replies !
Checking if an IP was generated by a Proxy.  (5 Views)

Is it possible to find out if an IP is created by a proxy I've googled and googled for quite a while now but I've had no luck....
View Replies !
C# Input string was not in a correct format  (3 Views)
this is a great forum and I've learnt alot from using the tutorials.
However I've having some problem with some of my code snippet at the moment. I keep getting a error message saying C# Input string wasn't in a correct format.
Here is the code in questions that I'm having the error with. arrData = clsData.getwarninglevel(machineID startTime, endTime);
if (arrData.Count > 0 )
{
string[] Alarmlevels = arrData[0].ToString().Split(' t');
pFAlarmLimitOk = Convert.ToInt32(Alarmlevels[0]);
pFAlarmLimitWarning = Convert.ToInt32(Alarmlevels[1]);
}
Any u guys know how could receive around this.
View Replies !
Index was outside the bounds of the array Error...  (14 Views)
friends..I am doing a c# program which uses Jagged array at one point.I am not able to repeat the for loop which is going to store my value in a jagged array.I have attached the Sample output i have to receive in a word document and also the difficulty description .Here is my code snippet for PART-1...... using System;
using System.collections.Generic;
using System.Linq;
using System.Text;
namespace Lab2
{
class Software
{
static void Main(string[] args)
{
int noofagents;
int[][] intJaggedArray;
string[] names;
Console.WriteLine("NUmber of agents ==>");
noofagents = Convert.ToInt32(Console.ReadLine());
names = new string[noofagents];
for (int i = 0; i " i + 1);
names[i] = Console.ReadLine();
Console.WriteLine("NUmber of Homes sold by {0}===>", names[i]);
int noofhomes=Convert.ToInt32(Console.ReadLine());
intJaggedArray = new int[noofhomes][];
for (int j = 1; j ", k++);
intJaggedArray[j][k] =Convert.ToInt32( Console.ReadLine());
} }

}

}
}
}

-------------------I am not getting any error message but i am not also getting the output as i want.Pls assist me what was my mistake here...
View Replies !
That key was pressed?  (1 Views)
guys.
I need to know how i can check in C#.net that "keycode" was pressed
Example:
If i press "CTRL" key MessageBox will display "U was pressed 'CTRL'key".
Sorry if my English is bad, I am from Serbia and here English language isn't main..
View Replies !
"ArgumentNullException was unhandled" debug error no display  (5 Views)
I have written a program where I ask the user to input a number b/w 2 and 8. If the user picks a number b/w 2 and 8 an Object is instantiated and will go on to do some work. If the user picks a number outside of those parameters, then the user gets a statement that says "invalid number." The trouble is that nothing shows. Here's the code snippet for the software class.
using System;
using System.collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Exercise6_7
{
class ProgramApplication
{
static void Main(string[] args)
{
int userInput1 = UserInputNumber1();
if (userInput1 >= 2 && userInput1)
{
instantiate multiplication table Object
Calculations multiplicationObject = new Calculations(UserInputNumber1());
}
else
{
Console.WriteLine("Invalid number");
}
}
Ask user to input first and second base values
public static int UserInputNumber1()
{
Console.WriteLine("Pls enter a number b/w 2 and 8: ");
int number1 = int.Parse(Console.ReadLine());
return number1;
}
}
}
Here is the code for Calculations class
using System;
using System.collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Exercise6_7
{
class Calculations
{
int number1 = 0;

property for the number1 datafield
public int Number1
{
receive
{
return number1;
}
set
{
number1 = value;
}
}

constructor
public Calculations(int firstNumber)
{
this.Number1 = firstNumber;
}
}
}
I started executing debug at the beginning of the software and it steps into
"int userInput1 = UserInputNumber1();" to the method UserInputNumber1() like I expected it would. It also steps into the " Console.WriteLine("Pls enter a number b/w 2 and 8: ");" line. From here, I expected a window to pop up so I could input a number, instead, it steps into the "int number1 = int.Parse(Console.ReadLine());" line and gives me an "ArgumentNullException was unhandled" error message. The detail states that "{"Value can't be null. r nParameter name: String"}.
For the error window gives me three various troubleshooting tips:
(1) Use the "new" keyword to generate an Object instance.
(2) Check to determine if the Object is null before calling the method
(3) Receive general assist for this exception
I do not believe that generating an instance Object is appropriate because I wana the if statement to verify the correct numbers before the Object is instantiated.
I am certain that the difficulty is because the Object is null before I call the method. However, I do not know what to do about that. I used this exact format on another exercise and it worked fine.
I am not asking for anybody to make my code for me. I am just attempting to understand why it works in one software but not the other. Here is the code for the other exercise. using System;
namespace Exercise5_4
{
public class Exercise5_4Application
{
public static void Main(string[] args)
{
call class method to begin control statement
String employeeType = SalaryOrHourly();
if salary employee, perform this work
if (employeeType == "Salary")
{
instantiate salaried employee
Employee salariedEmployeeObject = new Employee();
salariedEmployeeObject.EmployeeName = AskForEmployeeName();
salariedEmployeeObject.Salary = AskForSalary();
salariedEmployeeObject.GrossPay = GrossPay(salariedEmployeeObject.Salary);
salariedEmployeeObject.NetPay = NetPay(salariedEmployeeObject.GrossPay);
Console.WriteLine(salariedEmployeeObject.ToString());
}
if hourly employee, perform this work
else if (employeeType == "Hourly")
{
Employee hourlyEmployeeObject = new Employee();
hourlyEmployeeObject.EmployeeName = AskForEmployeeName();
hourlyEmployeeObject.HourlyRate = AskForHourlyWage();
hourlyEmployeeObject.HoursWorked = AskForHoursWorked();
hourlyEmployeeObject.OverTimeWorked = OverTimeWorked(
hourlyEmployeeObject.HoursWorked);
hourlyEmployeeObject.OverTimeRate = OverTimeWage(
hourlyEmployeeObject.HourlyRate);
hourlyEmployeeObject.GrossPay = GrossPay(
hourlyEmployeeObject.HourlyRate,
hourlyEmployeeObject.HoursWorked,
hourlyEmployeeObject.OverTimeWorked,
hourlyEmployeeObject.OverTimeRate);
hourlyEmployeeObject.NetPay = NetPay(
hourlyEmployeeObject.GrossPay);
Console.WriteLine(hourlyEmployeeObject.ToString());
}
}
class method to determin if employee is salary or hourly
public static String SalaryOrHourly()
{
Console.WriteLine("Salary or Hourly (case sensitive): ");
String employeeType = Console.ReadLine();
return employeeType;
}
classs method to request employee name
public static String AskForEmployeeName()
{
String employeeName;
Console.WriteLine("Enter Employee Name: ");
employeeName = Console.ReadLine();
return employeeName;
}
class method to request salary
public static double AskForSalary()
{
Console.WriteLine("Enter salary: ");
double salary = double.Parse(Console.ReadLine());
return salary;
}
class method to request hourly wage
public static double AskForHourlyWage()
{
Console.WriteLine("Enter Hourly Wage: ");
double hourlyRate = double.Parse(Console.ReadLine());
return hourlyRate;
}
class method to request hours worked
public static double AskForHoursWorked()
{
Console.WriteLine("Enter hours worked: ");
double hoursWorked = double.Parse(Console.ReadLine());
return hoursWorked;
}
class method to calculate overtime worked
public static double OverTimeWorked(double hoursWorked)
{
double overTimeWorked;
if (hoursWorked using System;
namespace Exercise5_4
{
public class Employee
{
declare variables
private String employeeName;
private double salary;
private double hourlyRate,
hoursWorked,
overTimeWorked,
overTimeRate,
grossPay,
netPay;
property of the employeeName datafield
public String EmployeeName
{
receive
{
return employeeName;
}
set
{
employeeName = value;
}
}
property of the salary datafield
public double Salary
{
receive
{
return salary;
}
set
{
salary = value;
}
}
property of hourlyRate datafield
public double HourlyRate
{
receive
{
return hourlyRate;
}
set
{
hourlyRate = value;
}
}
property of the hoursWorked datafield
public double HoursWorked
{
receive
{
return hoursWorked;
}
set
{
hoursWorked = value;
}
}
property of the overTimeWorked datafield
public double OverTimeWorked
{
receive
{
return overTimeWorked;
}
set
{
overTimeWorked = value;
}
}
property of the overTimeRate datafield
public double OverTimeRate
{
receive
{
return overTimeRate;
}
set
{
overTimeRate = value;
}
}
property of the overTimeRate datafield
public double GrossPay
{
receive
{
return grossPay;
}
set
{
grossPay = value;
}
}
property of the NetPay datafield
public double NetPay
{
receive
{
return netPay;
}
set
{
netPay = value;
}
}
generate default constructor
public Employee()
{
}
generate constructor for salaried employees
public Employee(String empName, double sal)
{
employeeName = empName;
salary = sal;
}
generate constructor for hourly employees
public Employee(String empName, double hrlyRate, double hrsWorked)
{
employeeName = empName;
hourlyRate = hrlyRate;
hoursWorked = hrsWorked;
}
update ToString() method
public override string ToString()
{
return "Gross Pay: " + GrossPay.ToString("C") + " n" +
"Net Pay: " + NetPay.ToString("C");
}
}
}

View Replies !
Input string was not in the correct format  (2 Views)
Upon executing the program below coded using Visual Studio 2010, I received the error message "Input string wasn't in the correct format". I've attempted to resolve it for some time now, but I fail to understand just why I get that message.
The program is easy. The user enters the amount of tickets sold for each class of tickets. There is class A, B, and C. Each ticket costs a certain amount, and the only calculation done is multiplying the amount tenter by the cost of the ticket. Finally, the result of each of these calculations is added together for the total cost of all tickets combined.
1) The user input is collected in a textbox in the string format. For the purpose of calculations, I converted it to decimal.
2)After the calculations for the three numbers entered have been made, It's added together for the total cost. Then, I converted each of the results to a string, formatted them to be presented in $ format, and finally, print them in the four boxes.
I do not understand why I get the error once the numbers are calculated. The code snippet is below. Thank u for the assist.
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;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalc_Click(Object sender, EventArgs e)
{
try
{
Stores the user input for amount of tickets sold
string boxA;
string boxB;
string boxC;
Stores the value of the tickets, converted from string to double
decimal ValueA;
decimal ValueB;
decimal ValueC;
Stores the total combined value of each class of ticket sold
decimal boxAtotal;
decimal boxBtotal;
decimal boxCtotal;
decimal abctotal = 0;
Value of each ticket
decimal boxAticket = 15;
decimal boxBticket = 12;
decimal boxCticket = 9;
Stores the final value of the tickets sold of each class to convert to the proper format for output
string SeatA;
string SeatB;
string SeatC;
string SeatsTotal;
Computes total value of tickets sold and total value
decimal Box1;
decimal Box2;
decimal Box3;
Takes user input
boxA = boxAtext.Text;
boxB = boxBtext.Text;
boxC = boxCtext.Text;
Converts input to decimal for calculations
ValueA = Convert.ToDecimal(boxA);
ValueB = Convert.ToDecimal(boxB);
ValueC = Convert.ToDecimal(boxC);
Computes the total value of tickets sold


boxAtotal = ValueA * boxAticket;
Box1 = boxAtotal;
boxBtotal = ValueB * boxBticket;
Box2 = boxBtotal;
boxCtotal = ValueC * boxCticket;
Box3 = boxCtotal;
abctotal = Box1 + Box2 + Box3;

Converts the value to $ format
SeatA = String.Format("{0:C}", boxAtotal);
SeatB = String.Format("{0:C}", boxBtotal);
SeatC = String.Format("{0:C}", boxCtotal);
SeatsTotal = String.Format("{0;C}", abctotal);

Shows final values in text box
totalA.Text = SeatA;
totalB.Text = SeatB;
totalC.Text = SeatC;
totalABC.Text = SeatsTotal;

}
catch (Exception ex)
{
MessageBox.Display(ex.Message);
}
}
private void btnClear_Click(Object sender, EventArgs e)
{
boxAtext.Text = "";
boxBtext.Text = "";
boxCtext.Text = "";
totalA.Text = "";
totalB.Text = "";
totalC.Text = "";
totalABC.Text = "";
}
private void btnEXIT_Click(Object sender, EventArgs e)
{
this.Close();
}
}
}

View Replies !
NullReferenceException was unhandled. Not sure on How do I resolve.  (4 Views)
I have more than one classes so I will put the problematic ones first:Enemy.csusing System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.collections.Generic;
using System.Linq;
using System.Text;
namespace Shooter
{
class Enemy
{
Animation representing the enemy
public Animation EnemyAnimation;
The position of the enemy ship relative to the top left corner of thescreen
public Vector2 Position;
The state of the Enemy Ship
public bool Active;
The hit points of the enemy, if this goes to zero the enemy dies
public int Health;
The amount of damage the enemy inflicts on the player ship
public int Damage;
The amount of score the enemy will provide to the player
public int Value;
Receive the width of the enemy ship
public int Width
{
**********************************
This is where I receive the exception
**********************************
receive { return EnemyAnimation.FrameWidth; }
}
Receive the height of the enemy ship
public int Height
{
receive { return EnemyAnimation.FrameHeight; }
}
The speed at that the enemy moves
float enemyMoveSpeed;
public void Initialize(Animation animation, Vector2 position)
{
Load the enemy ship texture
EnemyAnimation = animation;
Set the position of the enemy
Position = position;
We initialize the enemy to be active so it will be edit in the game
Active = true; Set the health of the enemy
Health = 10;
Set the amount of damage the enemy can do
Damage = 10;
Set how quick the enemy moves
enemyMoveSpeed = 2f; Set the score value of the enemy
Value = 100;
}
public void Edit(GameTime gameTime)
{
The enemy always moves to the left so decrement it is xposition
Position.Y += enemyMoveSpeed;
Edit the position of the Animation
EnemyAnimation.Position = Position;
Edit Animation
EnemyAnimation.Edit(gameTime);
If the enemy is past the screen or its health reaches 0 then deactivateit
if (Position.Y Game1.csusing System;
using System.collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Media;
namespace Shooter
{

This is the main type for ur game

public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Player player;
Keyboard states used to determine key presses
KeyboardState currentKeyboardState;
KeyboardState previousKeyboardState;
Gamepad states used to determine button presses
GamePadState currentGamePadState;
GamePadState previousGamePadState;
A movement speed for the player
float playerMoveSpeed;
image used to show the static background
Texture2D mainBackground;
Parallaxing Layers
ParallaxingBackground bgLayer1;
ParallaxingBackground bgLayer2;
Enemies
Texture2D enemyTexture;
List enemies;
Enemy enemy;
The rate at that the enemies appear
TimeSpan enemySpawnTime;
TimeSpan previousSpawnTime;
A random number generator
Random random;
Texture2D projectileTexture;
List projectiles;
Texture2D enemyProjectileTexture;
List enemyProjectiles;
The rate of fire of the player laser
TimeSpan fireTime;
TimeSpan previousFireTime;
TimeSpan enemyFireTime;
TimeSpan previousEnemyFireTime;
Texture2D explosionTexture;
List explosions;
The sound that is played when a laser is fired
SoundEffect laserSound;
The sound used when the player or an enemy dies
SoundEffect explosionSound;
The music played during gameplay
Song gameplayMusic;
Number that holds the player score
int score;
The font used to show UI elements
SpriteFont font;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}

allows the game to perform any initialization it needs to before starting to execute.
This is where it can query for any required services and load any non-graphic
related content. Calling base.Initialize will enumerate by any components
and initialize them as well.

protected override void Initialize()
{
TODO: Add ur initialization logic here
Initialize the player class
player = new Player();
enemy = new Enemy();
Set a constant player move speed
playerMoveSpeed = 8.0f;
Enable the FreeDrag gesture.
TouchPanel.EnabledGestures = GestureType.FreeDrag;
bgLayer1 = new ParallaxingBackground();
bgLayer2 = new ParallaxingBackground();
Initialize the enemies list
enemies = new List();
Set the time keepers to zero
previousSpawnTime = TimeSpan.Zero;
Used to determine how quick enemy respawns
enemySpawnTime = TimeSpan.FromSeconds(0.5f);
projectiles = new List();
enemyProjectiles = new List();
Set the laser to fire every quarter second
fireTime = TimeSpan.FromSeconds(.3f);
enemyFireTime = TimeSpan.FromSeconds(.3f);
explosions = new List();
Set player's score to zero
score = 0;
Initialize our random number generator
random = new Random();
base.Initialize();
}

LoadContent will be called once per game and is the place to load
all of ur content.

protected override void LoadContent()
{
Generate a new SpriteBatch, that may be utilized to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
TODO: use this.Content to load ur game content here
Load the player resources
Animation playerAnimation = new Animation();
Texture2D playerTexture = Content.Load("shipAnimation");
playerAnimation.Initialize(playerTexture, Vector2.Zero, 22, 28, 8, 30, Color.White, 1f, true);
Vector2 playerPosition = new Vector2(400, 420);
player.Initialize(playerAnimation, playerPosition);
Load the parallaxing background
bgLayer1.Initialize(Content, "bgLayer1", GraphicsDevice.Viewport.Width, -2);
bgLayer2.Initialize(Content, "bgLayer2", GraphicsDevice.Viewport.Width, -2);
enemyTexture = Content.Load("mineAnimation");
projectileTexture = Content.Load("laser");
enemyProjectileTexture = Content.Load("enemylaser");
explosionTexture = Content.Load("explosion");
Load the music
gameplayMusic = Content.Load("sound gameMusic");
Load the laser and explosion sound effect
laserSound = Content.Load("sound laserFire");
explosionSound = Content.Load("sound explosion");
Load the score font
font = Content.Load("gameFont");
Start the music right away
PlayMusic(gameplayMusic);
mainBackground = Content.Load("mainbackground");
}

UnloadContent will be called once per game and is the place to unload
all content.

protected override void UnloadContent()
{
TODO: Unload any non ContentManager content here
}

allows the game to execute logic such as updating the world,
checking for collisions, gathering input, and playing audio.

Provides a snapshot of timing values.
protected override void Edit(GameTime gameTime)
{
allows the game to EXIT
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.EXIT();
Save the previous state of the keyboard and game pad so we can determinesingle key button presses
previousGamePadState = currentGamePadState;
previousKeyboardState = currentKeyboardState;
Read the current state of the keyboard and gamepad and store it
currentKeyboardState = Keyboard.GetState();
currentGamePadState = GamePad.GetState(PlayerIndex.One);
if (currentKeyboardState.IsKeyDown(Keys.Escape))
{
EXIT();
}
Edit the player
UpdatePlayer(gameTime);
Edit the parallaxing background
bgLayer1.Edit();
bgLayer2.Edit();
Edit the enemies
UpdateEnemies(gameTime);
Edit the collision
UpdateCollision();
Edit the projectiles
UpdateProjectiles();

Edit the explosions
UpdateExplosions(gameTime);
base.Edit(gameTime);
}
private void PlayMusic(Song song)
{
Due to the way the MediaPlayer plays music,
we've to catch the exception. Music will play when the game isn't tethered
try
{
Play the music
MediaPlayer.Play(song);
Loop the recently playing song
MediaPlayer.IsRepeating = true;
}
catch { }
}
private void UpdateExplosions(GameTime gameTime)
{
for (int i = explosions.Count - 1; i >= 0; i--)
{
explosions[i].Edit(gameTime);
if (explosions[i].Active == false)
{
explosions.RemoveAt(i);
}
}
}
private void AddExplosion(Vector2 position)
{
Animation explosion = new Animation();
explosion.Initialize(explosionTexture, position, 25, 25, 12, 45, Color.White, 1f, false);
explosions.add(explosion);
}
private void UpdateProjectiles()
{
Edit the Projectiles
for (int i = projectiles.Count - 1; i >= 0; i--)
{
projectiles[i].Edit();
if (projectiles[i].Active == false)
{
projectiles.RemoveAt(i);
}
}
}
private void AddProjectile(Vector2 position)
{
KeyboardState keyboard = this.currentKeyboardState;
if (keyboard.IsKeyDown(Keys.Space))
{
Projectile projectile = new Projectile();
projectile.Initialize(GraphicsDevice.Viewport, projectileTexture, position);
projectiles.add(projectile);
}
}
private void UpdateProjectilesEnemy()
{
Edit the Projectiles
for (int i = enemyProjectiles.Count - 1; i >= 0; i--)
{
enemyProjectiles[i].Edit();
if (enemyProjectiles[i].Active == false)
{
enemyProjectiles.RemoveAt(i);
}
}
}
private void AddProjectileEnemy(Vector2 position)
{
KeyboardState keyboard = this.currentKeyboardState;

EnemyProjectile enemyprojectile = new EnemyProjectile();
enemyprojectile.Initialize(GraphicsDevice.Viewport, enemyProjectileTexture, position);
enemyProjectiles.add(enemyprojectile);

}
private void UpdateCollision()
{
Use the Rectangle's built-in intersect function to
determine if two Objects are overlapping
Rectangle rectangle1;
Rectangle rectangle2;
Only generate the rectangle once for the player
rectangle1 = new Rectangle((int)player.Position.X,
(int)player.Position.Y,
player.Width,
player.Height);
Do the collision b/w the player and the enemies
for (int i = 0; i enemySpawnTime)
{
previousSpawnTime = gameTime.TotalGameTime;
Add an Enemy
AddEnemy();
}
Edit the Enemies
for (int i = enemies.Count - 1; i >= 0; i--)
{
enemies[i].Edit(gameTime);
if (enemies[i].Active == false)
{
If not active and health enemyFireTime)
{
Reset our current time
previousEnemyFireTime = gameTime.TotalGameTime;
Add the projectile, but add it to the front and center of the player
AddProjectileEnemy(enemy.Position + new Vector2(enemy.Width 2, 0));
}
}
private void UpdatePlayer(GameTime gameTime)
{
player.Edit(gameTime);
Windows phone Controls
while (TouchPanel.IsGestureAvailable)
{
GestureSample gesture = TouchPanel.ReadGesture();
if (gesture.GestureType == GestureType.FreeDrag)
{
player.Position += gesture.Delta;
}
}
Receive Thumbstick Controls
player.Position.X += currentGamePadState.ThumbSticks.Left.X * playerMoveSpeed;
player.Position.Y -= currentGamePadState.ThumbSticks.Left.Y * playerMoveSpeed;
Use the Keyboard Dpad
if (currentKeyboardState.IsKeyDown(Keys.Left) ||
currentGamePadState.DPad.Left == ButtonState.Pressed)
{
player.Position.X -= playerMoveSpeed 2;
}
if (currentKeyboardState.IsKeyDown(Keys.Right) ||
currentGamePadState.DPad.Right == ButtonState.Pressed)
{
player.Position.X += playerMoveSpeed 2;
}

Make sure that the player does not go out of bounds
player.Position.X = MathHelper.Clamp(player.Position.X, 20, GraphicsDevice.Viewport.Width - player.Width);
player.Position.Y = MathHelper.Clamp(player.Position.Y, 20, GraphicsDevice.Viewport.Height - player.Height);
Fire only every interval we set as the fireTime
if (gameTime.TotalGameTime - previousFireTime > fireTime)
{
Reset our current time
previousFireTime = gameTime.TotalGameTime;
Add the projectile, but add it to the front and center of the player
AddProjectile(player.Position + new Vector2(player.Width 2, 0));

Play the laser sound
laserSound.Play();
}

reset score if player health goes to zero
if (player.Health
This is called when the game should draw itself.

Provides a snapshot of timing values.
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
TODO: Add ur drawing code snippet here
Start drawing
spriteBatch.Begin();
spriteBatch.Draw(mainBackground, Vector2.Zero, Color.White);
Draw the moving background
bgLayer1.Draw(spriteBatch);
bgLayer2.Draw(spriteBatch);
Draw the Enemies
for (int i = 0; i EnemyProjectile.csusing System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.collections.Generic;
using System.Linq;
using System.Text;
namespace Shooter
{
class EnemyProjectile
{
image representing the Projectile
public Texture2D Texture;
Position of the Projectile relative to the upper left side of the screen
public Vector2 Position;
State of the Projectile
public bool Active;
The amount of damage the projectile can inflict to an enemy
public int Damage;
Represents the viewable boundary of the game
Viewport viewport;
Receive the width of the projectile ship
public int Width
{
receive { return Texture.Width; }
}
Receive the height of the projectile ship
public int Height
{
receive { return Texture.Height; }
}
Determines how quick the projectile moves
float projectileMoveSpeed;
public void Initialize(Viewport viewport, Texture2D texture, Vector2 position)
{
Texture = texture;
Position = position;
this.viewport = viewport;
Active = true;
Damage = 10;
projectileMoveSpeed = 10f;
}
public void Edit()
{
Projectiles always move to the right
Position.Y += projectileMoveSpeed;
Deactivate the bullet if it goes out of screen
if (Position.Y + Texture.Height 2 > viewport.Height)
Active = false;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(Texture, Position, null, Color.White, 0f,
new Vector2((Width 2) + 10, (Height 2) + 10), 1f, SpriteEffects.None, 0f);
}

}
}ParallaxingBackground.csusing System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using System.collections.Generic;
using System.Linq;
using System.Text;
namespace Shooter
{
class ParallaxingBackground
{
The image representing the parallaxing background
Texture2D texture;
An array of positions of the parallaxing background
Vector2[] positions;
The speed that the background is moving
int speed;
public void Initialize(ContentManager content, String texturePath, int screenHeight, int speed)
{
Load the background texture we will be using
texture = content.Load(texturePath);
Set the speed of the background
this.speed = speed;
If we divide the screen with the texture width then we can determine the number of tiles want.
We add 1 to it so that we would not have a gap in the tiling
positions = new Vector2[screenHeight texture.Height + 1];
Set the initial positions of the parallaxing background
for (int i = 0; i = texture.Height * (positions.Length - 1))
{
positions[i].Y = -texture.Height;
}
}
}
}
public void Draw(SpriteBatch spriteBatch)
{
for (int i = 0; i Player.csusing System;
using System.collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Shooter
{
class Player
{
Animation representing the player
public Animation PlayerAnimation;
Position of the Player relative to the upper left side of the screen
public Vector2 Position;
State of the player
public bool Active;
Amount of hit points that player has
public int Health;
Receive the width of the player ship
public int Width
{
receive { return PlayerAnimation.FrameWidth; }
}
Receive the height of the player ship
public int Height
{
receive { return PlayerAnimation.FrameHeight; }
}
Initialize the player
public void Initialize(Animation animation, Vector2 position)
{
PlayerAnimation = animation;
Set the starting position of the player around the middle of the screen and to the back
Position = position;
Set the player to be active
Active = true;
Set the player health
Health = 100;
}
Edit the player animation
public void Edit(GameTime gameTime)
{
PlayerAnimation.Position = Position;
PlayerAnimation.Edit(gameTime);
}
Draw the player
public void Draw(SpriteBatch spriteBatch)
{
PlayerAnimation.Draw(spriteBatch);
}
}
}Animation.cs
Animation.cs
Using declarations
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using System.collections.Generic;
using System.Linq;
using System.Text;
namespace Shooter
{
class Animation
{
The image representing the collection of images used for animation
Texture2D spriteStrip;
The scale used to show the sprite strip
float scale;
The time since we last edited the frame
int elapsedTime;
The time we show a frame until the next one
int frameTime;
The number of frames that the animation contains
int frameCount;
The index of the current frame We're displaying
int currentFrame;
The color of the frame we will be displaying
Color color;
The area of the image strip we need to show
Rectangle sourceRect = new Rectangle();
The area where we need to show the image strip in the game
Rectangle destinationRect = new Rectangle();
Width of a given frame
public int FrameWidth;
Height of a given frame
public int FrameHeight;
The state of the Animation
public bool Active;
Determines if the animation will keep playing or deactivate after one execute
public bool Looping;
Width of a given frame
public Vector2 Position;
public void Initialize(Texture2D texture, Vector2 position,
int frameWidth, int frameHeight, int frameCount,
int frametime, Color color, float scale, bool looping)
{
Keep a local copy of the values passed in
this.color = color;
this.FrameWidth = frameWidth;
this.FrameHeight = frameHeight;
this.frameCount = frameCount;
this.frameTime = frametime;
this.scale = scale;
Looping = looping;
Position = position;
spriteStrip = texture;
Set the time to zero
elapsedTime = 0;
currentFrame = 0;
Set the Animation to active by default
Active = true;
}
public void Edit(GameTime gameTime)
{
Do not edit the game if We're not active
if (Active == false)
return;
Edit the elapsed time
elapsedTime += (int)gameTime.ElapsedGameTime.TotalMilliseconds;
If the elapsed time is larger than the frame time
we want to switch frames
if (elapsedTime > frameTime)
{
Move to the next frame
currentFrame++;
If the currentFrame is equal to frameCount reset currentFrame to zero
if (currentFrame == frameCount)
{
currentFrame = 0;
If We're not looping deactivate the animation
if (Looping == false)
Active = false;
}
Reset the elapsed time to zero
elapsedTime = 0;
}
Grab the correct frame in the image strip by multiplying the currentFrame index by the frame width
sourceRect = new Rectangle(currentFrame * FrameWidth, 0, FrameWidth, FrameHeight);
Grab the correct frame in the image strip by multiplying the currentFrame index by the frame width
destinationRect = new Rectangle((int)Position.X - (int)(FrameWidth * scale) 2,
(int)Position.Y - (int)(FrameHeight * scale) 2,
(int)(FrameWidth * scale),
(int)(FrameHeight * scale));
}
Draw the Animation Strip
public void Draw(SpriteBatch spriteBatch)
{
Only draw the animation when We're active
if (Active)
{
spriteBatch.Draw(spriteStrip, destinationRect, sourceRect, color);
}
}
}
}I'd like to know if there is any other way of doing this exception.
View Replies !
Input string was not in the correct format  (12 Views)
Upon executing the program below coded using Visual Studio 2010, I received the error message "Input string wasn't in the correct format". I've attempted to resolve it for some time now, but I fail to understand just why I get that message.
The program is easy. The user enters the amount of tickets sold for each class of tickets. There is class A, B, and C. Each ticket costs a certain amount, and the only calculation done is multiplying the amount tenter by the cost of the ticket. Finally, the result of each of these calculations is added together for the total cost of all tickets combined.
1) The user input is collected in a textbox in the string format. For the purpose of calculations, I converted it to decimal.
2)After the calculations for the three numbers entered have been made, It's added together for the total cost. Then, I converted each of the results to a string, formatted them to be presented in $ format, and finally, print them in the four boxes.
I do not understand why I get the error once the numbers are calculated. The code snippet is below. Thank u for the assist.
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;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalc_Click(Object sender, EventArgs e)
{
try
{
Stores the user input for amount of tickets sold
string boxA;
string boxB;
string boxC;
Stores the value of the tickets, converted from string to double
decimal ValueA;
decimal ValueB;
decimal ValueC;
Stores the total combined value of each class of ticket sold
decimal boxAtotal;
decimal boxBtotal;
decimal boxCtotal;
decimal abctotal = 0;
Value of each ticket
decimal boxAticket = 15;
decimal boxBticket = 12;
decimal boxCticket = 9;
Stores the final value of the tickets sold of each class to convert to the proper format for output
string SeatA;
string SeatB;
string SeatC;
string SeatsTotal;
Computes total value of tickets sold and total value
decimal Box1;
decimal Box2;
decimal Box3;
Takes user input
boxA = boxAtext.Text;
boxB = boxBtext.Text;
boxC = boxCtext.Text;
Converts input to decimal for calculations
ValueA = Convert.ToDecimal(boxA);
ValueB = Convert.ToDecimal(boxB);
ValueC = Convert.ToDecimal(boxC);
Computes the total value of tickets sold


boxAtotal = ValueA * boxAticket;
Box1 = boxAtotal;
boxBtotal = ValueB * boxBticket;
Box2 = boxBtotal;
boxCtotal = ValueC * boxCticket;
Box3 = boxCtotal;
abctotal = Box1 + Box2 + Box3;

Converts the value to $ format
SeatA = String.Format("{0:C}", boxAtotal);
SeatB = String.Format("{0:C}", boxBtotal);
SeatC = String.Format("{0:C}", boxCtotal);
SeatsTotal = String.Format("{0;C}", abctotal);

Shows final values in text box
totalA.Text = SeatA;
totalB.Text = SeatB;
totalC.Text = SeatC;
totalABC.Text = SeatsTotal;

}
catch (Exception ex)
{
MessageBox.Display(ex.Message);
}
}
private void btnClear_Click(Object sender, EventArgs e)
{
boxAtext.Text = "";
boxBtext.Text = "";
boxCtext.Text = "";
totalA.Text = "";
totalB.Text = "";
totalC.Text = "";
totalABC.Text = "";
}
private void btnEXIT_Click(Object sender, EventArgs e)
{
this.Close();
}
}
}

View Replies !
Error: Input string was not in a correct format  (7 Views)

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;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class frmAddProduct : Form
{
private CoffeeShopDatabaseEntities cse = new CoffeeShopDatabaseEntities();
private Byte[] byteBLOBData;
public frmAddProduct()
{
InitializeComponent();
cboCategory.DataSource = cse.TblProductTypes;
cboCategory.DisplayMember = "description";
cboCategory.ValueMember = "ProductType";
}
private void btnUpload_Click(Object sender EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
FileStream fsBLOBFile = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
byteBLOBData = new Byte[fsBLOBFile.Length];
fsBLOBFile.Read(byteBLOBData, 0, byteBLOBData.Length);
fsBLOBFile.Close();
MemoryStream stmBLOBData = new MemoryStream(byteBLOBData);
pbimage.image = image.FromStream(stmBLOBData);
}
}
private void btnSave_Click(Object sender, EventArgs e)
{
{
TblProduct product = new TblProduct();
product.description = txtdescription.Text;
product.Price = decimal.Parse(txtPrice.Text);
product.image = byteBLOBData;
product.ProductType = (int)cboCategory.SelectedValue;
cse.AddToTblProducts(product);
cse.SaveChanges();
MessageBox.Display("Record Saved");
}
}
}
}
Difficulty: "product.Price = decimal.Parse(txtPrice.Text);"
Input string wasn't in a correct format.
This post has been updated by tlhIn`toq: 03 April 2012 - 10:43 AM
View Replies !
Index was outside the bounds of the array.  (11 Views)
I'm recently learning C# via the head first C# book and I have come across the following peculiar difficulty. I know that I'm not outside of the bounds of the array yet its throwing this indexoutofrange exception. This is the first lab part of the book where you're not given the source code snippet, instead you are intended to figure it out yourself. The difficulties is with man[2], when I remove it the error message goes away.
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;
namespace ADayAtTheraces
{
public partial class Form1 : Form
{
Guy[] man;
Greyhound[] dog;


public Form1()
{
Guy[] man = new Guy[2];
man[0] = new Guy() { Name = "Joe", Cash = 50, MyBet = null };
man[1] = new Guy() { Name = "Bob", Cash = 75, MyBet = null };
man[2] = new Guy() { Name = "Al", Cash = 45, MyBet = null };

dog = new Greyhound[3];
dog[0] = new Greyhound() {MyPictureBox = pictureBox2, RacetrackLength = pictureBox1.Size.Width};
dog[1].MyPictureBox = pictureBox3;
dog[2].MyPictureBox = pictureBox4;
dog[3].MyPictureBox = pictureBox5;

InitializeComponent();
}
private void pictureBox2_Click(Object sender, EventArgs e)
{
}
}
}

View Replies !