Is there a way to put text or variables into the next array element without directly referencing what array element you want it in? For example:
private void btnAdd_Click(object sender, EventArgs e)
{
TextBox1.Text = array[0];
}
How could I get this to instead put it into element 0 but every time the button is clicked it automatically puts it into the next available one, array[0] then array[1].
My goal for this is that I have a large portion of code that only works for one array element but if I could automatically send the input into the next element I can just redirect each event handler to a new method containing the portion of code which would save me from just copy and pasting the code 5 times and just changing the element ID's.
Use List<string> array instead of string[] array
Example code:
private List<string> array = new List<string>();
private void btnAdd_Click(object sender, EventArgs e)
{
array.Add(TextBox1.Text);
}
Define a field called indexValue of type integer and increase it on every click event. For example:
private int indexValue; // defines a field to keep the current index
private void btnAdd_Click(object sender, EventArgs e)
{
array[indexValue++] = TextBox1.Text; // assigns the value entered by the user to the array on the next position
}
Related
I'm trying to make a sorting program with Windows Forms. The goal is to allow the user to create an array by taking a value from a trackBar that determines the size of the array. For example, if the trackbar value is set to 100, then the user would press the "Create Array" button, which would then generate an integer array with 100 numbers that are random and then display them on a Chart.
Then, the user would press another button to actually sort the array. However, because the array is defined in the scope of the button that actually creates the array, I don't know how to get it into the scope of the button that sorts it. After it is sorted, I want to keep the array sorted, so it needs to be changed on a global level.
I tried to define the variable on a class level within the Form1: Form class and have each control return a value, which would update the value for the array, but that doesn't work because my project doesn't have a static void Main() function, and I'm not sure how to implement that into Windows Forms with my current minimal knowledge of the program.
Code example is below:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// Initializes size of the array.
public int arraySize;
// Generates the array and links it to the chart for visualization.
private void button2_Click(object sender, EventArgs e)
{
// the dataArray takes in the arraySize and returns an array
// which is used to populate the chart.
arraySize = trackBar1.Value;
ArrayObject dataGenerator = new ArrayObject();
int[] dataArray = dataGenerator.GenerateData(arraySize);
chart1.Series["Data"].Points.Clear();
int placement = 0;
foreach (int dataPoint in dataArray)
{
this.chart1.Series["Data"].Points.AddXY(placement, dataPoint);
placement += 1;
}
}
// updates the label to show the current value that trackBar1 has selected.
private void trackBar1_Scroll(object sender, EventArgs e)
{
trackbarValueLabel.Text = trackBar1.Value.ToString();
}
private void buttonSort_Click(object sender, EventArgs e)
{
}
}
Worst-case scenario, I can create the array, chart it, sort, then re-chart it all within the same button control if need be, but I do want to keep them separated so the user can focus on creating a dataset they like, then have it sorted.
It sounds like you want the user to be able to do operations (sort) on the last array that was created. The last array represents a piece of state held by the form.
To make a form stateful, add a member variable at the form level. In this case you'd add an array and update it whenever you create an array.
public partial class Form1 : Form
{
protected int[] _latestArray = new int[] {} ;
public Form1()
{
InitializeComponent();
}
// Initializes size of the array.
public int arraySize = 0;
// Generates the array and links it to the chart for visualization.
private void button2_Click(object sender, EventArgs e)
{
// the dataArray takes in the arraySize and returns an array
// which is used to populate the chart.
arraySize = trackBar1.Value;
ArrayObject dataGenerator = new ArrayObject();
int[] dataArray = dataGenerator.GenerateData(arraySize);
chart1.Series["Data"].Points.Clear();
int placement = 0;
foreach (int dataPoint in dataArray)
{
this.chart1.Series["Data"].Points.AddXY(placement, dataPoint);
placement += 1;
}
//Save state
_latestArray = dataArray;
}
private void buttonSort_Click(object sender, EventArgs e)
{
Array.Sort(_latestArray);
}
}
I have a TextBox, a Button, and a Combobox
When I click the Button, I want the text in Textbox to be added to the Combobox Items
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
comboBox1.Items.Add(textBox1.Text);
}
My form until open. This text shows in the Combobox, but when I close the Form and open it again the text is not longer shown in the Combobox.
I want to save the text to the Collection Items of the Combobox. I don't want to use a database.
As others have mentioned in the comments, you need to understand and decide where you wish to store your values.
For the purpose of my example, I have created a simple text file to store these values. The code reads from the file and adds each line as an item into the ComboBox.
private void Form1_Load(object sender, EventArgs e)
{
// Read items from file into a string array
string[] items = System.IO.File.ReadAllLines(#"D:\ComboBoxValues.txt");
// Add items to the comobobox when opening the form
comboBox1.Items.AddRange(items);
}
private void button1_Click(object sender, EventArgs e)
{
// Add your new value to the combobox
comboBox1.Items.Add(textBox1.Text);
// Put all existing comobo box items into a string array
string[] items = comboBox1.Items.OfType<string>().ToArray();
// Save the array of items to a text file (this will not append, it will re-write the file)
System.IO.File.WriteAllLines(#"D:\ComboBoxValues.txt", items);
}
This may not be the most elegant way of going about it, but from the point of providing you an understanding - this should be more than sufficient.
if you don't like to use File System, you can use Preferences(but it's not recommendable to use preference to memorize large values), check this link to see how create a new setting
private void Form1_Load(object sender, EventArgs e)
{
string[] strItems = Properties.Settings.Default.items.Split(", ");
for(int i = 0; i < strItems.length; i++) {
comboBox1.Items.Add(strItems[i]);
}
}
private void button1_Click(object sender, EventArgs e)
{
//add your new value to the combobox
comboBox1.Items.Add(textBox1.Text);
//put all existing combo box items into a string array
string[] items = comboBox1.Items.OfType<string>().ToArray();
for(int i = 0; i < items.length; i++) {
//I assumed you had an items key in your settings
if(i == items.length - 1) {
Properties.Settings.Default.items += value;
} else {
Properties.Settings.Default.items += value + ", ";
}
}
//then you should to save your settings
Properties.Settings.Default.Save();
}
Within my system I have a text box and button that allows the user to input an integer to the list box. However, I want to include two radio buttons - sorted and unsorted, so that the user has to select whether they want the integer to be sorted or unsorted when added.
This is the code I have so far for the add button;
private void buttonAdd_Click(object sender, EventArgs e)
{
listBoxAddedIntegers.Items.Add(textBoxInsert.Text);
textBoxInsert.Text = string.Empty;
//MessageBox.Show(listBoxAddedIntegers.SelectedIndex.ToString());
MessageBox.Show(listBoxAddedIntegers.Items.Count.ToString());
}
this is the code for the radio button 'sorted;
private void radioButtonSorted_CheckedChanged(object sender, EventArgs e)
{
radioButtonSorted.Checked = true;
}
and this is the code for the 'unsorted' radio button -
private void radioButtonUnsorted_CheckedChanged(object sender, EventArgs e)
{
radioButtonSorted.Checked = false;
}
Does anyone have any suggestions on how to add an integer to the list, so that when the user selects the radio button 'sorted' and then clicks add integer, the integer is then added to the sorted list? Thank you.
Use your radio buttons to toggle the Sorted property of the listbox. According to documentation, it also ensures that
[as] items are added to a sorted ListBox, the items are moved to the appropriate location in the sorted list
So, you could write
private void radioButtonSorted_CheckedChanged(object sender, EventArgs e)
{
if((sender as RadioButton).Checked) listBoxAddedIntegers.Sorted = true;
}
private void radioButtonUnsorted_CheckedChanged(object sender, EventArgs e)
{
if((sender as RadioButton).Checked) listBoxAddedIntegers.Sorted = false;
}
You used the CheckedChanged event. It will fire not only when a radio button is selected, it will fire also for the other one that was unselected. Therefore it is necessary to query the actual check state in the handler.
There is a shortcoming though: Sorted is limited to alphabetical order. If you get 1, 10, 2, 3 but expect 1, 2, 3, 10 then you can left-pad your integers with zeroes to get 0001, 0002, 0003, 0010; or apply a solution like this which pre-sorts the data and then refreshes the entire listbox.
this will sort all the items from your list box if sorted is checked, still i don't think its necessary to have 2 redio buttons. you can replace that with single checkbox
List<int> numbers = new List<int>();
private void buttonAdd_Click(object sender, EventArgs e)
{
if (radioButtonSorted.Checked)
{
numbers.Clear();
if (!string.IsNullOrEmpty(textBoxInsert.Text))
numbers.Add(int.Parse(textBoxInsert.Text));
foreach (var item in listBoxAddedIntegers.Items)
{
if (item != null)
numbers.Add(int.Parse(item.ToString()));
}
listBoxAddedIntegers.Items.Clear();
numbers.Sort();
foreach (var number in numbers)
listBoxAddedIntegers.Items.Add(number);
}
else
listBoxAddedIntegers.Items.Add(textBoxInsert.Text);
textBoxInsert.Text = string.Empty;
//MessageBox.Show(listBoxAddedIntegers.SelectedIndex.ToString());
MessageBox.Show(listBoxAddedIntegers.Items.Count.ToString());
}
I'm trying to drag and drop a data row values from a data grid to list. I have two events in order to do that. but how can i pass two values?
This is the grid event
private void dgv_Mapper1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
//this works
//dgv_Mapper1.DoDragDrop(dgv_Mapper1.SelectedRows[0].Cells[0].Value, DragDropEffects.Copy);
//this is what i want, to send two values
dgv_Mapper1.DoDragDrop(new { First = dgv_Mapper1.SelectedRows[0].Cells[0].Value, Last = dgv_Mapper1.SelectedRows[0].Cells[1].Value }, DragDropEffects.Copy);
}
and this is list event
Problem is i don't understand how to access the object and get the two values.
private void list_Head1_DragDrop(object sender, DragEventArgs e)
{
//this works with one object
//list_Head1.Items.Add(e.Data.GetData(DataFormats.Text.ToString().Trim()));
}
This is the code:
private void button1_Click(object sender, EventArgs e)
{
List<string> user = new List<string>();
user.Add(usertextBox.Text);
I want it where each time I press the button, whatever is in usertextBox at that point gets added to the list 'user' as a new item, so I can recall the different ones later with [1], [2], [3], etc. I also want it so the user can close the app and all the users will still be saved. I I don't know if C# does this automatically
Even if you can only answer one of my questions that's fine. Thanks!!
In your code you are making List local to Button that means every time you click button new object of List is created, You should create it out side button click method. Try this.
List<string> user = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
user.Add(usertextBox.Text);
You have to define the List out side of the method. C# does not keep the content of the list.
private List<string> user = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
user.Add(usertextBox.Text);
}
for saving the content you could use a database (http://msdn.microsoft.com/en-us/library/bb655884%28v=vs.90%29.aspx) or an xml file (http://www.codeproject.com/Articles/7718/Using-XML-in-C-in-the-simplest-way).
to save the content of the List you could create a new class containing this two methods instead of the list
public List<string> getListContent()
{
//read xml-file
}
public void Add(string t)
{
//write to xml file
}
This will just fine work in single thread applications.