c# windows form application clear chart and reload error - c#

I have a c# windows form application.I have 2 charts in my windows form. i also have a combobox and two buttons among others. What i want is according to the text of the combobox, when i press the start button to load different graphs. So at button start event according to value of combobox i call a different function that loads the charts with what i want each time. And the second button , the stop button has the code below in order to clear the charts.
chart1.Series.Clear();
chart2.Series.Clear();
Sometimes my code runs ok but there are times that it throws the error
" A chart element with the name 'kwh_price' already exists in the 'SeriesCollection'." My code for load the chart is:
string[] seriesArray = { "kwh_price", "p_cost" };
for (int i = 0; i < seriesArray.Length; i++)
{
this.chart1.Series.Add(seriesArray[i]);
this.chart1.Series[seriesArray[i]].BorderWidth = 7;
}
Am i doing something wrong??is there something more needed in order to clear the chart?? And i don't understand why sometimes it runs ok and others not.

Put the clear code in before the load code. That way you can be sure the data is cleared before adding new data.
chart1.Series.Clear();
chart2.Series.Clear();
string[] seriesArray = { "kwh_price", "p_cost" };
for (int i = 0; i < seriesArray.Length; i++)
{
this.chart1.Series.Add(seriesArray[i]);
this.chart1.Series[seriesArray[i]].BorderWidth = 7;
}

Related

How to initialize an object within a for loop

I'm currently using Microsoft's Visual Studio 2019 and I'm trying to make a version of tic-tac-toe that allows the user to select the size of the board (3x3, 4x4, 5x5, etc...). I'm using buttons for the user input and I'm stuck on how I would go about initializing the needed buttons depending on the size of the board.
if (ThreeByThree)
{
for(int i = 1; i <= 9; i++)
{
Button ("btn" + i) = new Button();
}
This is the only way I could think about doing this but this results in an error, if anyone has encountered this issue I would appreciate some advice.
You can't dynamically create variable names, but you could add items to a list of buttons:
List<Button> buttons = new List<Button>();
if (ThreeByThree)
{
for(int i = 1; i <= 9; i++)
{
buttons.Add(new Button());
}
}
You can then reference the buttons by index - e.g. buttons[0] through buttons[8]

Cannot edit DataGridView cell, after choosing option I have to press Esc and lose the edit

So here is the story - I have 2 DataGridViews - one of them is used as a display, the other one is user for editing or adding new entries. I don't use bindings on the edit one. When I am creating new entry I am just extracting the cells' values and passing them to an object. When I am editing though comes the problem.
The edit consists of 2 parts - one is to select the entry to be edited and display it on the second DGV. This is done with SelectionChanged event and the code is bellow. Then when editing is done it should just publish the new task the same way as creation. The thing is that when I am doing the edit and I come to the moment when I have to select from one of my cells - a ComboBoxCell - and I make a selection everything freezes. I cannot click anything else than this ComboBox until I press Esc - which obviously reverts the choice.
Why is this freeze happening and what causes it only when the data is cloned from the first DGV, but is okay when creating a brand new row? I am using VS2012 by the way and this is a windows forms application
Here is the code for duplication of the selected task - this method is the only thing in the DGV1's SelectionChanged Event handler:
public void createTemplateTaskToBeEditted(Form1 form1, ApplicationControl appControl)
{
form1.dg_templateView.Rows.Clear();
for (int i = 0; i < form1.dg_taskView.SelectedRows.Count; i++)
{
if (form1.dg_taskView.SelectedRows[i].Cells[0].Value == null)
{
form1.dg_taskView.SelectedRows[i].Cells[0].Value = false;
}
int index = form1.dg_templateView.Rows.Add();
form1.dg_templateView.Rows[index].Cells[0].Value =
form1.dg_taskView.SelectedRows[i].Cells[0].Value.ToString();
form1.dg_templateView.Rows[index].Cells[1].Value =
form1.dg_taskView.SelectedRows[i].Cells[2].Value.ToString();
form1.dg_templateView.Rows[index].Cells[2].Value =
form1.dg_taskView.SelectedRows[i].Cells[3].Value.ToString();
form1.dg_templateView.Rows[index].Cells[3].ValueType = typeof(ComboBox);
form1.dg_templateView.Rows[index].Cells[3].Value =
form1.PopulateAssignToComboBox(appControl.GetAllowedMembers(form1));
form1.dg_templateView.Rows[index].Cells[4].Value =
form1.dg_taskView.SelectedRows[i].Cells[5].Value.ToString();
form1.dg_templateView.Rows[index].Cells[5].Value =
form1.dg_taskView.SelectedRows[i].Cells[6].Value.ToString();
form1.dg_templateView.Rows[index].Cells[6].Value =
form1.dg_taskView.SelectedRows[i].Cells[7].Value.ToString();
form1.dg_templateView.Rows[index].Cells[7].Value =
form1.dg_taskView.SelectedRows[i].Cells[8].Value.ToString();
form1.dg_templateView.Rows[index].Cells[8].Value =
form1.dg_taskView.SelectedRows[i].Cells[9].Value.ToString();
form1.dg_templateView.Rows[index].Cells[9].Value =
form1.dg_taskView.SelectedRows[i].Cells[10].Value.ToString();
form1.dg_templateView.Rows[index].Cells[10].Value =
form1.dg_taskView.SelectedRows[i].Cells[11].Value.ToString();
form1.dg_templateView.Rows[index].Cells[11].Value =
form1.dg_taskView.SelectedRows[i].Cells[12].Value.ToString();
}
}

How to move items from a checkedListBox to another checkedListBox

I made a program which adds checkedListBox.Items from a text written in a TextBox . Regarding this, to make everything more esthetic , I made a rule so that if the number of Items added in CheckedListBox1 is bigger than a number I set, it will go to a second CheckedListBox and so on.
I can also save my Entries in a .txt file so I have easy access to my previous references. So naturally I also made a Load References which ,obviously, load the file I saved.
Anyhow, my dillemma is the following : When I press the Load References button it loads ALL the references (Lines) in the text into the first checkedListBox. I want it to respect the previous law. If I click Load References I want that if there are more than, lets say, 10 entries, all the other ones will go into the other checkedListBox ,by consequence, if the limit number is passed from the second checkedListBox the rest will go into the third one and so on.
I have searched StackOverflow and the Web for several solutions ,some of the more relevant ones :
First found link semi-regarding the subject
Second found link
So to not get it wrong I will state that I want to have all the entries that pass the limit be MOVED to another checkedlistBox ,not copied like the links would suggest.
This is the Line of code for my Load Reference button :
private void button8_Click(object sender, EventArgs e)
{
string fileData = File.ReadAllText(#" To-Do References .txt");
checkedListBox1.Items.AddRange(fileData.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
}
Also I tried several methods but this one seemed to be the closest ,even though I got almost no satisfactory result :
var i = checkedListBox1.Items.Count;
if (i >= 10)
checkedListBox2.Items.Insert(0, checkedListBox1.Items);
Regarding this line of code : It does get an entry send into the second checkedList Box it is just that the entry is called (Collection) and has nothing to do with my references.
I hope I made myself clear and thank you for support!
UPDATE
The marked answer works perfectly for this kind of program. As I have not found anything similar I believe this is most likely the best way to implement the separation of text lines into different checkedListBoxes.
if you populate listboxes properly there will be no need to move items
private void button8_Click(object sender, EventArgs e)
{
int limit = 10;
string[] fileData = File.ReadAllText(#" To-Do References .txt").Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
// this loop adds items to the 1st list until limit is reached
for(int i =0; i<limit && i<fileData.Length; i++)
checkedListBox1.Items.Add(fileData[i]);
// if there extra items, 2nd loop adds them to list №2
for(int i =limit; i<fileData.Length; i++)
checkedListBox2.Items.Add(fileData[i]);
}
Set a limit, and maybe a multiplier to control the checkedList the data will be added to.
int limit = 10;
int checkList = 1;
string[] fileData = File.ReadAllText(#" To-Do References .txt").Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < fileData.Length; i++)
{
if (i == limit * checkList)
{
checkList++;
}
switch (checkList)
{
case 1: checkedListBox1.Items.Add(fileData[i]); break;
case 2: checkedListBox2.Items.Add(fileData[i]); break;
case 3: checkedListBox3.Items.Add(fileData[i]); break;
}
}
As big as your text file gets, adding data to a checkedListBox just requires you to add a new line to the switch statement.
Well, my head is stuck in wpf land, so I would just bind it to a list of lists, in an itemscontrol, or something similar. Reading back, of course, it appears you are using winforms, so this may not be applicable...but i'll post anyways, because it can still be done this way using the WinForms DataRepeater control.
List<List<string>> mainList = new List<List<string>>();
int listIndex = 0;
string[] fileData = File.ReadAllText(#" To-Do References.txt").Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
for(int i = 0; i<=fileData.Length; i++)
{
mainList[listIndex].Add(fileData[i]);
if (i%10 == 0)
{
listIndex++;
}
}
Then bind the mainList to the control and configure your ItemTemplate.
There was lots of info on binding to the DataRepeater, but here's one link:
https://msdn.microsoft.com/en-us/library/cc488279.aspx

How to change checkbox text in checkboxlist? I tried but got error message

I work on windows application. It has one form in application which displays check boxes in check box list, here is the screen shot of form
It's single from of my application which i display in different languages And also my windows application is made in multiple languages Like English, German, Japanese etc..
My problem is that how to display translated text of check box in check box list
Here is my code :
this.checkedListBox1.FormattingEnabled = true;
this.checkedListBox1.Items.AddRange(new object[] {
"Select All",
"Amplitude1",
"Amplitude2",
"Amplitude3",
"Amplitude4",
"Amplitude5",
"Amplitude6",
"Amplitude7"});
this.checkedListBox1.Location = new System.Drawing.Point(96, 55);
this.checkedListBox1.Name = "checkedListBox1";
this.checkedListBox1.Size = new System.Drawing.Size(123, 124);
this.checkedListBox1.TabIndex = 8;
this.checkedListBox1.SelectedIndexChanged += new System.EventHandler(this.ckbselectall_CheckedChanged);
I made a single file to translate text of form, i put that code below where LCheckBox is my file from where i translate the text of check box in check box list
this.checkedListBox1.FormattingEnabled = true;
this.checkedListBox1.Items.AddRange(new object[] {
LCheckBox.SELECTALL,
LCheckBox.Amplitude1,
LCheckBox.Amplitude2,
LCheckBox.Amplitude3,
LCheckBox.Amplitude4,
LCheckBox.Amplitude5,
LCheckBox.Amplitude6,
LCheckBox.Amplitude7});
this.checkedListBox1.Location = new System.Drawing.Point(96, 55);
this.checkedListBox1.Name = "checkedListBox1";
this.checkedListBox1.Size = new System.Drawing.Size(123, 124);
this.checkedListBox1.TabIndex = 8;
this.checkedListBox1.SelectedIndexChanged += new System.EventHandler(this.ckbselectall_CheckedChanged);
But it gives me some error message
you can ask for the language at the begining and then create the checkbox list depending on the language. u can use different if cases for each language
In code I just use the items collection to modify the desired item.
So lets say you have a form with a button on it. When the button is clicked
you want to add one to all the items in the list, then the code to do that
would look as found below assuming that the listbox was named "_list" and
the button was named "_button."
private void FillList()
{
_list.BeginUpdate();
_list.Items.Clear();
for(int i =0 ; i <=9; i++)
_list.Items.Add(i);
_list.EndUpdate();
}
private void _button_Click(object sender, System.EventArgs e)
{
_list.BeginUpdate();
ListBox.ObjectCollection items = _list.Items;
int count = items.Count;
for(int i = 0; i < count; i++)
{
int integerListItem = (int)items[i];
integerListItem ++;
// --- Update The Item
items[i] = integerListItem;
}
_list.EndUpdate();
}

Dynamically create text inputs (ASP.net/C#)

I have an input field on my page where the user will type in the number of text inputs they want to create. The action for the button is:
int num_flds = int.Parse(a_fld.Text);
for (int i = 0; i < num_flds; i++)
{
TextBox tmp = new TextBox();
tmp.ID = "answer_box" + i;
tmp.Width = Unit.Pixel(300);
answer_inputs.Controls.Add(tmp);
}
Now, I have another button that the user would click after they have filled in all their dynamically-created text boxes. Questions, first of all, am I creating the text boxes dynamically in the correct place? How would I get the values out of the dynamically-created text boxes? (The dynamically-created text boxes are being added to the Panel "answer_inputs".
I recommend reading this and a few other articles about the topic of dynamically created controls. It is not quite as straightforward as you might think. There are some important page lifecycle issues to consider.
When creating web controls dynamically, I find it best to have the controls themselves report in the answers. You can achieve it like this:
Create something in your Page class to store the values:
private readonly Dictionary<TextBox, string> values=new Dictionary<TextBox, string>();
Make a method to act as a callback for the textboxes when their value changes:
void tmp_TextChanged(object sender, EventArgs e)
{
TextBox txt = sender as TextBox;
if(txt!=null)
{
values.Add(txt,txt.Text);
}
}
And then add this method to each textbox as they are added:
int num_flds;
if(!int.TryParse(a_fld.Text,out num_flds))
{
num_flds = 0;
}
for (int i = 0; i < num_flds; i++)
{
TextBox tmp = new TextBox();
tmp.ID = "answer_box" + i;
tmp.Width = Unit.Pixel(300);
answer_inputs.Controls.Add(tmp);
tmp.TextChanged += tmp_TextChanged;
}
Finally, you iterate through the dictionary on callback to see if it holds any values. Do this in the OnPreRender method for instance.
Edit: There is a problem with this, if the number of text fields are decreased on postback. Some safe way to recreate the previous textfields on postback should be employed.

Categories

Resources