I have created dynamic NumericUpDown. I want to save the values that the user enters. How can i do that. After I am saving the values I want to do some time manipulation with them. Knowing I do not know the number of NumericUpDown the user wants each time?
// To set up the location for the NumericUpDown
int xCoor;
int yCoor;
Random coor = new Random();
// Button to create the NumericUpDown
private void btnRun_Click(object sender, EventArgs e)
{
/// I am assuming that the user choice is 8
int value = 8;
//this calls the method which is going to create NumericUpDown
this.AddNewNumrical(value);
}
//Method to Create NumericUpDown
private void AddNewNumrical(int numiraclNew)
{
for (int x = 0; x < numiraclNew; x++)
{
for (int y = 0; y < 1; y++)
{
NumericUpDown numiNumber = new NumericUpDown();
xCoor = coor.Next(0, 700);
yCoor = coor.Next(0, 710);
numiNumber.Location = new Point(xCoor, yCoor);
numiNumber.Size = new System.Drawing.Size(50, 15);
numiNumber.Maximum = 1000;
numiNumber.Minimum = 1;
this.pnlNodes.Controls.Add(numiNumber);
}
}
}
Just store your new NumericUpDown control in another list! You could also search the Controls collection for NumericUpDown controls but you might pick up some stuff you don't want:
List<NumericUpDown> numberControls = new List<NumericUpDown>();
//Method to Create NumericUpDown
private void AddNewNumrical(int numiraclNew)
{
for (int x = 0; x < numiraclNew; x++)
{
NumericUpDown numiNumber = new NumericUpDown();
xCoor = coor.Next(0, 700);
yCoor = coor.Next(0, 710);
numiNumber.Location = new Point(xCoor, yCoor);
numiNumber.Size = new System.Drawing.Size(50, 15);
numiNumber.Maximum = 1000;
numiNumber.Minimum = 1;
numberControls.Add(numiNumber); //Save the control off for later
this.pnlNodes.Controls.Add(numiNumber);
}
}
Then you can use it later to do whatever you want:
private void Foo()
{
foreach (NumericUpDown userSelection in numberControls)
{
//Do whatever with userSelection.Value
}
}
Related
My requirement is in my line graph( which is developed with c# MS Chart), I
always need to display 10 points(samples) at a time. The xaxis has interval value 1.
Initially the Xaxis tick values are (1,2,3,4,5,6,7,8,9,10), After 1 second of time interval, I
have to plot 10 points(samples) starts from 2nd point(i.e. I have to skip 1st
point).Now I need to update the xaxis tick values also , it should be starts from
2,now the xaxis tick values should be like 2,3,4,5,6,7,8,9,10,11). Likewise
After every second the starting value of x axis
tick needs to be increased by 1.
How to update Xaxis tick value in the chart dynamically ?
I am using below code
private void Form1_Load(object sender, EventArgs e)
{
loadCsvFile("C:\\mydata.csv");
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.timer1 = new System.Windows.Forms.Timer(this.components);
chart = new System.Windows.Forms.DataVisualization.Charting.Chart();
chart.Location = new System.Drawing.Point(1, 1);
chart.Size = new System.Drawing.Size(700, 700);
// Add a chartarea called "draw", add axes to it and color the area black
chart.ChartAreas.Add("draw");
numofSamples = 10;
chart.ChartAreas["draw"].AxisX.Minimum = 1;
chart.ChartAreas["draw"].AxisX.Maximum = 10;
chart.ChartAreas["draw"].AxisX.Interval = 1;
chart.ChartAreas["draw"].AxisX.Title = "X Axis";
chart.ChartAreas["draw"].AxisX.MajorGrid.LineColor = System.Drawing.Color.Black;
chart.ChartAreas["draw"].AxisX.MajorGrid.LineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Dash;
chart.ChartAreas["draw"].AxisY.Minimum = 0;
chart.ChartAreas["draw"].AxisY.Maximum = 1000;
chart.ChartAreas["draw"].AxisY.Interval = 250;
chart.ChartAreas["draw"].AxisY.Title = "Y Axis";
chart.ChartAreas["draw"].AxisY.MajorGrid.LineColor = Color.Black;
chart.ChartAreas["draw"].AxisY.MajorGrid.LineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Dash;
chart.ChartAreas["draw"].BackColor = Color.White;
// Create a new function series
chart.Series.Add("Tags");
// Set the type to line
chart.Series["Tags"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
// Color the line of the graph light green and give it a thickness of 3
chart.Series["Tags"].Color = Color.LightGreen;
chart.Series["Tags"].BorderWidth = 3;
chart.Series["Tags"].MarkerStyle = MarkerStyle.Circle;
chart.Series["Tags"].MarkerSize = 10;
chart.Legends.Add("MyLegend");
chart.Legends["MyLegend"].BorderColor = Color.Tomato; // I like tomato juice!
Controls.Add(this.chart);
// hook up timer event
this.timer1.Interval = 1000;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
timer1.Start();
}
public void loadCsvFile(string filePath)
{
var reader = new StreamReader(File.OpenRead(filePath));
while (!reader.EndOfStream)
{
List<string> listA = new List<string>();
string line = reader.ReadLine();
mList.Add(line );
}
}
int i = 0;
int n = 0;
private void timer1_Tick(object sender, EventArgs e)
{
if (n > 20)
n = 0;
int j=0;
chart.Series["Tags"].Points.Clear();
for (i=n; i < mList.Count; i++)
{
string l =mList[i];
chart.Series["Tags"].Points.AddY(l);
j++;
if (j == 10)
break;
}
n++;
chart.Update();
}
List<List<string>> mList = new List<List<string>>();
I have a WinForms project with MVP pattern (passive view) implemented.
I think that I have a problem with the pattern when it comes to a user control, which I figured out during unit testing
I have a user control that I put on my form as a result of an event fired in my view. That user control adds a certain amount of labels, textboxes, etc. to itsself based on a number it gets from the view. Finally, it tells the view to add the user control to the view.
I want to unit test the logic in this class, since that is what I think is most important to test. I just do not know how to do this, since there is both logic and form controls in this class. I am currently using Moq for creating my unit tests.
I would normally create a Mock object to represent the view and then test the implementation of the methods in the object to be tested in isolation. However, since I create controls in this class, I don't think I can test this like this (without including the .Forms library that is).
I hope someone knows a solution.
EDIT: I have been trying to separate my logic from the control manipulation, but I am struggling with a function from a different user control I have posted below the original user control code. Since I loop through a list of controls, I dont know how to separate this into just logic and just control handling.
User control code
public partial class DetailScreenUserControl : UserControl
{
// Private members.
private readonly IDetailScreenView _view;
private List<ComboBox> maturityInput = new List<ComboBox>();
private List<ComboBox> complianceInput = new List<ComboBox>();
// Public members.
public List<string> MaturityInput
{
get
{
var list = new List<string>();
for (int i = 0; i < maturityInput.Count; i++)
{
list.Add(maturityInput[i].Text);
}
return list;
}
set
{
for (int i = 0; i < maturityInput.Count; i++)
{
maturityInput[i].DataSource = new List<string>(value);
}
}
}
public List<string> ComplianceInput
{
get
{
var list = new List<string>();
for (int i = 0; i < complianceInput.Count; i++)
{
list.Add(complianceInput[i].Text);
}
return list;
}
set
{
for (int i = 0; i < complianceInput.Count; i++)
{
complianceInput[i].DataSource = new List<string>(value);
}
}
}
// Initialize user control with IDetailScreenView. Subscribe to necessary events.
public DetailScreenUserControl(IDetailScreenView view)
{
InitializeComponent();
_view = view;
_view.InitializingUserControl += InitializeUserControl;
}
// Initializes the user control for the detail screen.
public void InitializeUserControl(object sender, EventArgs e)
{
List<string> qStandards = _view.SelectedQuestionStandards;
Controls.Clear();
maturityInput.Clear();
complianceInput.Clear();
int inputSeparation = Height / 2;
int spacing = Width / 20;
Size = new Size(_view.RightUserControlBoundary - Location.X, Size.Height);
for (int i = 0; i < qStandards.Count; i++)
{
Panel inputPanel = new Panel();
inputPanel.BackColor = Color.AliceBlue;
inputPanel.Location = new Point(0, i * inputSeparation);
inputPanel.Size = new Size(Width - spacing, inputSeparation);
Controls.Add(inputPanel);
Label qs_label = new Label();
qs_label.AutoSize = true;
qs_label.Location = new Point(0, 0);
qs_label.Font = new Font("Arial", 12F, FontStyle.Bold);
qs_label.AutoSize = true;
qs_label.Text = qStandards[i].ToString();
inputPanel.Controls.Add(qs_label);
Label m_label = new Label();
m_label.AutoSize = true;
m_label.Location = new Point(0, qs_label.Bounds.Bottom + qs_label.Height / 2);
m_label.Font = new Font("Arial", 12F, FontStyle.Regular);
m_label.Text = "Maturity standard";
inputPanel.Controls.Add(m_label);
Label c_label = new Label();
c_label.AutoSize = true;
c_label.Location = new Point(0, m_label.Bounds.Bottom + qs_label.Height / 2);
c_label.Font = new Font("Arial", 12F, FontStyle.Regular);
c_label.Text = "Compliance standard";
inputPanel.Controls.Add(c_label);
ComboBox m_input = new ComboBox();
m_input.AutoSize = true;
m_input.Location = new Point(c_label.Bounds.Right + 2 * spacing, m_label.Bounds.Top);
m_input.Font = new Font("Arial", 10F, FontStyle.Regular);
m_input.DropDownStyle = ComboBoxStyle.DropDownList;
m_input.Size = new Size(inputPanel.Size.Width - m_input.Bounds.Left, spacing);
maturityInput.Add(m_input);
inputPanel.Controls.Add(m_input);
ComboBox c_input = new ComboBox();
c_input.AutoSize = true;
c_input.Location = new Point(c_label.Bounds.Right + 2 * spacing, c_label.Bounds.Top);
c_input.Font = new Font("Arial", 10F, FontStyle.Regular);
c_input.DropDownStyle = ComboBoxStyle.DropDownList;
c_input.Size = new Size(inputPanel.Size.Width - c_input.Bounds.Left, spacing);
complianceInput.Add(c_input);
inputPanel.Controls.Add(c_input);
}
if(qStandards.Count != 0)
{
saveAssessmentButton.BackColor = System.Drawing.SystemColors.ButtonHighlight;
Controls.Add(saveAssessmentButton);
saveAssessmentButton.Location = new Point(this.Size.Width - saveAssessmentButton.Width - spacing, qStandards.Count * inputSeparation);
}
_view.AddUserControl();
}
// Tells the view to save the assessment.
private void saveAssessmentButton_Click(object sender, EventArgs e)
{
_view.SaveAssessmentButtonClicked();
}
}
Other user control function('answers' is the list of controls)
public void SaveResults()
{
results = new List<string>();
int questionNr = 0;
for (int p = 0; p < questions.Count; p++)
{
for (int i = 0; i < questions[p].Count; i++)
{
bool unanswered = true;
results.Add(questions[p][i]);
for (int j = 1; j <= maturityAnswers[p].Count; j++)
{
var radioButton = (RadioButton)answers[questionNr][j];
if (radioButton.Checked)
{
results.Add(answers[questionNr][j].Text);
unanswered = false;
}
}
if (unanswered == true)
{
results.Add("");
}
unanswered = true;
for (int j = maturityAnswers[p].Count + 1; j <= (maturityAnswers[p].Count + complianceAnswers[p].Count); j++)
{
var radioButton = (RadioButton)answers[questionNr][j];
if (radioButton.Checked)
{
results.Add(answers[questionNr][j].Text);
unanswered = false;
}
}
if (unanswered == true)
{
results.Add("");
}
results.Add(answers[questionNr][0].Text.Replace("'", "''"));
questionNr++;
}
}
I want to unit test the logic in this class, since that is what I
think is most important to test. I just do not know how to do this,
since there is both logic and form controls in this class
So separate them to different classes and test the class which contains only logic
Is there any way to dynamically create and display 'n' Labels with 'n' corresponding Textboxs when we know value of 'n' after for example, clicking "Display" button.
Let me know if anything make you don't understand my question. Thank you!
I am working with VS C# Express 2010 Windows Form.
I would create a user control which holds a Label and a Text Box in it and simply create instances of that user control 'n' times. If you want to know a better way to do it and use properties to get access to the values of Label and Text Box from the user control, please let me know.
Simple way to do it would be:
int n = 4; // Or whatever value - n has to be global so that the event handler can access it
private void btnDisplay_Click(object sender, EventArgs e)
{
TextBox[] textBoxes = new TextBox[n];
Label[] labels = new Label[n];
for (int i = 0; i < n; i++)
{
textBoxes[i] = new TextBox();
// Here you can modify the value of the textbox which is at textBoxes[i]
labels[i] = new Label();
// Here you can modify the value of the label which is at labels[i]
}
// This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
for (int i = 0; i < n; i++)
{
this.Controls.Add(textBoxes[i]);
this.Controls.Add(labels[i]);
}
}
The code above assumes that you have a button btnDisplay and it has a onClick event assigned to btnDisplay_Click event handler. You also need to know the value of n and need a way of figuring out where to place all controls. Controls should have a width and height specified as well.
To do it using a User Control simply do this.
Okay, first of all go and create a new user control and put a text box and label in it.
Lets say they are called txtSomeTextBox and lblSomeLabel. In the code behind add this code:
public string GetTextBoxValue()
{
return this.txtSomeTextBox.Text;
}
public string GetLabelValue()
{
return this.lblSomeLabel.Text;
}
public void SetTextBoxValue(string newText)
{
this.txtSomeTextBox.Text = newText;
}
public void SetLabelValue(string newText)
{
this.lblSomeLabel.Text = newText;
}
Now the code to generate the user control will look like this (MyUserControl is the name you have give to your user control):
private void btnDisplay_Click(object sender, EventArgs e)
{
MyUserControl[] controls = new MyUserControl[n];
for (int i = 0; i < n; i++)
{
controls[i] = new MyUserControl();
controls[i].setTextBoxValue("some value to display in text");
controls[i].setLabelValue("some value to display in label");
// Now if you write controls[i].getTextBoxValue() it will return "some value to display in text" and controls[i].getLabelValue() will return "some value to display in label". These value will also be displayed in the user control.
}
// This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
for (int i = 0; i < n; i++)
{
this.Controls.Add(controls[i]);
}
}
Of course you can create more methods in the usercontrol to access properties and set them. Or simply if you have to access a lot, just put in these two variables and you can access the textbox and label directly:
public TextBox myTextBox;
public Label myLabel;
In the constructor of the user control do this:
myTextBox = this.txtSomeTextBox;
myLabel = this.lblSomeLabel;
Then in your program if you want to modify the text value of either just do this.
control[i].myTextBox.Text = "some random text"; // Same applies to myLabel
Hope it helped :)
Here is a simple example that should let you keep going add somethink that would act as a placeholder to your winform can be TableLayoutPanel
and then just add controls to it
for ( int i = 0; i < COUNT; i++ ) {
Label lblTitle = new Label();
lblTitle.Text = i+"Your Text";
youlayOut.Controls.Add( lblTitle, 0, i );
TextBox txtValue = new TextBox();
youlayOut.Controls.Add( txtValue, 2, i );
}
Suppose you have a button that when pressed sets n to 5, you could then generate labels and textboxes on your form like so.
var n = 5;
for (int i = 0; i < n; i++)
{
//Create label
Label label = new Label();
label.Text = String.Format("Label {0}", i);
//Position label on screen
label.Left = 10;
label.Top = (i + 1) * 20;
//Create textbox
TextBox textBox = new TextBox();
//Position textbox on screen
textBox.Left = 120;
textBox.Top = (i + 1) * 20;
//Add controls to form
this.Controls.Add(label);
this.Controls.Add(textBox);
}
This will not only add them to the form but position them decently as well.
You can try this:
int cleft = 1;
intaleft = 1;
private void button2_Click(object sender, EventArgs e)
{
TextBox txt = new TextBox();
this.Controls.Add(txt);
txt.Top = cleft * 40;
txt.Size = new Size(200, 16);
txt.Left = 150;
cleft = cleft + 1;
Label lbl = new Label();
this.Controls.Add(lbl);
lbl.Top = aleft * 40;
lbl.Size = new Size(100, 16);
lbl.ForeColor = Color.Blue;
lbl.Text = "BoxNo/CardNo";
lbl.Left = 70;
aleft = aleft + 1;
return;
}
private void btd_Click(object sender, EventArgs e)
{
//Here you Delete Text Box One By One(int ix for Text Box)
for (int ix = this.Controls.Count - 2; ix >= 0; ix--)
//Here you Delete Lable One By One(int ix for Lable)
for (int x = this.Controls.Count - 2; x >= 0; x--)
{
if (this.Controls[ix] is TextBox)
this.Controls[ix].Dispose();
if (this.Controls[x] is Label)
this.Controls[x].Dispose();
return;
}
}
I have a problem with my C# WinForm project.
In my project I have a function to draw a square, and I have a function that makes buttons at run time. What I want to do is that the button will place on the square.
I try to use 2 arrays; one gets the x location of the square, and the other gets the y location.
The button is placed at the x and y location one by one in columns but its place them diagonal.
int[] locationx = new int[100];
int[] locationy = new int[100];
int monex = 0;
int money = 0;
private void DrawAllSquares()//z,k its many square its going to draw
{
int tempy = y;
for (int i = 0; i < z; i++)
{
DrawingSquares(x, y);
for (int j = 0; j < k - 1; j++)
{
locationy[money] = tempy;
money++;
tempy += 60;
DrawingSquares(x, tempy);
}
x += 120;
locationx[monex] = x;
monex++;
tempy = y;
}
}
private void button2_Click(object sender, EventArgs e)
{
Button myText = new Button();
myText.Tag = counter;
//changeplace();
myText.Location = new Point(locationx[monex2], locationy[money2]);
monex2++;
money2++;
buttonList.AddLast(myText);
myText.Text = Convert.ToString(textBox3.Text);
this.Controls.Add(myText);
buttons[counter] = myText;
myText.BringToFront();
counter++;
}
You need do add created button to Form Controls collection.
private void button2_Click(object sender, EventArgs e)
{
Button myText = new Button();
myText.Tag = counter;
myText.Location = new Point(locationx[monex2], locationy[money2]);
Controls.Add(myText); // Assuming that handler 'button2_Click' is in your Form class.
// rest of your code
}
EDIT:
Button myText = new Button();
myText.Click += button2_Click;
I am trying to write a code in order to create dynamic textboxes.
I have Function class and have a second form in my program named ProductForm.cs
What I wanna do is to read some data with a function named GetSpecs in my Function.cs and than inside GetSpecs I want to call a function in another class and send data to my other function under ProductForm.cs class.
I am getting blank form at the end.
a part of my GetSpecs function:
private String GetSpecs(String webData)
{
......
ProductForm form2 = new ProductForm();
form2.CreateTextBox(n);
}
ProductForm.cs
public void CreateTextBox(int i)
{
ProductForm form2 = new ProductForm();
form2.Visible = true;
form2.Activate();
int x = 10;
int y = 10;
int width = 100;
int height = 20;
for (int n = 0; n < i; n++)
{
for (int row = 0; row < 4; row++)
{
String name = "txtBox_" + row.ToString();
TextBox tb = new TextBox();
tb.Name = name;
tb.Location = new Point(x, y);
tb.Height = height;
tb.Width = width + row * 2;
x += 25 + row * 2;
this.Controls.Add(tb);
}
y += 25;
}
}
I get a blank form of ProductForm. Textboxes are not created or I cannot see them.
If I put textbox inside
private void ProductForm_Load(object sender, EventArgs e)
I can see textboxes.
You're creating showing a brand new ProductForm instance (in the form2 variable), then adding controls to this (which is never shown).
You are adding the controls to the current form: this.Controls.Add(tb);, you need to add them to the other form:
form2.Controls.Add(tb);