C# - Use Label to show how many Digits are left - c#

I've created a Sudoku Game and I have 23 Digits that are covered for the user and that he needs too solve.
I'm wondering if it's possible that through a Label show the user how many textboxes that are left over without an digit in them.
I've created the game through WinForms and I've pretty much come to an hold. If anyone can throw me in the right direction it would be much appreciated!
I created the textboxes and used arrays, then I randomized a finished sudoku. The randomizer is a whole class for itself and after that I pretty much assigned arrays
private void assign_Char_Value(string[] s_Rem_Value)
{
arr_Char_Value = (s_Rem_Value[0] + s_Rem_Value[1] + s_Rem_Value[2]
+ s_Rem_Value[3] + s_Rem_Value[4] + s_Rem_Value[5] + s_Rem_Value[6]
+ s_Rem_Value[7] + s_Rem_Value[8]).ToCharArray();
int i_Cnt = 0;
foreach (TextBox[] arr_txtBox in validate.arr_txtBox_Horiz)
{
foreach (TextBox txtBox in arr_txtBox)
{
txtBox.Text = arr_Char_Value[i_Cnt].ToString();
i_Cnt++;
}
}
Rondomize_Numbers();
}
After that I chose int number = 23;
I have 3 buttons one of them correct the game another randomizes a new game and the other shows the rules of sudoku.

Let's assume for simplicity you have all your textboxes in a panel.
and that the textboxes are the only items in the panel.
Now have your textboxes hookup to the same textBox_TextChanged event like this:
public Form1()
{
InitializeComponent();
foreach (TextBox txtBox in panel1.Controls)
{
txtBox.TextChanged += textBox_TextChanged;
}
}
now for the event:
private void textBox_TextChanged(object sender, EventArgs e)
{
var emptyCounter = 0;
foreach (TextBox txtBox in panel1.Controls)
{
if (String.IsNullOrWhiteSpace(txtBox.Text))
{
emptyCounter++;
}
}
label1.Text = emptyCounter.ToString();
}
you could also use a LINQ statement instead of the foreach above making the method look like this:
private void textBox_TextChanged(object sender, EventArgs e)
{
var emptyCounter = panel1.Controls.OfType<TextBox>().Count(txtBox => String.IsNullOrWhiteSpace(txtBox.Text));
label1.Text = emptyCounter.ToString();
}
Hope this helps.

Related

How to change a text on multiple buttons in the most efficient way without repeating code in C#? [duplicate]

This question already has answers here:
Find control by name from Windows Forms controls
(3 answers)
Closed 3 years ago.
I don't want to repeat my code, so I want to make something that can change the text on multiple buttons. Is it any way you can specify what button is called and add that to the code for changing the text?
I know you can change text on a button with button1.Text = "X";
I have tried to make a string, so I only have to write the name of the button, so the calling code ends up being PickPlayer("button1");.
My full code is:
private void button9_Click(object sender, EventArgs e)
{
pickPlayer("button9");
}
private void pickPlayer(string Button)
{
if (player % 2 == 0)
{
player += 1;
Button.Text = "O";
}
else
{
player += 1;
Button.Text = "X";
}
}
But it shows an error message as follows:
string does not contain a definition for Text.
What am I doing wrong?
This will append Foo to the end of all of your buttons. Without knowing more information to what the conditions are for setting the button text, this is all I can give you.
private void Form1_Load(object sender, EventArgs e)
{
var list = GetAllButtonControls();
foreach (Control control in list)
{
if (control.GetType() == typeof(Button))
{
//Set text
control.Text += " Foo";
}
}
}
private List<Control> GetAllButtonControls()
{
List<Control> rlist = new List<Control>();
foreach (Control control in this.Controls)
{
if (control.GetType() == typeof(Button))
{
rlist.Add(control);
}
}
return rlist;
}

Getting sum of textbox from all the dynamically generated usercontrols

I want to add the price(label) of all the dynamically generated usercontrol and set to a label on the winform how can i do that? by clicking the ok button on the winform
i tried this code but it didn't add the labels and the output is always 0
Here is the image : https://imgur.com/a/ViPGt
and this is my code :
private void add_Click(object sender, EventArgs e)
{
double g = 0;
foreach (Control ctrl in Controls)
{
if (ctrl is DynaItems)
{
var myCrl = ctrl as DynaItems;
g += Convert.ToInt32(myCrl.price.Text);
}
}
textBox1.Text = g.ToString();
}
I think this might be coming from the fact that you want a double while you're converting to an Int32. Try this code and at the same time check if your price control has its property Text correct.
private void add_Click(object sender, EventArgs e)
{
double g = 0;
// Controls.OfType will automatically find your DynaItems controls and cast them for you
foreach (DynaItems dynaItem in Controls.OfType<DynaItems>())
{
// Breakpoint here and check the value of dynaItem.price.Text
g += double.Parse(dynaItem.price.Text);
}
textBox1.Text = g.ToString();
}

Does resize event with search event are Independent ? ListView + TextBox c#

Working on application which is searching for items in ListView. I've added a liitle bit logic for this to looks better.
First I have added logic to the List View Columns - size of column fit to the content.
Then searching via ID - which is working.
My problem and question is if these two events depends of each other ? mean.. while I am trying to search it gets to infinitive loop with resizing and it makes "crash". My code which depends of that is :
// Resize
void DeviceListView_Resize(object sender, EventArgs e)
{
controller.ResizeColumns((ListView)sender);
}
public void ResizeColumns(ListView lv)
{
foreach (ColumnHeader column in lv.Columns)
{
column.Width = -2;
}
}
// Search
void SearchBox_TextChanged(object sender, EventArgs e)
{
controller.Search();
}
public void Search()
{
myListView.Items.Clear();
myListView.Items.AddRange(myList.Where(i => string.IsNullOrEmpty(searchBox.Text) || searchBox.Text.Contains("Search") || i.esn.Contains(searchBox.Text))
.Select(c => new ListViewItem (
new string[] {c.ID, c.Name, (...), c.Smth}
)).ToArray());
}
// Search Box place holder
void SearchBox_TextChanged(object sender, EventArgs e)
{
controller.Search();
}
void TextGotFocus(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
if(tb.Text == "Search...")
{
tb.Text = "";
tb.ForeColor = Color.Black;
}
}
void TextLostFocus(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
if(tb.Text == "")
{
tb.Text = "Search...";
tb.ForeColor = Color.LightGray;
}
}
The whole application already have a lot of lines of code, posted just pice of this.
Btw. My suspicions are in Search method in the line which contains : myListView.Items.Clear(); If i do not cleare it it wont makes anything, but Search wont have usage as well.
Thanks in advance!
Yes they are independent of each other, somehow - I do not know :) If solved my problem which look like :
global variable :
bool resized = false;
if (!resized)
{
foreach (ColumnHeader column in lv.Columns)
{
column.Width = -2;
}
resized = true;
}

How do I add click events to all buttons that have names starting with a certain string in C#?

I am writing a simple calculator script for my C# programming class. It will of course have buttons 0-9 that will update the output textbox to add the number of whatever button is clicked. My problem right now that is I would rather not have to have 10 different click events in my script. I would rather have a loop that cycles through the buttons that will add the same click event to each one and then decide what number to add to the output based on the button.
So right now, I have a click event for the "1" button which is this...
private void btnNum1_Click(object sender, EventArgs e)
{
txtOutput.Text = Convert.ToString(txtOutput.Text + "1");
}
This works fine, but, again, I would rather not have to do this 10 times. How can I create a loop that prevents this?
The button names are btnNum1, btnNum2, btnNum3, etc.
Assuming the button text is just "1", "2" etc you could do this:
private void btnNum_Click(object sender, EventArgs e)
{
var button = sender as Button
txtOutput.Text += button.Content.ToString();
}
Then just apply this event to all the buttons.
Also note you don't need Convert.ToString() as what you are trying to convert is already a string. Using += also cleans up your code a bit.
You could do this to wire-up all of the events in one go:
for (var n = 0; n <= 9; n++)
{
var btn =
this
.Controls
.Find("btnNum" + n.ToString(), false)
.Cast<Button>()
.First();
var digit = n;
btn.Click += (s, e) =>
{
txtOutput.Text = digit.ToString();
};
}
You could enumerate the children controls of your Form/Control, look the type of controls which are type of Button and the name StartWith 'btnNum', with each of these buttons, add a Click event address to btnNum_Click().
Say if all your buttons are contained in a Panel named 'pnlButtons', you could loop all the children like this.
foreach (var control in pnlButtons.Controls)
{
if(control.GetType() == typeof(Button))
{
var button = control as Button;
if (button .Name.StartWith('btnNum'))
{
button.Click += btnNum_Click;
}
}
}
You can use the "Tag" property of the Button control and make an array of Buttons to subscribe to the same event. See sample below:
void InitializeButtons()
{
Button btnNum1 = new Button();
btnNum1.Text = "1";
btnNum1.Tag = 1;
//Button 2..8 goes here
Button btnNum9 = new Button();
btnNum9.Text = "9";
btnNum9.Tag = 9;
Button[] buttons = new Button[]{
btnNum1, btnNum2, btnNum3, btnNum4, btnNum5, btnNum6, btnNum7, btnNum8, btnNum9
};
for (int i = 0; i < buttons.Length; i++)
{
buttons[i].Click += Button_Click;
}
}
void Button_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
int value = (int)button.Tag;
//Do something with value
}
Assuming WinForms, you can recursively search for buttons that start with "btnNum" and wire them up to a common handler like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Load += Form1_Load;
}
void Form1_Load(object sender, EventArgs e)
{
FindButtons(this);
}
private void FindButtons(Control ctl)
{
foreach(Control ctrl in ctl.Controls)
{
if (ctrl.Name.StartsWith("btnNum") && (ctrl is Button))
{
Button btn = (Button)ctrl;
btn.Click += btn_Click;
}
else if(ctrl.HasChildren)
{
FindButtons(ctrl);
}
}
}
private void btn_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
txtOutput.Text = Convert.ToString(txtOutput.Text + btn.Text);
}
}

Access control after creating it at runtime in WPF

I have created many textboxes at runtime then I want to add values to them.. after that I add a button to click on it and calculate all these values in the textboxes but I do n't know how can I access to these textboxes ??
Thanks
have you tried the method FindControl?
private void Button1_Click(object sender, EventArgs MyEventArgs)
{
// Find control on page.
Control myControl1 = FindControl("TextBox2");
if(myControl1!=null)
{
// Get control's parent.
Control myControl2 = myControl1.Parent;
Response.Write("Parent of the text box is : " + myControl2.ID);
}
else
{
Response.Write("Control not found");
}
}
reference: http://msdn.microsoft.com/en-us/library/system.web.ui.control.findcontrol(v=vs.71).aspx
I this method from time to time, as long as you know the name of the textbox or what ever control you need.
FindControl("textboxnamehere").Text = "This would put this string in the current text box";
If you have the TextBoxes in a container, like a StackPanel, you could do something like this...
private void btnCalculate_Click(object sender, EventArgs e)
{
var total = 0;
var textboxes = StackPanelParent.Children.OfType<TextBox>();
foreach (var textbox in textboxes)
{
var input = 0;
int.TryParse(textbox.Text, out input);
total += input;
}
MessageBox.Show(total.ToString());
}
this is just a sample, Lets assume you put your text boxes in a stackpanel - you need a container!,
private void Button_Click(object sender, RoutedEventArgs e)
{
var sum = 0.0;
foreach (var child in stackPanel.Children)
{
var textBox = child as TextBox;
if (textBox == null) continue;
double value;
Double.TryParse(textBox.Text, out value);
sum += value;
}
Console.WriteLine(sum);
}
of course, I am assuming you know that you might want to validate the input (use a numeric textblock), button.Click += Button_click; , etc..
edit for a question
private void Button_Click(object sender, RoutedEventArgs e)
{
var sum = 0.0;
for (int i = 1; i < grid.Children.Count; i++ )
{
var textBox = grid.Children[i] as TextBox;
if (textBox == null) continue;
double value;
Double.TryParse(textBox.Text, out value);
sum += value;
}
Console.WriteLine(sum);
}

Categories

Resources