i am using visual studio 2010 for making a Drawing Application but the problem is when i try to compile the program it says
1)The type name 'DrawingBoard' does not exist in the type 'DrawingBoard.DrawingBoard' line 33
2)The type name 'Toolbox' does not exist in the type 'DrawingBoard.DrawingBoard' line 34
3)An object reference is required for the non-static field, method, or property 'DrawingBoard.DrawingBoard.EditOption.get' line 74
the code of this program is below i have pointed the errors with the word problem. i would be very Thankful if you help me.
using System.Drawing;
namespace DrawingBoard
{
partial class WinForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.splitContainerMain = new System.Windows.Forms.SplitContainer();
this.drawingBoard = new DrawingBoard.DrawingBoard();//problem
this.toolBox = new DrawingBoard.Toolbox.ToolBox();//problem
this.splitContainerMain.Panel1.SuspendLayout();
this.splitContainerMain.Panel2.SuspendLayout();
this.splitContainerMain.SuspendLayout();
this.SuspendLayout();
//
// splitContainerMain
//
this.splitContainerMain.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainerMain.Location = new System.Drawing.Point(0, 0);
this.splitContainerMain.Margin = new System.Windows.Forms.Padding(2);
this.splitContainerMain.Name = "splitContainerMain";
//
// splitContainerMain.Panel1
//
this.splitContainerMain.Panel1.Controls.Add(this.drawingBoard);
//
// splitContainerMain.Panel2
//
this.splitContainerMain.Panel2.Controls.Add(this.toolBox);
this.splitContainerMain.Size = new System.Drawing.Size(853, 553);
this.splitContainerMain.SplitterDistance = 532;
this.splitContainerMain.SplitterWidth = 3;
this.splitContainerMain.TabIndex = 37;
//
// drawingBoard
//
this.drawingBoard.AllowDrop = true;
this.drawingBoard.AutoScroll = true;
this.drawingBoard.BackColor = System.Drawing.Color.White;
this.drawingBoard.BackgroundImageAlpha = ((byte)(255));
this.drawingBoard.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.drawingBoard.BackgroundImageX = 0;
this.drawingBoard.BackgroundImageY = 0;
this.drawingBoard.BoundedCanvasHeight = 1140;
this.drawingBoard.BoundedCanvasWidth = 810;
this.drawingBoard.CanvasOriginX = 0;
this.drawingBoard.CanvasOriginY = 0;
this.drawingBoard.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.Default;
this.drawingBoard.Dock = System.Windows.Forms.DockStyle.Fill;
this.drawingBoard.EditOption = DrawingBoard.EditOption.Select; //problem
this.drawingBoard.GridColor = System.Drawing.Color.Gainsboro;
this.drawingBoard.GridSize = 0;
this.drawingBoard.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default;
this.drawingBoard.IsBoundedCanvas = true;
this.drawingBoard.Location = new System.Drawing.Point(0, 0);
this.drawingBoard.Name = "drawingBoard";
this.drawingBoard.PaperOutsideColor = System.Drawing.Color.FromArgb(((int)(((byte)(230)))), ((int)(((byte)(230)))), ((int)(((byte)(255)))));
this.drawingBoard.ShowPaperOutside = true;
this.drawingBoard.Size = new System.Drawing.Size(532, 553);
this.drawingBoard.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
this.drawingBoard.StickyEditOption = true;
this.drawingBoard.TabIndex = 3;
this.drawingBoard.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
this.drawingBoard.Zoom = 1F;
//
// toolBox
//
this.toolBox.AutoSize = true;
this.toolBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.toolBox.Drawingboard = null;
this.toolBox.Location = new System.Drawing.Point(0, 0);
this.toolBox.Margin = new System.Windows.Forms.Padding(4);
this.toolBox.Name = "toolBox";
this.toolBox.Size = new System.Drawing.Size(318, 553);
this.toolBox.TabIndex = 1;
//
// WinForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
this.ClientSize = new System.Drawing.Size(853, 553);
this.Controls.Add(this.splitContainerMain);
this.Name = "WinForm";
this.Text = "DrawingBoard";
this.splitContainerMain.Panel1.ResumeLayout(false);
this.splitContainerMain.Panel2.ResumeLayout(false);
this.splitContainerMain.Panel2.PerformLayout();
this.splitContainerMain.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.SplitContainer splitContainerMain;
private DrawingBoard drawingBoard;
private global::DrawingBoard.Toolbox.ToolBox toolBox;
}
}
It sounds like you have a namespace issue and it looks like DrawingBoard.DrawingBoard is probably going to cause confusion. Try to rename your namespace to omit duplicate names. Use a format such as Solution.Project.Module. In your case it could be MySolution.DrawingBoard.
Related
So, I'm trying to create an accordion with dynamically loaded buttons. In the future, the title of the buttons will change depending on the details I've retrieved from somewhere. For now, what I'm trying to do is to load buttons to look like these:
I've tried doing the following below:
// Forms1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
int buttonCount = 3;
var buttons = new FontAwesome.Sharp.IconButton[buttonCount];
for (int i = 0; i < buttonCount; i++)
{
var btn = new FontAwesome.Sharp.IconButton
{
Text = "Button " + i,
TextAlign = ContentAlignment.MiddleLeft,
IconChar = FontAwesome.Sharp.IconChar.Book,
IconColor = ColorTranslator.FromHtml("#6A6A73"),
IconSize = 20,
IconFont = FontAwesome.Sharp.IconFont.Auto,
TextImageRelation = TextImageRelation.ImageBeforeText,
FlatStyle = FlatStyle.Flat
};
btn.FlatAppearance.BorderSize = 0;
btn.ForeColor = ColorTranslator.FromHtml("#6A6A73");
btn.BackColor = ColorTranslator.FromHtml("#FDFEFF");
btn.Dock = DockStyle.Top;
buttons[i] = btn;
}
flowLayoutPanel1.Controls.AddRange(buttons);
}
}
}
// Forms1.Designer.cs
namespace WindowsFormsApp1
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.SuspendLayout();
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.BackColor = System.Drawing.SystemColors.ControlLight;
this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Left;
this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Size = new System.Drawing.Size(200, 450);
this.flowLayoutPanel1.TabIndex = 0;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.flowLayoutPanel1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
}
}
Here's what it looks like after building and running the application:
What am I doing wrong?
Form1_Load method is not subscribed to Load event of your form. Body of InitializeComponent is missing following line of code.
this.Load += new System.EventHandler(this.Form1_Load);
Insert this line before this.ResumeLayout(false);. You can fix it in designer as well.
I think vertical tearing is the proper term to describe what I'm seeing but here is an screenshot that shows the issue:
I thought the DoubleBuffered property could help with this but it neither setting it on my Form or inheriting TableLayoutPanel and setting it in the constructor seem to have any effect.
I apologize for the following long block of code, but I felt I should include a complete example that demonstrates the issue. You should just be able to copy it and run it to replicate my issue:
public class ScrollTearingDemo : Form
{
private const int ROW_COUNT = 20;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new ScrollTearingDemo());
}
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
public ScrollTearingDemo()
{
InitializeComponent();
this.initializeTable();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
// Moved this here to encapsulate demo in single source file
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
//this.tableLayoutPanel1 = new BufferedTableLayoutPanel();
this.SuspendLayout();
//
// tableLayoutPanel1
//
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.tableLayoutPanel1.AutoScroll = true;
this.tableLayoutPanel1.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single;
this.tableLayoutPanel1.ColumnCount = 2;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel1.Dock = DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.TabIndex = 0;
//
// ScrollTearingDemo
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.tableLayoutPanel1);
this.DoubleBuffered = true;
this.Name = "ScrollTearingDemo";
this.Text = "ScrollTearingDemo";
this.ResumeLayout(false);
}
private void initializeTable()
{
// There is one more empty row to take up any extra space
// in the event the number of rows does not fill the table.
this.tableLayoutPanel1.RowCount = ROW_COUNT + 1;
for(int j = 0; j < ROW_COUNT;j++)
{
Label markerLabel = new Label();
markerLabel.Dock = System.Windows.Forms.DockStyle.Fill;
markerLabel.TextAlign = ContentAlignment.MiddleRight;
markerLabel.Name = "Label " + j;
markerLabel.Text = markerLabel.Name;
TextBox inputItem = new TextBox();
inputItem.Dock = DockStyle.Fill;
inputItem.Name = "Input " + j;
inputItem.Text = inputItem.Name;
inputItem.TextAlign = HorizontalAlignment.Right;
inputItem.CausesValidation = true;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.AutoSize, 25F));
this.tableLayoutPanel1.Controls.Add(markerLabel, 0, j);
this.tableLayoutPanel1.Controls.Add(inputItem, 1, j);
}
// Row style for the empty filler row.
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 0F));
this.ResumeLayout();
}
}
The project this is for is limited to C# 2.0.
Thanks to this answer https://stackoverflow.com/a/13734766/637142 I am able to know when a button is pressed or when the steering wheel is rotated. Now my question is how do I send an effect to the device? For example when I am playing a game if I crash the wheel will vibrate. How could I make the steering wheel vibrate?
I belive what I need to do is to Start() an effect (http://sharpdx.org/documentation/api/t-sharpdx-directinput-effect). The SharpDX.DirectInput.Joystick class does not seem to have a method to return me all the effects. There is a method called GetEffects but that method returns a collection of EffectInfo objects. How does a game sends commands to the joystick?
The source code is copy-pasted from here.
To use this source you need a "Force Effect file" (C:\MyEffectFile.ffe), to "play" it on the joystick.
According to this book to create the "force effect" file you need to use the "Force Editor" that came with DirectX SDK.
(the same book, alternatively, state that you can create the effect from scratch in the code... down in the answer I've found another piece of code that create and use an effect without loading it from a file :-))
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using Microsoft.DirectX;
using Microsoft.DirectX.DirectInput;
namespace JoystickProject
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private Device device = null;
private bool running = true;
private ArrayList effectList = new ArrayList();
private bool button0pressed = false;
private string joyState = "";
public bool InitializeInput()
{
// Create our joystick device
foreach(DeviceInstance di in Manager.GetDevices(DeviceClass.GameControl,
EnumDevicesFlags.AttachedOnly | EnumDevicesFlags.ForceFeeback))
{
// Pick the first attached joystick we see
device = new Device(di.InstanceGuid);
break;
}
if (device == null) // We couldn't find a joystick
return false;
device.SetDataFormat(DeviceDataFormat.Joystick);
device.SetCooperativeLevel(this, CooperativeLevelFlags.Exclusive | CooperativeLevelFlags.Background);
device.Properties.AxisModeAbsolute = true;
device.Properties.AutoCenter = false;
device.Acquire();
// Enumerate any axes
foreach(DeviceObjectInstance doi in device.Objects)
{
if ((doi.ObjectId & (int)DeviceObjectTypeFlags.Axis) != 0)
{
// We found an axis, set the range to a max of 10,000
device.Properties.SetRange(ParameterHow.ById,
doi.ObjectId, new InputRange(-5000, 5000));
}
}
// Load our feedback file
EffectList effects = null;
effects = device.GetEffects(#"C:\MyEffectFile.ffe",
FileEffectsFlags.ModifyIfNeeded);
foreach(FileEffect fe in effects)
{
EffectObject myEffect = new EffectObject(fe.EffectGuid, fe.EffectStruct,
device);
myEffect.Download();
effectList.Add(myEffect);
}
while(running)
{
UpdateInputState();
Application.DoEvents();
}
return true;
}
private void PlayEffects()
{
// See if our effects are playing.
foreach(EffectObject myEffect in effectList)
{
//if (button0pressed == true)
//{
//MessageBox.Show("Button Pressed.");
// myEffect.Start(1, EffectStartFlags.NoDownload);
//}
if (!myEffect.EffectStatus.Playing)
{
// If not, play them
myEffect.Start(1, EffectStartFlags.NoDownload);
}
}
//button0pressed = true;
}
protected override void OnClosed(EventArgs e)
{
running = false;
}
private void UpdateInputState()
{
PlayEffects();
// Check the joystick state
JoystickState state = device.CurrentJoystickState;
device.Poll();
joyState = "Using JoystickState: \r\n";
joyState += device.Properties.ProductName;
joyState += "\n";
joyState += device.ForceFeedbackState;
joyState += "\n";
joyState += state.ToString();
byte[] buttons = state.GetButtons();
for(int i = 0; i < buttons.Length; i++)
joyState += string.Format("Button {0} {1}\r\n", i, buttons[i] != 0 ? "Pressed" : "Not Pressed");
label1.Text = joyState;
//if(buttons[0] != 0)
//button0pressed = true;
}
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.BackColor = System.Drawing.SystemColors.ActiveCaptionText;
this.label1.Location = new System.Drawing.Point(8, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(272, 488);
this.label1.TabIndex = 0;
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.BackColor = System.Drawing.SystemColors.ControlText;
this.ClientSize = new System.Drawing.Size(288, 502);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.label1});
this.Name = "Form1";
this.Text = "Joystick Stuff";
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
using (Form1 frm = new Form1())
{
frm.Show();
if (!frm.InitializeInput())
MessageBox.Show("Couldn't find a joystick.");
}
}
}
}
I've just found here another piece of code that maybe useful.
This sample seem to create the effect from scratch, so you shouldn't need an "effect file".
DeviceList xDeviceList = Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly);
DeviceInstance someDeviceInstance;
foreach (DeviceInstance deviceInstance in xDeviceList)
{
someDeviceInstance = deviceInstance;
break;
}
Device someDevice = new Device(someDeviceInstance.InstanceGuid);
someDevice.SetCooperativeLevel(this.Handle, CooperativeLevelFlags.Exclusive | CooperativeLevelFlags.Background);
int[] axis = new int[0];
foreach (DeviceObjectInstance doi in someDevice.Objects)
{
if((doi.Flags & (int)ObjectInstanceFlags.Actuator) != 0)
{
axis = new int[axis.Length + 1];
axis[axis.Length - 1] = doi.Offset;
}
}
someDevice.Acquire();
Effect effect = new Effect();
effect.SetDirection(new int[axis.Length]);
effect.SetAxes(new int[axis.Length]);
effect.ConditionStruct = new Condition[axis.Length];
effect.Flags = EffectFlags.Cartesian | EffectFlags.ObjectOffsets;
effect.Duration = int.MaxValue;
effect.SamplePeriod = 0;
effect.Gain = 10000;
effect.TriggerButton = (int)Microsoft.DirectX.DirectInput.Button.NoTrigger;
effect.TriggerRepeatInterval = 0;
effect.UsesEnvelope = false;
effect.EffectType = Microsoft.DirectX.DirectInput.EffectType.ConstantForce;
effect.StartDelay = 0;
effect.Constant = new Microsoft.DirectX.DirectInput.ConstantForce();
effect.Constant.Magnitude = -5000;
EffectObject effectObject = null;
foreach (EffectInformation ei in someDevice.GetEffects(EffectType.ConstantForce))
{
effectObject = new EffectObject(ei.EffectGuid, effect, someDevice);
}
effectObject.SetParameters(effect, EffectParameterFlags.Start );
And here is another link then may be useful Force feedback sample
I'm trying to implement a C# drag and drop row-reorder with a listbox. I've come across some snippets of code on the internet but none seem to be working with my needs.
I want you to show me an example code of how to move rows in ListBox.
Thanks!
The moving of rows is done in methods "listBox1_MouseUp and listBox1_MouseDown.
Use view code to change this:
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 Calculator
{
public partial class ComponentMover : Form
{
private Control trackedControl;
private int gridWidth = 100, gridHeight = 20;
private int row;
public ComponentMover()
{
this.InitializeComponent();
this.InitializeDynamic();
}
void draggable_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (this.trackedControl == null)
this.trackedControl = (Control)sender;
}
void draggable_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (this.trackedControl != null)
{
int x = e.X + this.trackedControl.Location.X;
int y = e.Y + this.trackedControl.Location.Y;
Point moved = new Point(x - x % this.gridWidth, y - y % this.gridHeight);
Console.WriteLine(e.X + ", " + e.Y + ", " + ", " + moved.X + ", " + moved.Y);
if (moved != this.trackedControl.Location)
this.trackedControl.Location = moved;
}
}
void draggable_MouseUp(object sender, MouseEventArgs e)
{
this.trackedControl = null;
}
private void AddDragListeners(Control draggable)
{
draggable.MouseDown += new MouseEventHandler(draggable_MouseDown);
draggable.MouseMove += new MouseEventHandler(draggable_MouseMove);
draggable.MouseUp += new MouseEventHandler(draggable_MouseUp);
}
}
}
Designer code:
namespace Calculator
{
// Designer code.
partial class ComponentMover
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeDynamic()
{
this.AddDragListeners(button1);
this.AddDragListeners(button4);
this.AddDragListeners(domainUpDown1);
this.AddDragListeners(textBox1);
this.AddDragListeners(checkBox1);
this.AddDragListeners(radioButton1);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.domainUpDown1 = new System.Windows.Forms.DomainUpDown();
this.textBox1 = new System.Windows.Forms.TextBox();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.radioButton1 = new System.Windows.Forms.RadioButton();
this.listBox1 = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(13, 13);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
//
// button4
//
this.button4.Location = new System.Drawing.Point(177, 43);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(75, 23);
this.button4.TabIndex = 3;
this.button4.Text = "button4";
this.button4.UseVisualStyleBackColor = true;
//
// domainUpDown1
//
this.domainUpDown1.Location = new System.Drawing.Point(95, 42);
this.domainUpDown1.Name = "domainUpDown1";
this.domainUpDown1.Size = new System.Drawing.Size(74, 20);
this.domainUpDown1.TabIndex = 4;
this.domainUpDown1.Text = "domainUpDown1";
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(177, 72);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(100, 20);
this.textBox1.TabIndex = 5;
//
// checkBox1
//
this.checkBox1.AutoSize = true;
this.checkBox1.Location = new System.Drawing.Point(281, 13);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(80, 17);
this.checkBox1.TabIndex = 6;
this.checkBox1.Text = "checkBox1";
this.checkBox1.UseVisualStyleBackColor = true;
//
// radioButton1
//
this.radioButton1.AutoSize = true;
this.radioButton1.Location = new System.Drawing.Point(366, 42);
this.radioButton1.Name = "radioButton1";
this.radioButton1.Size = new System.Drawing.Size(85, 17);
this.radioButton1.TabIndex = 7;
this.radioButton1.TabStop = true;
this.radioButton1.Text = "radioButton1";
this.radioButton1.UseVisualStyleBackColor = true;
//
// listBox1
//
this.listBox1.FormattingEnabled = true;
this.listBox1.Items.AddRange(new object[] {
"word1",
"word2",
"word3"});
this.listBox1.Location = new System.Drawing.Point(13, 42);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(76, 82);
this.listBox1.TabIndex = 8;
this.listBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(listBox1_MouseDown);
this.listBox1.MouseUp += new System.Windows.Forms.MouseEventHandler(listBox1_MouseUp);
//
// ComponentMover
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(485, 159);
this.Controls.Add(this.listBox1);
this.Controls.Add(this.radioButton1);
this.Controls.Add(this.checkBox1);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.domainUpDown1);
this.Controls.Add(this.button4);
this.Controls.Add(this.button1);
this.Name = "ComponentMover";
this.Text = "ComponentMover";
this.ResumeLayout(false);
this.PerformLayout();
}
void listBox1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
System.Windows.Forms.ListBox list = (System.Windows.Forms.ListBox)sender;
int swap = list.SelectedIndex;
if(swap != this.row)
{
string temp = (string)list.Items[this.row];
list.Items[this.row] = list.Items[swap];
list.Items[swap] = temp;
}
}
void listBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
this.row = ((System.Windows.Forms.ListBox)sender).SelectedIndex;
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.DomainUpDown domainUpDown1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.CheckBox checkBox1;
private System.Windows.Forms.RadioButton radioButton1;
private System.Windows.Forms.ListBox listBox1;
}
}
I have a simple Windows Forms application which is used to calculate the solutions to a quadratic equation. Since it requires some values to be inputted into three different textboxes and then upon clicking a "Calculate" button, makes some calculations with the inputted values. Upon testing the application, and clicking the "Calculate" button prior to inputting any values, I get a Input string was not in a correct format This is due to trying to parse a non-existent value. Is there any way to avoid this? I tried to construct a conditional based on if the button was clicked and there was no values in the textboxes, to not do anything, but that didn't quite work. Here is my designer code:
namespace QuadraticSolver
{
partial class QuadraticSolver
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.lblPrompt = new System.Windows.Forms.Label();
this.lblA = new System.Windows.Forms.Label();
this.lblB = new System.Windows.Forms.Label();
this.lblC = new System.Windows.Forms.Label();
this.txtA = new System.Windows.Forms.TextBox();
this.txtB = new System.Windows.Forms.TextBox();
this.txtC = new System.Windows.Forms.TextBox();
this.btnCalculate = new System.Windows.Forms.Button();
this.lblSolutions = new System.Windows.Forms.Label();
this.txtSolution1 = new System.Windows.Forms.TextBox();
this.txtSolution2 = new System.Windows.Forms.TextBox();
this.chkImaginary = new System.Windows.Forms.CheckBox();
this.SuspendLayout();
//
// lblPrompt
//
this.lblPrompt.AutoSize = true;
this.lblPrompt.Location = new System.Drawing.Point(12, 9);
this.lblPrompt.Name = "lblPrompt";
this.lblPrompt.Size = new System.Drawing.Size(92, 13);
this.lblPrompt.TabIndex = 0;
this.lblPrompt.Text = "Enter Your Values";
//
// lblA
//
this.lblA.AutoSize = true;
this.lblA.Location = new System.Drawing.Point(12, 49);
this.lblA.Name = "lblA";
this.lblA.Size = new System.Drawing.Size(16, 13);
this.lblA.TabIndex = 1;
this.lblA.Text = "a:";
//
// lblB
//
this.lblB.AutoSize = true;
this.lblB.Location = new System.Drawing.Point(12, 85);
this.lblB.Name = "lblB";
this.lblB.Size = new System.Drawing.Size(16, 13);
this.lblB.TabIndex = 2;
this.lblB.Text = "b:";
//
// lblC
//
this.lblC.AutoSize = true;
this.lblC.Location = new System.Drawing.Point(12, 122);
this.lblC.Name = "lblC";
this.lblC.Size = new System.Drawing.Size(16, 13);
this.lblC.TabIndex = 3;
this.lblC.Text = "c:";
//
// txtA
//
this.txtA.Location = new System.Drawing.Point(34, 46);
this.txtA.Name = "txtA";
this.txtA.Size = new System.Drawing.Size(360, 20);
this.txtA.TabIndex = 4;
//
// txtB
//
this.txtB.Location = new System.Drawing.Point(34, 82);
this.txtB.Name = "txtB";
this.txtB.Size = new System.Drawing.Size(360, 20);
this.txtB.TabIndex = 5;
//
// txtC
//
this.txtC.Location = new System.Drawing.Point(34, 122);
this.txtC.Name = "txtC";
this.txtC.Size = new System.Drawing.Size(360, 20);
this.txtC.TabIndex = 6;
//
// btnCalculate
//
this.btnCalculate.Location = new System.Drawing.Point(175, 154);
this.btnCalculate.Name = "btnCalculate";
this.btnCalculate.Size = new System.Drawing.Size(75, 23);
this.btnCalculate.TabIndex = 7;
this.btnCalculate.Text = "Calculate!";
this.btnCalculate.UseVisualStyleBackColor = true;
this.btnCalculate.Click += new System.EventHandler(this.btnCalculate_Click);
//
// lblSolutions
//
this.lblSolutions.AutoSize = true;
this.lblSolutions.Location = new System.Drawing.Point(31, 226);
this.lblSolutions.Name = "lblSolutions";
this.lblSolutions.Size = new System.Drawing.Size(53, 13);
this.lblSolutions.TabIndex = 8;
this.lblSolutions.Text = "Solutions:";
//
// txtSolution1
//
this.txtSolution1.Location = new System.Drawing.Point(34, 242);
this.txtSolution1.Name = "txtSolution1";
this.txtSolution1.ReadOnly = true;
this.txtSolution1.Size = new System.Drawing.Size(165, 20);
this.txtSolution1.TabIndex = 9;
//
// txtSolution2
//
this.txtSolution2.Location = new System.Drawing.Point(222, 242);
this.txtSolution2.Name = "txtSolution2";
this.txtSolution2.ReadOnly = true;
this.txtSolution2.Size = new System.Drawing.Size(172, 20);
this.txtSolution2.TabIndex = 10;
//
// chkImaginary
//
this.chkImaginary.AutoSize = true;
this.chkImaginary.Location = new System.Drawing.Point(33, 189);
this.chkImaginary.Name = "chkImaginary";
this.chkImaginary.Size = new System.Drawing.Size(71, 17);
this.chkImaginary.TabIndex = 11;
this.chkImaginary.Text = "Imaginary";
this.chkImaginary.UseVisualStyleBackColor = true;
//
// QuadraticSolver
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(406, 285);
this.Controls.Add(this.chkImaginary);
this.Controls.Add(this.txtSolution2);
this.Controls.Add(this.txtSolution1);
this.Controls.Add(this.lblSolutions);
this.Controls.Add(this.btnCalculate);
this.Controls.Add(this.txtC);
this.Controls.Add(this.txtB);
this.Controls.Add(this.txtA);
this.Controls.Add(this.lblC);
this.Controls.Add(this.lblB);
this.Controls.Add(this.lblA);
this.Controls.Add(this.lblPrompt);
this.Name = "QuadraticSolver";
this.Text = "Quadratic Solver";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lblPrompt;
private System.Windows.Forms.Label lblA;
private System.Windows.Forms.Label lblB;
private System.Windows.Forms.Label lblC;
private System.Windows.Forms.TextBox txtA;
private System.Windows.Forms.TextBox txtB;
private System.Windows.Forms.TextBox txtC;
private System.Windows.Forms.Button btnCalculate;
private System.Windows.Forms.Label lblSolutions;
private System.Windows.Forms.TextBox txtSolution1;
private System.Windows.Forms.TextBox txtSolution2;
private System.Windows.Forms.CheckBox chkImaginary;
}
}
Here is my program's code which does the actual data manipulation:
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 QuadraticSolver
{
public partial class QuadraticSolver : Form
{
public QuadraticSolver()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
if (txtA.Text == "" || txtB.Text == "" || txtC.Text == "")
{
string stringSol = "Please enter some values!";
txtSolution1.Text = stringSol;
txtSolution2.Text = stringSol;
}
double aValue = double.Parse(txtA.Text);
double bValue = double.Parse(txtB.Text);
double cValue = double.Parse(txtC.Text);
double solution1Double, solution2Double;
//Quadratic Formula: x = (-b +- sqrt(b^2 - 4ac)) / 2a
//Calculate discriminant
double insideSquareRoot = (bValue * bValue) - 4 * aValue * cValue;
if (insideSquareRoot < 0)
{
//No real solution
solution1Double = Double.NaN;
solution2Double = Double.NaN;
txtSolution1.Text = solution1Double.ToString();
txtSolution2.Text = solution2Double.ToString();
}
else if (insideSquareRoot == 0)
{
//One real solution
double sqrtOneSolution = Math.Sqrt(insideSquareRoot);
solution1Double = (-bValue + sqrtOneSolution) / (2 * aValue);
solution2Double = double.NaN;
txtSolution1.Text = solution1Double.ToString();
txtSolution2.Text = solution2Double.ToString();
}
else if (insideSquareRoot > 0)
{
//Two real solutions
double sqrtTwoSolutions = Math.Sqrt(insideSquareRoot);
solution1Double = (-bValue + sqrtTwoSolutions) / (2 * aValue);
solution2Double = (-bValue - sqrtTwoSolutions) / (2 * aValue);
txtSolution1.Text = solution1Double.ToString();
txtSolution2.Text = solution2Double.ToString();
}
}
}
}
You can use the double.TryParse method.
This is better than checking for == "" since it will tell you that you can not parse "Hello" as a double too.
You also need to return from the event handler if one of the TryParse returns false.
You may consider using a NumericUpDown control instead. You are guaranteed the input from this control will be numeric. All the code that is required is then:
double userNumber = myNumUpDown.Value;
You can even restrict the number input to ensure it falls within your defined range
myNumUpDown.Minimum = 300;
myNumUpDown.Maximum = 500;
Along with many other things. Finally, it even comes with up/down GUI controls so your users can be super lazy and enter the number with their mouse!
You can try this format,
replace the textbox1 with your textbox name.
int a = textbox1.Text != "" ? Convert.ToInt32(textbox1.Text) : 0;
int b = textbox2.Text != "" ? Convert.ToInt32(textbox2.Text) : 0;
int total = a + b;
you can reassign the result this way:
textbox3 = total.toString();
if (txtA.Text == "" || txtB.Text == "" || txtC.Text == "")
{
string stringSol = "Please enter some values!";
txtSolution1.Text = stringSol;
txtSolution2.Text = stringSol;
return;
}