Sentence Builder app in c# - c#

I am trying to complete an assignment for a new C# class using VS doing a windows form application (all new to me, code and all). We were assigned to creating a sentence builder with various words that were buttons; and then when the app runs, the user could click the buttons to build a sentence; which is then shown in the Label control.
Well, I have the form built, and from other info I found on this site for a similar question; have made it to this point. BUT my problem is - my instructor said we should be concatenating the results within the Label output, but FIRST I dont' know how to do that with someone just randomly clicking letters or words**(with what we have learned so far).
I got it to run with the following code(without concatenationin Label); except the "spaceButton" event puts IN the text of "(Space)" because that is it's text... I changed it to " " in the code and If I click on it running, it will now put in spaces but changes the text in the running app to a blank button. I don't know how to fix that.
I have had this instructor before and while I might be able to work around the concatenation in the "sentenceOutputLabel" - I might very well get a zero because I didn't concatenate in the output label.
Laura
Here is all the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Sentence_Builder
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void upperCaseAButton_Click(object sender, EventArgs e)
{
string output;
output = upperCaseAButton.Text;
sentenceOutputLabel.Text += output;
}
private void lowerCaseAButton_Click(object sender, EventArgs e)
{
string output;
output = lowerCaseAButton.Text;
sentenceOutputLabel.Text += output;
}
private void upperCaseAnButton_Click(object sender, EventArgs e)
{
string output;
output = upperCaseAnButton.Text;
sentenceOutputLabel.Text += output;
}
private void lowerCaseAnButton_Click(object sender, EventArgs e)
{
string output;
output = lowerCaseAnButton.Text;
sentenceOutputLabel.Text += output;
}
private void upperCaseTheButton_Click(object sender, EventArgs e)
{
string output;
output = upperCaseTheButton.Text;
sentenceOutputLabel.Text += output;
}
private void lowerCaseTheButton_Click(object sender, EventArgs e)
{
string output;
output = lowerCaseTheButton.Text;
sentenceOutputLabel.Text += output;
}
private void manWordButton_Click(object sender, EventArgs e)
{
string output;
output = manWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void womanWordButton_Click(object sender, EventArgs e)
{
string output;
output = womanWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void dogWordButton_Click(object sender, EventArgs e)
{
string output;
output = dogWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void catWordButton_Click(object sender, EventArgs e)
{
string output;
output = catWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void carWordButton_Click(object sender, EventArgs e)
{
string output;
output = carWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void bicycleWordButton_Click(object sender, EventArgs e)
{
string output;
output = bicycleWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void beautifulWordButton_Click(object sender, EventArgs e)
{
string output;
output = beautifulWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void bigWordButton_Click(object sender, EventArgs e)
{
string output;
output = bigWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void smallWordButton_Click(object sender, EventArgs e)
{
string output;
output = smallWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void strangeWordButton_Click(object sender, EventArgs e)
{
string output;
output = strangeWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void lookedAtWordButton_Click(object sender, EventArgs e)
{
string output;
output = lookedAtWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void rodeWordButton_Click(object sender, EventArgs e)
{
string output;
output = rodeWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void spokeToWordButton_Click(object sender, EventArgs e)
{
string output;
output = spokeToWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void laughedAtWordButton_Click(object sender, EventArgs e)
{
string output;
output = laughedAtWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void droveWordButton_Click(object sender, EventArgs e)
{
string output;
output = droveWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void spaceButton_Click(object sender, EventArgs e)
{
string output;
output = spaceButton.Text = " ";
sentenceOutputLabel.Text += output;
}
private void periodButton_Click(object sender, EventArgs e)
{
string output;
output = periodButton.Text;
sentenceOutputLabel.Text += output;
}
private void exclamButton_Click(object sender, EventArgs e)
{
string output;
output = exclamButton.Text;
sentenceOutputLabel.Text += output;
}
/ I DON'T EVEN KNOW WHAT I NEED THIS below FOR NOW
private void sentenceOutputLabel_Click(object sender, EventArgs e)
{
//string output;
// sentenceOutputLabel.Text = sentenceOutputLabel.Text;
}
private void clearButton_Click(object sender, EventArgs e)
{
sentenceOutputLabel.Text = "";
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}`

If I understood the assignment description correctly, this is what I would do:
using System;
using System.Windows.Forms;
namespace StringBuilder
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void btnInput_Click(object sender, EventArgs e)
{
Button button = sender as Button;
if (button != null)
{
if (button.Text == "Space")
lblOutput.Text += " ";
else
lblOutput.Text += button.Text;
}
}
}
}
With this code, every single button can be assigned to the btnInput_Click event handler, and lblOutput is just the output.

I think the solution might just be so simple, it didn't occur to you it was allowed:
private void spaceButton_Click(object sender, EventArgs e)
{
string output;
output = " "; // don't necessarily have to use the Text property of the button ...
sentenceOutputLabel.Text += output;
}

I won't give you the solution, but maybe I can provide a bit more guidance and assist in the learning process.
First off, the value you're concatenating doesn't have to come from the button itself. The way you have it setup, each button has a designated event (*_CLick(object,EventArgs)). If you already know what button's being click, using that button's .Text isn't really necessary. So, feel free to use the desired result within this method and not stick to the button's .Text.
Also, based on what you've described, you're fulfilling the concatenation part (you seem reluctant to believe this). Every time you append (+=) the clicked item's text to the label's current value you're concatenating (just C# is doing to work for you).
To take it a step further though, each control has a Tag property. This allows you to specify metadata and bind it to that specific control. You may want to consider specifying the desired output (with regards to what's added to the final label) as the button's tag, then appending that value (over the button's Text). You could also re-use a single *_Click(object,EventArgs) method and just concatenate ((Button)sender).Tag.

Here's an example of how you can use a common click event, and how you can use the Tag property to store the value to be added to the label (which may be different than the value displayed on the Button text).
I'm dynamically adding the buttons, which you wouldn't have to do, but this way you can copy/past the code into a new project and run it. Hopefully it is instructive, but not something you would turn in as your own work.
public partial class Form1 : Form
{
Label sentenceOutputLabel = new Label();
public Form1()
{
InitializeComponent();
int padding = 10;
// Add a label to the form
sentenceOutputLabel.Width = ClientSize.Width - (padding * 2);
sentenceOutputLabel.Top = padding;
sentenceOutputLabel.Left = padding;
sentenceOutputLabel.BorderStyle = BorderStyle.FixedSingle;
Controls.Add(sentenceOutputLabel);
// List of words that, for each one, we'll add a button to the form
// Note that some words have two parts: the first part is the button
// text, followed by a colon, then followed by the tag text. We split
// these out later, when assigning button properties
var words = new List<string>
{
"A", "a", "An", "an", "The", "the", "man", "woman", "dog", "cat",
"car", "bicycle", "beautiful", "big", "small", "strange", "looked",
"rode", "spoke", "laughed at", "drove", "[space]: ", "[period]:.",
"[exclamation]:!"
};
// Get the width of the longest word so we size the buttons accordingly
int width;
using (Graphics cg = CreateGraphics())
{
width = Convert.ToInt32(cg.MeasureString(words.Aggregate("", (max, cur) =>
(cg.MeasureString(max, new Button().Font).Width) >
(cg.MeasureString(cur, new Button().Font).Width)
? max
: cur), new Button().Font).Width);
}
// Add the buttons to the form, spacing them evenly
int left = padding;
int top = sentenceOutputLabel.Bottom + padding;
int bottomOfLastButton = 0;
foreach (var word in words)
{
// For some words, we have a colon-separated symbol that we
// will use instead of the word (like 'space', for example)
// So we store the symbol in the 'Tag' property and the word
// in the text property.
var wordParts = word.Split(':');
var text = wordParts[0];
var tag = wordParts.Length > 1 ? wordParts[1] : text;
var button = new Button
{
Text = text,
Tag = tag,
Left = left,
Top = top,
Width = width,
Visible = true
};
// HERE WE ADD A COMMON CLICK EVENT
button.Click += wordButton_Click;
// Add the button to the form
Controls.Add(button);
// Reset left and top if we're going past the width of the form
left += (width + padding);
if (left + width + padding > ClientSize.Width)
{
left = padding;
top += button.Height + padding;
}
bottomOfLastButton = button.Bottom;
}
// Add a clear and exit button
var exitButton = new Button
{
Top = bottomOfLastButton + (padding * 2),
Text = "Exit",
Left = ClientSize.Width - padding - width,
Width = width
};
exitButton.Click += exitButton_Click;
var clearButton = new Button
{
Top = bottomOfLastButton + (padding * 2),
Text = "Clear",
Left = exitButton.Left - padding - width,
Width = width
};
clearButton.Click += clearButton_Click;
Controls.Add(exitButton);
Controls.Add(clearButton);
}
void clearButton_Click(object sender, EventArgs e)
{
sentenceOutputLabel.Text = "";
}
void exitButton_Click(object sender, EventArgs e)
{
Close();
}
void wordButton_Click(object sender, EventArgs e)
{
var wordButton = sender as Button;
if (wordButton != null)
{
sentenceOutputLabel.Text += wordButton.Tag;
}
}
}

Related

TextBox to Display Mouse Clicks

my problem is that i'm trying to have a textbox display the number of times that I have clicked on the screen. I'm having the issue of not being able to take the textbox's text and convert it to a int. Thanks!
{
public partial class Form1 : Form
{
Random rand = new Random();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
button1.Location = new Point(rand.Next(0, 750), rand.Next(0, 750));
}
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Right)
{
int mouseclick = 0;
textBox1.Text = Int32.Parse(mouseclick);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
Try the following changes:
{
public partial class Form1 : Form
{
Random rand = new Random();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
button1.Location = new Point(rand.Next(0, 750), rand.Next(0, 750));
}
int mouseclick = 0;
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Right)
{
mouseclick++;
}
textBox1.Text = mouseclick.ToString();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
I have moved mouseclick out of the event so that it can maintain its value and i am only incrementing mouseclick if the user clicks with the left mouse button.
The textbox datatype is a string, but its assignment is a number being parsed as a number. Perhaps the following example would be helpful.
string mouseclick = "0";
int intMouseClick = Int32.Parse(mouseclick);
textBox1.Text = intMouseClick.ToString();
You tried to convert an int into string bei using Int32.Parse(...).
But this function does the reverse conversion. It converts a string to an int.
First off, you are telling the program to set mouseclicks to 0 every single time it is clicked. You might instead want the code to read:
if (e.Button != MouseButtons.Right)
{
int mouseclick = mouseclick + 1;
textBox1.Text = Int32.Parse(mouseclick);
}
or move the int out of the if statement and just do mouseclick++;
On top of that, if you are trying to set the text boxes text, you can do it much easier by just doing this:
textBox1.Text = mouseclick.ToString();

GMap.NET and polygon names not getting passed from second form

So basically im trying to make polygons with a name entered from Form2, called Apgabala_nosaukums (it's in my language, sorry for that). I have been trying to debug this, first 2 times the name entered from Form2 did get read and i was able to see that the name was added to the Polygon. But now it is not getting in the fromVisibleChanged anymore, ending in that the polygon is not getting name. Meaning that I cannot get the bool to true, so I could add 4 points and make a square or rectangle area out of them. Any ideas? Basically the btnAdd_Click function is not working properly, rest is working fine. Any ideas?
Form1 (Main form):
namespace GMapTest
{
public partial class Form1 : Form
{
GMapOverlay polygons = new GMapOverlay("polygons");
List<PointLatLng> points = new List<PointLatLng>();
double lat;
double lng;
int clicks = 0;
bool add = false;
string nosaukums;
public Form1()
{
InitializeComponent();
}
private void gMapControl1_Load(object sender, EventArgs e)
{
gmap.MapProvider = GoogleMapProvider.Instance;
GMaps.Instance.Mode = AccessMode.ServerOnly;
gmap.SetPositionByKeywords("Riga, Latvia");
gmap.ShowCenter = false;
gmap.Overlays.Add(polygons);
}
private void gmap_MouseDown(object sender, MouseEventArgs e)
{
if (add == true)
{
if (e.Button == MouseButtons.Left)
{
lat = gmap.FromLocalToLatLng(e.X, e.Y).Lat;
lng = gmap.FromLocalToLatLng(e.X, e.Y).Lng;
clicks += 1;
points.Add(new PointLatLng(lat, lng));
}
if (clicks == 4)
{
GMapPolygon polygon = new GMapPolygon(points, nosaukums);
polygons.Polygons.Add(polygon);
clicks = 0;
points.Clear();
add = false;
}
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
Apgabala_nosaukums addName = new Apgabala_nosaukums();
addName.ShowDialog();
addName.VisibleChanged += formVisibleChanged;
if (nosaukums != null)
{
this.add = true;
}
}
private void formVisibleChanged(object sender, EventArgs e)
{
Apgabala_nosaukums frm = (Apgabala_nosaukums)sender;
if (!frm.Visible)
{
this.nosaukums = (frm.ReturnText);
frm.Dispose();
}
}
}
}
Form2 (Apgabala_nosaukums):
namespace GMapTest
{
public partial class Apgabala_nosaukums : Form
{
public string ReturnText { get; set; }
public Apgabala_nosaukums()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.ReturnText = this.txtName.Text;
this.Visible = false;
}
}
}
The problem is in your btnAdd_Click function. When you call ShowDialog your other form is shown and the next line, addName.VisibleChanged += formVisibleChanged; isn't called until you close the new form. ShowDialog shows the form modally, you can't interact with the parent until you close the new form.
There are a couple ways you could fix this.
1) Subscribe to the VisibleChanged event before you show the form,
addName.VisibleChanged += formVisibleChanged;
addName.ShowDialog();
2) Call addName.Show() instead of addName.ShowDialog(). This shows the form in a non-modal way. The event will get subscribed to because execution continues in btnAdd_Click before the new form is closed. But, the parent form will be interactable, not sure if this is desired or not.
3) You could also get rid of the VisibleChanged event stuff and instead do ShowDialog and read the property after. This is what I'd recommend from seeing the code.
private void btnAdd_Click(object sender, EventArgs e)
{
Apgabala_nosaukums addName = new Apgabala_nosaukums();
addName.ShowDialog();
this.nosaukums = addName.ReturnText;
addName.Dispose();
}

Text file breaking lines up when opening it using ReadAllLines() c#

I've created a program to make bug templates and am having a problem with text not saving correctly.
I have a text file called TemplateTexts that holds all the text for each template, a template looks like this -
REQUIREMENTS
- Example
ADDITIONAL REQUIREMENTS
- Example
- Example
-----COPY BELOW THIS LINE-----
When the program closes it copies all of that into 1 line of a text file. (looks like this)
REQUIREMENTS- Example ADDITIONAL REQUIREMENTS- Example - Example-----COPY BELOW THIS LINE-----
The text file contains 20 lines of templates. The template is saved as 1 line of text into the text file, but when I go to open the program again, it turns that 1 line of text into multiple lines of text like how it is displayed in the first example.
Any idea why this might be happening? or is there a better way to save each template into a text file, possibly by separating it with flags or something?
Here's the code to my program:
public partial class Form1 : Form
{
static String buttonNamesPath = AppDomain.CurrentDomain.BaseDirectory + "/ButtonNames.txt";
String[] ButtonNames = System.IO.File.ReadAllLines(buttonNamesPath);
static String buttonTextPath = AppDomain.CurrentDomain.BaseDirectory + "/ButtonText.txt";
String[] ButtonText = System.IO.File.ReadAllLines(buttonTextPath);
private void SetupTextField()
{
comboBox1.Items.Clear();
comboBox2.Items.Clear();
for (int i = 0; i < ButtonNames.Length; i++)
{
comboBox1.Items.Insert(i, ButtonNames[i]);
comboBox2.Items.Insert(i, ButtonNames[i]);
}
}
public Form1()
{
InitializeComponent();
this.FormClosing += this.Form1_FormClosing;
}
private void Form1_Load(object sender, EventArgs e)
{
SetupTextField();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string comboBoxText;
comboBoxText = comboBox1.SelectedItem.ToString();
int strNumber;
int strIndex = 0;
for (strNumber = 0; strNumber < ButtonNames.Length; strNumber++)
{
strIndex = Array.FindIndex(ButtonNames, x => x.Contains(comboBoxText));
if (strIndex >= 0)
break;
}
ButtonNames[strIndex] = textBox1.Text;
ButtonText[strIndex] = richTextBox2.Text;
SetupTextField();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
System.IO.File.WriteAllLines(buttonNamesPath, ButtonNames);
System.IO.File.WriteAllLines(buttonTextPath, ButtonText);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
richTextBox1.Text = "";
}
private void button2_Click(object sender, EventArgs e)
{
string comboBoxText;
comboBoxText = comboBox2.SelectedItem.ToString();
int strNumber;
int strIndex = 0;
for (strNumber = 0; strNumber < ButtonNames.Length; strNumber++)
{
strIndex = Array.FindIndex(ButtonNames, x => x.Contains(comboBoxText));
if (strIndex >= 0)
break;
}
richTextBox1.Text = ButtonText[strIndex];
}
private void label3_Click(object sender, EventArgs e)
{
}
}
I also have 2 text files called ButtonNames.txt and ButtonText.txt
When you ask the RichTextBox for its Text property, it converts the rich text it contains internally to a plain-text string, and apparently by default it uses \n to translate line endings. Notepad doesn't recognize \n as a line ending (because it's looking for the official Windows line ending of \r\n), so it displays everything on one line. If you want to save with \r\n for line endings, use string.Replace on the result of RichTextBox.Text to replace \n with \r\n.
See this question and its answers for more details:
RichTextBox Newline Conversion?

How to call a button click event when i click another button in c#

I have 2 buttons in my win app.
Button1 do a task :
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Value = 0;
String[] a = textBox7.Text.Split('#');
progressBar1.Maximum = a.Length;
for (var i = 0; i <= a.GetUpperBound(0); i++)
{
ansh.Close();
progressBar1.Value++;
}
}
Button 2 do following
private void button2_Click(object sender, EventArgs e)
{
foreach (string item in listBox2.Items)
textBox7.Text += item.Contains("#") ? string.Format("{0}#", item.Split('#')[0]) : string.Empty;
}
I just want to use just one button for two events.
But I want the event of button2 to be called before event that was called by button1.
Means I want to use just one button instead of button 1 and 2.and when I click I want first thing to be done is getting listbox items in a textbox.
{
foreach (string item in listBox2.Items)
textBox7.Text += item.Contains("#") ? string.Format("{0}#", item.Split('#')[0]) : string.Empty;
}
and then the event of starting progress bar and closing connection x.
progressBar1.Value = 0;
String[] a = textBox7.Text.Split('#');
progressBar1.Maximum = a.Length;
for (var i = 0; i <= a.GetUpperBound(0); i++)
{
ansh.Close();
progressBar1.Value++;
}
You can use PerformClick method of button object
Button button1 = new Button(), button2 = new Button();
button1.Click += new EventHandler(button1_Click);
button2.Click += new EventHandler(button2_Click);
void button1_Click(object sender, EventArgs e)
{
/* .................... */
button2.PerformClick(); //Simulate click on button2
/* .................... */
}
void button2_Click(object sender, EventArgs e)
{
/* .................... */
}
I'd suggest removing the logic from behind the click events into separate methods.
private void MethodOne()
{
progressBar1.Value = 0;
String[] a = textBox7.Text.Split('#');
progressBar1.Maximum = a.Length;
for (var i = 0; i <= a.GetUpperBound(0); i++)
{
ansh.Close();
progressBar1.Value++;
}
}
private void MethodTwo()
{
foreach (string item in listBox2.Items)
textBox7.Text += item.Contains("#") ? string.Format("{0}#", item.Split('#')[0]) : string.Empty;
}
private void button1_Click(object sender, EventArgs e)
{
MethodTwo();
MethodOne();
}
private void button2_Click(object sender, EventArgs e)
{
MethodTwo();
}
In my experience, it's easier to maintain and test this way. Having different controls' events all calling each other makes it tougher to follow the logic.
You can trigger the click event of Button2 manually:
private void button1_Click(object sender, EventArgs e)
{
button2_Click(sender,e);
...
}
Just in case you neen events:
Button1.click += method1;
Button1.click += method2;
void method1(object sender, EventArgs e)
{
// do your stuff
}
void method2(object sender, EventArgs e)
{
// do your stuff
}

How to retrieve text from datagridview cell and displayit in the button?

How can I retrieve text from DataGridView Cell and displayit on the button.
Basically I have two forms on my project (Form1 & Form2).
-In Form1 I have two buttons (Starter & Main). Both these buttons on click event, they call database sql-query and genereate into form the records as buttons.
-In Form2 I have a button (Starter). Also this button on click event calls database sql-query and generates records in DatagridView.
Now in Form2 when I double_click inside the cell under the Quantity In Stock column, a dialog-box pops up and allows me to enter the number in to that particular cell. Lets say Row-1:
Soup Starter 10 <Allways On Stock>
So based on this, how can I take the value of that cell = 10 and dispalyit on the bottom-right corner of the Button (in this case button Soup)
Like So:
##############
# #
# Soup #
# 10 #
##############
Could someone help me please and solve this problem....
Thanks in advance...
Kind regards
lapeci
here is the code of cellclick event of datagridview
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
// make sure that the click was in the right column
if (e.ColumnIndex == 2) // I used 1 here because I didn't put a column for FoodType, you should use 2.
{
// Give it a value in case the cell is empty
string cellContent = "0";
if (this.dataGridView1[e.ColumnIndex, e.RowIndex].Value != null)
{
cellContent = this.dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();
}
using (InputBox ib = new InputBox("Enter new stock amount:", this.dataGridView1[0, e.RowIndex].Value.ToString(), cellContent))
{
if (ib.ShowDialog() == DialogResult.OK)
{
this.dataGridView1[e.ColumnIndex, e.RowIndex].Value = ib.Result;
cellContent = ib.Result;
}
}
}
}
And this is the InputBox dialog to enter quantity in to the cell...
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 DtposApplication
{
public partial class InputBox : Form
{
public InputBox(string text, string caption, string defaultValue)
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
this.Text = caption; //.Clone().ToString();
Size size;
using (Graphics g = this.CreateGraphics())
{
Rectangle screen = Screen.PrimaryScreen.WorkingArea;
SizeF sizeF = g.MeasureString(text, lblPrompt.Font, screen.Width - 20);
size = sizeF.ToSize();
size.Width += 4;
}
if (size.Width < 310)
{
size.Width = 310;
}
Size clientSize = this.ClientSize;
clientSize.Width += size.Width - lblPrompt.Width;
clientSize.Height += size.Height - lblPrompt.Height;
this.ClientSize = clientSize;
lblPrompt.Text = text;
txtResult.Text = defaultValue;
this.DialogResult = DialogResult.Cancel;
}
void CancelButtonClick(object sender, System.EventArgs e)
{
result = null;
this.Close();
}
void AcceptButtonClick(object sender, System.EventArgs e)
{
this.DialogResult = DialogResult.OK;
result = txtResult.Text;
this.Close();
}
string result;
public string Result
{
get
{
return result;
}
}
private void btnSeven_Click(object sender, EventArgs e)
{
txtResult.Text += btnSeven.Text + "7";
}
private void btnTwo_Click(object sender, EventArgs e)
{
txtResult.Text += btnTwo.Text + "2";
}
private void btnOne_Click(object sender, EventArgs e)
{
txtResult.Text += btnOne.Text + "1";
}
private void btnSix_Click(object sender, EventArgs e)
{
txtResult.Text += btnSix.Text + "6";
}
private void btnFive_Click(object sender, EventArgs e)
{
txtResult.Text += btnFive.Text + "5";
}
private void btnFour_Click(object sender, EventArgs e)
{
txtResult.Text += btnFour.Text + "4";
}
private void btnNine_Click(object sender, EventArgs e)
{
txtResult.Text += btnNine.Text + "9";
}
private void btnEight_Click(object sender, EventArgs e)
{
txtResult.Text += btnEight.Text + "8";
}
private void btnThree_Click(object sender, EventArgs e)
{
txtResult.Text += btnThree.Text + "3";
}
private void btnZero_Click(object sender, EventArgs e)
{
txtResult.Text += btnZero.Text + "0";
}
private void btnClear_Click(object sender, EventArgs e)
{
txtResult.Clear();
txtResult.Focus();
}
}
}
is the code how im creating buttons on form1 and then take the database records and asign values to these buttons
private void FoodAddButtons(DataTable table)
{
int xpos = 5;
int ypos = 5;
int space = 2;
VistaButtonTest.VistaButton newButton = null;
DtposMenuBS.Sort = "FoodPrice";
try
{
foreach (DataRowView dr in DtposMenuBS.List)
{
newButton = new VistaButtonTest.VistaButton();
newButton.ButtonText = dr["FoodName"].ToString();
newButton.AutoEllipsis = true;
newButton.Width = 152;
newButton.Height = 70;
newButton.CornerRadius = 4;
newButton.Font = new System.Drawing.Font("Arial Narrow", 15.00F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
newButton.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
newButton.ForeColor = System.Drawing.Color.Black;
newButton.HighlightColor = System.Drawing.Color.DarkGray;
newButton.GlowColor = System.Drawing.Color.DimGray;
if (xpos + newButton.Width > this.FoodMenuPanel.ClientSize.Width)
{
ypos += newButton.Height + space;
xpos = 5;
}
newButton.Location = new Point(xpos, ypos);
xpos += newButton.Width + space;
newButton.Click += ItemSelection1;
this.FoodMenuPanel.Controls.Add(newButton);
}
}
finally
{
DtposMenuBS.Sort = "";
}
}
You could put a label on top of the button exactly where you want it
and then update the label
Check this out:
Multiline Text as the button label - Windows Forms
At the time you get the value 10, try to set the button text property with this value. You should do some formatting (adding spaces accordingly) to fit the text in the bottom-right part of the button.
More detailed explanation:
When the dialog box pops up you enter the value 10. When you set this number in the datagrid cell (I think you have some kind of event handler doing this job) you should also set the button's text property btnSoup.Text = 10 within the same event handler. To align the text in the button, use the link I provided you above.

Categories

Resources