I have dynamically created buttons as shown in code all all the button from 10:00 to 12:00 with 15 min of interval and deselect in lifo order like if i have selected 10:0 and 10:15 then i can not select 10:45 .. and i i have selected 10:0,10:15,10:30,10:45 and then i have to deselect 10:15 then first we have to deselect 10:30 and 10:45 ...please help me out.
private void GetControls()
{
count++;
for (int i = 10; i < 12; i++)
{
for (int j = 0; j < 60; j += 15)
{
Button btn = new Button();
btn.Text = i + "-" + j;
btn.ID = i + "-" + j;
btn.Command += new CommandEventHandler(this.btn_Click);
// btn.Click += btn_Click;
flag = true;
btn.CommandName = i + "-" + j;
if (count==1)
{
PlaceHolder1.Controls.Add(btn);
}
}
}
}
private void btn_Click(object sender, CommandEventArgs e)
{
count++;
string ID = (sender as Button).ID;
Label1.Text = " Congrates! Your meeting time has been sheduled upto " + ID;
Label1.Visible = false;
Button btn = sender as Button;
if (btn.BackColor == Color.Green)
{
btn.BackColor = System.Drawing.Color.Yellow;
getStatus(sender);
}
else
{
btn.BackColor = System.Drawing.Color.Green;
}
Correct me if I am wrong! You want to only select one button at a time so that if one button is clicked, the rest should reset? if that's the case, here's a code to do so:
[Edit]
Added a Session to remember dynamic button ids and used (.) instead of (-) for button Ids
private void GetControls()
{
count++;
for (int i = 10; i < 12; i++)
{
for (int j = 0; j < 60; j += 15)
{
Button btn = new Button();
btn.Text = i + "-" + j;
btn.ID = i + "." + j;
btn.Command += new CommandEventHandler(this.btn_Click);
// btn.Click += btn_Click;
flag = true;
btn.CommandName = i + "-" + j;
if (count == 1)
{
PlaceHolder1.Controls.Add(btn);
List<string> createdControls = Session["Controls"] != null ? Session["Controls"] as List<string> : new List<string>();
if (!createdControls.Contains(btn.ID)) createdControls.Add(btn.ID);
Session["Controls"] = createdControls;
}
}
}
}
[Edited] Replace the btn-Click event with the following.
private void btn_Click(object sender, CommandEventArgs e)
{
count++;
string ID = (sender as Button).ID;
ResetButton(Convert.ToDouble(ID));
Label1.Text = " Congrates! Your meeting time has been sheduled upto " + ID;
Button btn = sender as Button;
if (btn.BackColor == Color.Green)
{
btn.BackColor = System.Drawing.Color.Yellow;
}
else
{
btn.BackColor = System.Drawing.Color.Green;
}
}
[Edited] And this is the method implementation
private void ResetButton(double selectedButtonID)
{
List<string> createdControls = Session["Controls"] != null ? Session["Controls"] as List<string> : new List<string>();
TimeSpan timespan = TimeSpan.FromHours(selectedButtonID);
string currentSelectedTime = timespan.ToString("h\\:mm");
foreach (string buttonID in createdControls)
{
if (!string.IsNullOrEmpty(buttonID))
{
int comparisonResult = timespan.CompareTo(TimeSpan.FromHours(Convert.ToDouble(buttonID)));
Button button = Page.FindControl(buttonID) as Button;
if (button != null && comparisonResult==1)
{
button.BackColor = Color.Yellow;// selected
}
else
{
button.BackColor = Color.Red;// deselected
}
}
}
Related
I'm using this code to create buttons with two lines text
private void button1_Click(object sender, EventArgs e)
{
int top = 50;
int left = 100;
int n = 0;
int s = 99;
for (int i = 0; i < 20; i++)
{
Button button = new Button();
button.Left = left;
button.Top = top;
panel1.Controls.Add(button); // here
button.Size = new Size(50, 50);
if (i == 4 || i == 9||i==14||i==19)
{
top = 30;
left = 23;
top +=button.Top+2;
left += button.Width+2;
}
else
left += button.Width + 2;
n = n + 1;
s = s + 1;
button.Text = Convert.ToString(n) + Environment.NewLine + Convert.ToString(s);
button.Click += Button_Click;
}
}
private void Button_Click(object sender, EventArgs e)
{
string s;
Button button = (Button)sender;
s = button.Text + Environment.NewLine;
MessageBox.Show(s);
}
So I need to select only second line brom my button text when I click dynamic button. How will I do this?
you can store some data in Tag property:
button.Text = Convert.ToString(n) + Environment.NewLine + Convert.ToString(s);
button.Tag = new int[] { n, s };
and later retrive it and use:
private void Button_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
var data = button.Tag as int[];
string s = data[1].ToString();
MessageBox.Show(s);
}
private void Button_Click(object sender, EventArgs e)
{
string s;
Button button = (Button)sender;
s = button.Text + Environment.NewLine;
MessageBox.Show(button.Text.Split(new[] { Environment.NewLine }, StringSplitOptions.None)[1]);
}
UPDATE: I added my code to show the whole process and this is somehow a continuation to my last question
I have 3 items listed in my listview and a if statement which states that if my subitem is Inactive code inside will generate a file. My problem is once the Inactive item/s is Active again, how will I make my timer to move again?
private void Form1_Load(object sender, EventArgs e)
{
timer2.Enabled = true;
}
private void running_process()
{
Process[] processes = Process.GetProcesses("ITWORKSPC152");
for (int i = 0; i < listView1.Items.Count; i++)
{
if (flag == false)
{
listView1.Items[i].SubItems.Add("Inactive");
if(i == listView1.Items.Count - 1)
flag = true;
}
foreach (Process p in processes)
{
if (!listBox1.Items.Contains(listView1.Items[i].Text))
{
listView1.Items[i].SubItems[1].Text = " ";
listView1.Items[i].SubItems[1].Text = "Inactive";
listView1.Items[i].BackColor = Color.Red;
}
if (listView1.Items[i].Text == p.ProcessName)
{
listBox1.Items.Add(p.ProcessName);
listView1.Items[i].SubItems[1].Text = "Inactive";
for (int j = 0; j < listBox1.Items.Count; j++)
{
if (listBox1.Items[j].ToString() == listView1.Items[i].Text)
{
listView1.Items[i].SubItems[1].Text = "Active";
listView1.Items[i].BackColor = Color.FromArgb(66, 181, 33);
//m_boolIsDown = false;
}
}
}
}
}
}
private void InactiveCheck()
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].SubItems[1].Text == "Inactive")
{
richTextBox1.Text = richTextBox1.Text + listView1.Items[i].Text +
" was inactive at " + DateTime.Now.ToString("hh':'mm tt") + "\n";
File.AppendAllText(#"C:\Documents and Settings\pamojica\My Documents\InactiveProgramLogs\" + lbl_date.Text + ".txt", richTextBox1.Text);
timer3.Enabled = false;
}
else
{
timer3.Enabled = true;
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
listBox1.Items.Clear();
richTextBox1.Clear();
running_process();
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void timer3_Tick(object sender, EventArgs e)
{
InactiveCheck();
}
private void listView1_AfterLabelEdit(object sender, LabelEditEventArgs e)
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i] == null || listView1.Items.Count == 0)
return;
var item = listView1.Items[i];
if (item.SubItems != null && item.SubItems.Count > 1 && item.SubItems[1].Text == "Inactive")
{
richTextBox1.Text = richTextBox1.Text + item.Text + " was inactive at " + DateTime.Now.ToString("hh':'mm tt") + "\n";
File.AppendAllText(#"C:\Documents and Settings\pamojica\My Documents\InactiveProgramLogs\" + lbl_date.Text + ".txt", richTextBox1.Text);
}
}
}
You do not need Timer at all. In your case, the problem is: you want to do something when the value of your item in the listview changes. "event" is the key word here.
Subscribe to an event of your ListView, choose one here. I think that in that list the event "AfterLabelEdit" is the one you are looking for.
Here is some clues, maybe you should adapt the code to your specific context:
listView1.AfterLabelEdit += (o, e) =>
{
if (listView1.SelectedItems == null || listView1.SelectedItems.Count == 0)
return;
var item = listView1.SelectedItems[0];
if (item.SubItems != null && item.SubItems.Count > 1 && item.SubItems[1].Text == "Inactive")
{
richTextBox1.Text = richTextBox1.Text + item.Text + " was inactive at " + DateTime.Now.ToString("hh':'mm tt") + "\n";
File.AppendAllText(#"C:\Documents and Settings\pamojica\My Documents\InactiveProgramLogs\" + lbl_date.Text + ".txt", richTextBox1.Text);
}
};
Generally speaking, there is almost no simple UI hanlding case where a timer is needed. Just use event.
In a "ListView point of view", using a timer is like:
"I will look around if something changed. If not, I will recheck in a few milliseconds. I will be very busy."
The (better) logic with event is:
"Hey you, controls. All of you: when something changes... keep me posted!"
Instead of doing timer3.Enabled = true; or timer3.Enabled =false
use timer3.Start(); and timer3.Stop()
Stop the Timer in Tick Event will do the trick
private void Form1_Load(object sender, EventArgs e)
{
timer3.Start();
}
private void InactiveCheck()
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].SubItems[1].Text == "Inactive")
{
richTextBox1.Text = richTextBox1.Text + listView1.Items[i].Text + " was inactive at " + DateTime.Now.ToString("hh':'mm tt") + "\n";
File.AppendAllText(#"C:\Documents and Settings\pamojica\My Documents\InactiveProgramLogs\" + lbl_date.Text + ".txt", richTextBox1.Text);
}
else
{
timer3.Start();
}
}
}
private void timer3_Tick(object sender, EventArgs e)
{
timer3.Stop()
InactiveCheck();
}
Use timer3.Stop(); or timer3.Start(); methods in a ItemSelectionChanged event
private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
if (e.Item == sender)
{
if (e.IsSelected) timer3.Start();
else timer3.Stop();
}
}
I have a Button array in C# WFA and I want to create an event for a click of any button in the array.
How can I do it?
And how to know which location in the array it is?
I know sender is the button itself
You can use a for loop that closes over a variable containing the current index:
for(int i = 0; i < buttons.Length; i++)
{
//it's important to have this; closing over the loop variable would be bad
int index = i;
buttons[i].Click += (sender, args) => SomeMethod(buttons[index], index);
}
You can add the event handler to each button in a for loop.
Inside the handler, you can call array.IndexOf((Button)sender).
try this
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Button[] myButtons = new Button[10];
private void Form1_Load(object sender, EventArgs e)
{
for(int i = 0; i < myButtons.Length; i++)
{
int index = i;
this.myButtons[i] = new Button();
this.myButtons[i].Location = new System.Drawing.Point(((i + 1) * 70), 100 + ((i + 10) * 5));
this.myButtons[i].Name = "button" + (index + 1);
this.myButtons[i].Size = new System.Drawing.Size(70, 23);
this.myButtons[i].TabIndex = i;
this.myButtons[i].Text = "button" + (index + 1);
this.myButtons[i].UseVisualStyleBackColor = true;
this.myButtons[i].Visible = true;
myButtons[i].Click += (sender1, ex) => this.Display(index+1);
this.Controls.Add(myButtons[i]);
}
}
public void Display(int i)
{
MessageBox.Show("Button No " + i);
}
}
}
I have created a program for some class work and it all works fine, but I'm having some problems with the alignment of the multiple bits of info inserted into the list box on the same rows.
When I print it, it looks messy and also looks messy in the list box.
Is there anyway I can neaten it up a little? I've tried pad right with no joy and list views confuse the hell out of me. Here is my code:
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 Microsoft.VisualBasic;
using System.Collections;
namespace Assignment2
{
public partial class frmCalculator : Form
{
bool blnDot = false;
double dbAllPoints = 0;
double dbAllMoney = 0;
public frmCalculator()
{
InitializeComponent();
}
private void frmCalculator_Load(object sender, EventArgs e)
{
ddbItems.Items.Add("Glass");
ddbItems.Items.Add("Paper");
ddbItems.Items.Add("Beverage Cans");
ddbItems.Items.Add("Tins");
ddbItems.Items.Add("Milk Cartons");
ddbItems.Items.Add("Juice Boxes");
ddbItems.Items.Add("Plastics");
ddbItems.Items.Add("Clothes");
}
private void txtInput_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar < '0' || e.KeyChar > '9') && (e.KeyChar != '.'))
{
MessageBox.Show("Please input a number!", "Error");
e.Handled = true;
}
if (e.KeyChar == '.')
{
if (blnDot == true) { e.Handled = true; }
else { blnDot = true; }
}
}
private void txtInput_MouseClick(object sender, MouseEventArgs e)
{
txtInput.Text = "";
}
private void btnCalculate_Click(object sender, EventArgs e)
{
String strItem = "";
double dbMoney = 0;
double dbPoints = 0;
int intPoint = 0;
double dbWeight = 0;
if (((txtInput.Text == "")||(txtInput.Text=="Input the weight")|| (ddbItems.SelectedIndex==0)))
{
MessageBox.Show("Please input a weight into the textbox and make a selection from the drop down box", "Error");
}
else
{
if (ddbItems.SelectedIndex == 1)
{
intPoint = 7;
strItem = ddbItems.Items[1].ToString();
}
if (ddbItems.SelectedIndex == 2)
{
intPoint = 8;
strItem = ddbItems.Items[2].ToString();
}
if (ddbItems.SelectedIndex == 3)
{
intPoint = 10;
strItem = ddbItems.Items[3].ToString();
}
if (ddbItems.SelectedIndex == 4)
{
intPoint = 10;
strItem = ddbItems.Items[4].ToString();
}
if (ddbItems.SelectedIndex == 5)
{
intPoint = 3;
strItem = ddbItems.Items[5].ToString();
}
if (ddbItems.SelectedIndex == 6)
{
intPoint = 3;
strItem = ddbItems.Items[6].ToString();
}
if (ddbItems.SelectedIndex == 7)
{
intPoint = 5;
strItem = ddbItems.Items[7].ToString();
}
if (ddbItems.SelectedIndex == 8)
{
intPoint = 6;
strItem = ddbItems.Items[8].ToString();
}
dbWeight = Convert.ToDouble(txtInput.Text);
dbPoints = intPoint * dbWeight;
dbMoney = dbPoints * 0.01;
dbAllPoints = dbAllPoints + dbPoints;
dbAllMoney = dbAllMoney + dbMoney;
lblTotals.Visible = true;
lblTotals.Text = "You have " + dbAllPoints.ToString() + " points, and you have earned £" + dbAllMoney.ToString("0.00");
lstResults.Items.Add(strItem + " " + dbWeight.ToString() + "kg " + dbPoints.ToString() + " points £" + dbMoney.ToString("0.00"));
txtInput.Text = "Input the weight";
ddbItems.SelectedIndex = 0;
blnDot = false;
}
}
private void btnEnd_Click(object sender, EventArgs e)
{
frmWelcome frmWelcome = (frmWelcome)Application.OpenForms["frmWelcome"];
frmWelcome.Close();
this.Dispose();
}
private void btnReset_Click(object sender, EventArgs e)
{
DialogResult result;
result = MessageBox.Show("Are you sure you want to reset everything?", "Confirm", MessageBoxButtons.YesNo);
if (result == DialogResult.No) return;
txtInput.Text = "Input the weight";
lstResults.Items.Clear();
ddbItems.SelectedIndex = 0;
lblTotals.Text = "";
lblTotals.Visible = false;
blnDot = false;
}
private void btnPrint_Click(object sender, EventArgs e)
{
int intMax;
intMax = lstResults.Items.Count;
String[] arrResults = new String[intMax];
int intLoop;
for (intLoop = 0; intLoop < intMax; intLoop++)
{
arrResults[intLoop] = lstResults.Items[intLoop].ToString();
}
Array.Sort(arrResults);
lstResults.Items.Clear();
for (intLoop = 0; intLoop < intMax; intLoop++)
{
lstResults.Items.Add(arrResults[intLoop]);
}
printDocument1.Print();
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
String strLine = "";
int intLoop;
Font pfont = new Font("Verdana", 18, GraphicsUnit.Point);
int intLine = 75;
strLine = "Item Weight Points Money";
e.Graphics.DrawString(strLine, pfont, Brushes.Black, 75, intLine);
strLine = "";
intLine = intLine + 30;
intLine = intLine + 30;
for (intLoop = 0; intLoop < lstResults.Items.Count; intLoop++)
{
strLine = strLine +lstResults.Items[intLoop];
e.Graphics.DrawString(strLine, pfont, Brushes.Black, 75, intLine);
intLine = intLine + 30;
strLine = "";
}
intLine = intLine + 30;
strLine = lblTotals.Text;
e.Graphics.DrawString(strLine, pfont, Brushes.Black, 75, intLine);
strLine = "";
intLine = intLine + 30;
}
}
}
You should use a DataGridView control instead of a ListBox since you are trying to display "column" information.
Likewise, when printing, you should be doing the DrawString for each column as well so that they line up properly.
If you want to continue with what you are doing, then you should use a mono-spaced font like Courier, not Verdana, and count the spaces between then lengths of the words.
Hello I'm currently working on a windows from where I need to be able to add and remove a number of textboxes (and a lable) with a button click.
I have to have it set out within a tableLayoutPanel and Once "Add" is clicked a Label and 5 Text boxes must appear on the same row, and then when I click "Remove" they must dissapear, Hiding won't work as Data needs to be taken from them at a later stage but thats not an issue atm.
The problem is with the removal (I can add them fine as you'll see below) I know whats happening and can guess as to why but I need to find an alternate solution >.<
public partial class Form2 : Form
{
int Count = 1;
int rowIndex = 2, colIndex = 1;
Label Label;
TextBox Value;
TextBox Weight;
TextBox Width;
TextBox Height;
TextBox Length;
private void button1_Click(object sender, EventArgs e)
{
if (Count <= 9)
{
Count += 1;
rowIndex += 1;
tableLayoutPanel10.RowCount = +1;
AddLot(Count);
if (Count > 9)
button1.Enabled = false;
}
button2.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
if (Count == 2)
{
tableLayoutPanel10.Controls.Remove(Label);
tableLayoutPanel10.Controls.Remove(Value);
tableLayoutPanel10.Controls.Remove(Weight);
tableLayoutPanel10.Controls.Remove(Width);
tableLayoutPanel10.Controls.Remove(Height);
tableLayoutPanel10.Controls.Remove(Length);
Count -= 1;
rowIndex -= 1;
button2.Enabled = false;
}
else
{
tableLayoutPanel10.Controls.Remove(Label);
tableLayoutPanel10.Controls.Remove(Value);
tableLayoutPanel10.Controls.Remove(Weight);
tableLayoutPanel10.Controls.Remove(Width);
tableLayoutPanel10.Controls.Remove(Height);
tableLayoutPanel10.Controls.Remove(Length);
Count -= 1;
rowIndex -= 1;
button1.Enabled = true;
}
}
private void AddLot(int Count)
{
Label = new Label();
Label.Dock = DockStyle.Fill;
Label.Text = Count.ToString();
Label.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
Value = new TextBox();
Value.Dock = DockStyle.Fill;
Weight = new TextBox();
Weight.Dock = DockStyle.Fill;
Width = new TextBox();
Width.Dock = DockStyle.Fill;
Height = new TextBox();
Height.Dock = DockStyle.Fill;
Length = new TextBox();
Length.Dock = DockStyle.Fill;
tableLayoutPanel10.Controls.Add(Label, colIndex - 1, rowIndex);
tableLayoutPanel10.Controls.Add(Value, colIndex, rowIndex);
tableLayoutPanel10.Controls.Add(Weight, colIndex + 1, rowIndex);
tableLayoutPanel10.Controls.Add(Width, colIndex + 2, rowIndex);
tableLayoutPanel10.Controls.Add(Height, colIndex + 3, rowIndex);
tableLayoutPanel10.Controls.Add(Length, colIndex + 4, rowIndex);
}
}
All That Happens when I try to remove is the Last added Row of label/textboxes is removed, and then only the rowindex/count decrease on any clocks afterwards.
Any Ideas how to get this to work, I'll accept having to change it almost completely but as I said It must be done in the TableLayoutPanel >.<
Cheers,
Jmaru7
This works 100% for me i spent an hour working on it :
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
tableLayoutPanel1.RowCount = 1;
tableLayoutPanel1.ColumnCount = 6;
removeButton.Enabled = false;
}
private void addButton_Click(object sender, EventArgs e)
{
int index = tableLayoutPanel1.RowCount - 1;
Label label = new Label();
TextBox Value = new TextBox();
TextBox Weight = new TextBox();
TextBox Width = new TextBox();
TextBox Height = new TextBox();
TextBox Length = new TextBox();
label.Dock = DockStyle.Fill;
label.Text = (index + 1).ToString();
label.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
Value.Dock = DockStyle.Fill;
Weight.Dock = DockStyle.Fill;
Width.Dock = DockStyle.Fill;
Height.Dock = DockStyle.Fill;
Length.Dock = DockStyle.Fill;
int i = 0;
tableLayoutPanel1.Controls.Add(label, i++, index);
tableLayoutPanel1.Controls.Add(Value, i++, index);
tableLayoutPanel1.Controls.Add(Weight, i++, index);
tableLayoutPanel1.Controls.Add(Width, i++, index);
tableLayoutPanel1.Controls.Add(Height, i++, index);
tableLayoutPanel1.Controls.Add(Length, i++, index);
tableLayoutPanel1.RowCount += 1;
if (tableLayoutPanel1.RowCount > 9)
{
addButton.Enabled = false;
}
if (tableLayoutPanel1.RowCount > 0)
{
removeButton.Enabled = true;
}
}
private void removeButton_Click(object sender, EventArgs e)
{
if (tableLayoutPanel1.RowCount > 0)
{
int startIndex = ((tableLayoutPanel1.RowCount - 1) * 6) - 1;
for (int i = 0; i < 6; i++)
{
tableLayoutPanel1.Controls.RemoveAt(startIndex--);
}
tableLayoutPanel1.RowCount -= 1;
if (tableLayoutPanel1.RowCount == 0)
{
removeButton.Enabled = false;
}
if (tableLayoutPanel1.RowCount <= 9)
{
addButton.Enabled = true;
}
}
}
}
You are keeping only last added set of controls, you should keep all of them. Now when you delete last added controls, next delete uses reference to already deleted so it wont have any effect.
Best would be to make some storage class for set of the controls and keep them in some kind of collection.