Basically I have a string array with a few text values in it. I want to on load assign a value from the array to a string then on button press change it to the next value, once it gets to the end it needs to loop around. So the string will be set to one value in the array then get changed after a button click.
Array stringArray = Array.CreateInstance(typeof(String), 3);
stringArray.SetValue("ssstring", 0);
stringArray.SetValue("sstring", 1);
stringArray.SetValue("string", 2);
Here's some code to get you going. You dont mention what environment you're using (ASP.NET, Winforms etc..)
When you provide more info I'll update my example so its more relevant.
public class AClass
{
private int index = 0;
private string[] values = new string[] { "a", "b", "c" };
public void Load()
{
string currentValue = this.values[this.index];
}
private void Increment()
{
this.index++;
if (this.index > this.values.Length - 1)
this.index = 0;
}
private void button1_Click(object sender, EventArgs e)
{
Increment();
}
}
Set Index = 0
Let Count = StringArray.Count
On Button Click Do the following
Set Return Value As StringArray(Index)
Set Index = ( Index + 1 ) Mod Count
You can program that algorithm in C#...
You could have a class that holds and iterates your strings like:
class StringIterator
{
private int _index = 0;
private string[] _strings;
public StringIterator(string[] strings)
{
_string = strings;
}
public string GetString()
{
string result = _string[_index];
_index = (_index + 1) % _strings.Length;
return result;
}
}
The usage would look like
class Program
{
private string _theStringYouWantToSet;
private StringIterator _stringIter;
public Program()
{
string[] stringsToLoad = { "a", "b", "c" };
_stringIter = new StringIterator(stringsToLoad);
_theStringYouWantToSet = _stringIter.GetString();
}
protected void ButtonClickHandler(object sender, EventArgs e)
{
_theStringYouWantToSet = _stringIter.GetString();
}
}
Related
Code On Windows form is
private void button2_Click(object sender, EventArgs e)
{
CandleCollection collection = GetCandleCollection();
int Dim = int.Parse(txt_agent.Text);
int NumParticles = int.Parse(txt_part.Text);
SOSManager p = new SOSManager(collection);
//this part
p.Dim = Dim;
p.NumParticles = NumParticles;
m_part = new ParticleSwarm(fit,p.Dim, p.NumParticles);
}
So,I want to add value that i put on textbox to this class.
public class SOSManager
{
private ParticleSwarm m_part;
public ParticleSwarm BackTestPartReport
{
get
{
return m_part;
}
}
I declare this
public int Dim; //this part
public int NumParticles;
public double fit;
to add value .
public SOSManager(CandleCollection collection)
{
CandleList = collection;
Calculate();
m_backTesting = new BackTesting(this);
fit = m_backTesting.fitness;
//this part
m_part = new ParticleSwarm(fit, Dim, NumParticles);
m_part.Calculate(Dim,NumParticles);
//
}
Now,I can't get value from windows from into this class . What should i do ?
Instead of setting the properties when it's too late, pass them into a constructor with more parameters:
public SOSManager(CandleCollection collection, int Dim, int NumParticles)
{
// If you still need to store them as properties:
this.Dim = Dim;
this.NumParticles = NumParticles;
Then call it like this:
SOSManager p = new SOSManager(collection, Dim, NumParticles);
I am doing MVC and I am new at it. I am making a game where 5 dice roll by clicking on the 'roll dice' button and show random numbers. Under each die label there is a check box. If the player clicks on the check box the dice don't roll again and the other dice do roll.
I can show dice numbers in my view but I don't understand how to make it so the dice don't roll if you check the checkbox. I translated my program because it's in dutch: Waarde=value; dobbesteen=dice; werp=throw.
public class Dobbelsteen
{
Random rnd = new Random();
public int Waarde { get; set; }
public bool Checked { get; set; }
public int Worpen { get; set; }
public void Rollen()
{
if (Checked == false)
Waarde = rnd.Next(1, 7);
}
}
public class BusinessController
{
List<int> dice = new List<int>();
Dobbelsteen objdobbelsteen = new Dobbelsteen();
public BusinessController()
{
}
public int Roll()
{
for (int i = 0; i < 5; i++)
{
objdobbelsteen.Rollen();
dice.Add(i);
}
return objdobbelsteen.Waarde;
}
public int Werp()
{
objdobbelsteen.Worpen++;
return objdobbelsteen.Worpen;
}
public int nietroll()
{
int i = 1;
return i;
}
/*public bool Winnaar()
{
if (dice[1] == dice[2])
{
return true;
}
else return false;
}*/
public void SetLock(int p)
{
if(objdobbelsteen.Checked==false)
{
nietroll();
}
}
}
public partial class Form1 : Form
{
BusinessController busniessController = new BusinessController();
public Form1()
{
InitializeComponent();
}
public void Gooien_Click(object sender, EventArgs e)
{
lblWorpen.Text = Convert.ToString(busniessController.Werp());
dblsteen1.Text = Convert.ToString(busniessController.Roll());
dblsteen2.Text = Convert.ToString(busniessController.Roll());
dblsteen3.Text = Convert.ToString(busniessController.Roll());
dblsteen4.Text = Convert.ToString(busniessController.Roll());
dblsteen5.Text = Convert.ToString(busniessController.Roll());
if (dblsteen1.Text==dblsteen2.Text)
MessageBox.Show("u win");
}
public void checkBox1_CheckedChanged(object sender, EventArgs e)
{
busniessController.SetLock(1);
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
busniessController.SetLock(2);
}
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
busniessController.SetLock(3);
}
private void checkBox4_CheckedChanged(object sender, EventArgs e)
{
busniessController.SetLock(4);
}
private void checkBox5_CheckedChanged(object sender, EventArgs e)
{
busniessController.SetLock(5);
}
}
You need 5 different dices, not just one. In this way each dice can have its own Checked property set to a different value
List<Dobbelsteen> dices = new List<Dobbelsteen>()
{
{new Dobbelsteen()},
{new Dobbelsteen()},
{new Dobbelsteen()},
{new Dobbelsteen()},
{new Dobbelsteen()}
};
public void RollAll()
{
for (int i = 0; i < 5; i++)
dices[i].Rollen();
}
public int GetDiceValue(int i)
{
if(i >= 0 && i <= dices.Count)
return dices[i].Waarde;
else
throw new IndexOutOfRangeException($"Invalid index {i}");
}
public void SetLock(int p)
{
if(p >= 0 && p <= dices.Count)
return dices[p].Checked = true;
else
throw new IndexOutOfRangeException($"Invalid index {p}");
}
Also you should make your Random variable of the class DobbelSteen static otherwise the strict loop inside the Rollen method results in the same value returned for every dice.
After this you can call
busniessController.RollAll();
dblsteen1.Text = busniessController.GetDiceValue(0).ToString();
dblsteen2.Text = busniessController.GetDiceValue(1).ToString();
dblsteen3.Text = busniessController.GetDiceValue(2).ToString();
dblsteen4.Text = busniessController.GetDiceValue(3).ToString();
dblsteen5.Text = busniessController.GetDiceValue(4).ToString();
Finally remember that in NET the index for a collection like a list starts at zero and ends to the collection count - 1. So your call to SetLock should be changed accordingly to avoid the exception
You never actually set the "Checked" value, SetLock refers to the nietRol function which just sets an int. Here you need to set the "Checked" value to true.
And please programmeer niet in het Nederlands maar doe alles in het Engels.
enter image description here
Ok i need little help with this project. This is my main windows in widows Form
and this is code from MainForm:
using System;
using System.Windows.Forms;
namespace TestNiCat1
{
public partial class Form1 : Form
{
private Atleticar atleticar;
public Atleticar noviAtleticar { get { return atleticar; } }
public string tipDiscipline;
private string imeDiscipline { get; set; }
private int brojUcesnika { get; set; }
public string [] nizUcesnika { get; set; }
public string[] getskakac()
{
string[] arr = new string[listBox1.Items.Count];
for (int i = 0; i < listBox1.Items.Count; i++)
{
arr[i] = listBox1.Items[i].ToString();
}
return arr;
}
//listBox2.trkac to array
public string[] getTrkac()
{
string[] arr1 = new string[listBox2.Items.Count];
for (int i = 0; i < listBox1.Items.Count; i++)
{
arr1[i] = listBox2.Items[i].ToString();
}
return arr1;
}
public Form1()
{
InitializeComponent();
}
private void buttonDodaj_Click(object sender, EventArgs e)
{
if (radioButtonSkok.Checked)
{
atleticar = new Skakac(textBoxIme.Text,textBoxPrezime.Text,float.Parse(textBoxRezultat.Text));
this.listBox1.Items.Add(atleticar);
}
else if (radioButtonPrepone.Checked)
{
atleticar = new Trkac(textBoxIme.Text, textBoxPrezime.Text, float.Parse(textBoxRezultat.Text));
this.listBox2.Items.Add(atleticar);
}
}
private void buttonTrazi_Click(object sender, EventArgs e)
{
if (radioButtonSkok.Checked)
{
getskakac();
}
else if (radioButtonPrepone.Checked)
{
getTrkac();
}
}
}
}
i have 1 abstract class and 2 classes code :
namespace TestNiCat1
{
public abstract class Atleticar
{
protected string ime { get; set; }
protected string prezime { get; set; }
protected float rezultat { get; set; }
public override string ToString()
{
return ime + " " + prezime + " " + rezultat;
} }//abstract Atleticar
public class Skakac : Atleticar
{
private String tip;
public Skakac(String ime,String prezime,float rezultat)
{
this.rezultat = rezultat;
this.ime = ime;
this.prezime = prezime;
}
}public class Trkac : Atleticar
{
public Trkac(String ime,String prezime,float rezultat)
{
this.rezultat = rezultat;
this.ime = ime;
this.prezime = prezime;
}
}
}
what i need is to List all items when pressed Trazi button that will be stored into Listbox1 or listbox2 and sort them by highest result stored.
I made when i press trazi button to store all listbox items into String Array but i need help hot to sort them by highest score and show them into new messageBox OR if there is a way to sort items in listBox immidiatly as they been made in listbox by highest number.
I think this is what you look for
public string[] getskakac()
{
listBox1.Sorted = true;
return listBox1.Items.Cast<string>().ToArray();
}
It appears you may be better off having your abstract class Atleticar implement an IComparable interface. This will make sorting much easier and give you complete control over how Atleticar objects are sorted.
First you need to indicate that the Atleticar class will implement a CompareTo method for sorting:
public abstract class Atleticar : IComparable
Below is the CompareTo method needed when you implement the IComparable interface. I simply compare each object based on the rezultat variable but you can customize this to sort on another variable(s) if needed.
public int CompareTo(object obj) {
Atleticar other = (Atleticar)obj;
if (this.rezultat == other.rezultat)
return 0;
if (this.rezultat > other.rezultat)
return 1;
else
return -1;
}
Below I created a form with a ListBox and two buttons. One button fills the list box with some unsorted Atleticar objects. Button two sorts the list. I do not think you can directly sort the listbox1.Items so I created a list of Atleticar objects from the list box items and then sorted it, cleared the list box items then update it with the sorted data.
private List<Atleticar> GetData() {
List<Atleticar> list = new List<Atleticar>();
Atleticar atl = new Trkac("textBoxIme.Text1", "textBoxPrezime.Text1", 12);
list.Add(atl);
atl = new Trkac("textBoxIme.Text2", "textBoxPrezime.Text2", 1);
list.Add(atl);
atl = new Trkac("textBoxIme.Text3", "textBoxPrezime.Text3", 122);
list.Add(atl);
atl = new Trkac("textBoxIme.Text4", "textBoxPrezime.Text4", 99);
list.Add(atl);
atl = new Trkac("textBoxIme.Text5", "textBoxPrezime.Text5", 03);
list.Add(atl);
atl = new Trkac("textBoxIme.Text6", "textBoxPrezime.Text6", 67);
list.Add(atl);
atl = new Trkac("textBoxIme.Text7", "textBoxPrezime.Text7", -12);
list.Add(atl);
return list;
}
private void buttonGetData_Click(object sender, EventArgs e) {
listBox1.Items.Clear();
foreach (Atleticar a in GetData()) {
listBox1.Items.Add(a);
}
}
private void buttonSort_Click(object sender, EventArgs e) {
List<Atleticar> list = new List<Atleticar>();
foreach (Atleticar a in listBox1.Items) {
list.Add(a);
}
list.Sort();
listBox1.Items.Clear();
foreach (Atleticar a in list) {
listBox1.Items.Add(a);
}
}
Hope this makes sense.
I have this short windows form application code that i cannot get to work properly. It uses an instance of a class (as a temporary storage place) to populate an array of the same class type. It has a button and a textbox. If you press the button, the text is saved in the Name member and added to the array.
If the Name is taken by another array member, it should show a message "name taken!" and not add it to the array. The problem is that this condition check is always true!
if we type in "Marry", the debugger shows that
if (examleArray[i].Name == temp.Name)
is equivalent to:
if ("Marry" == "Marry")
as if one is pointing to the other. Why is this? how do i fix it? thank you!
namespace errorexample
{
public partial class Form1 : Form
{
example temp = new example();
example[] examleArray = new example[10];
int examleArrayIndex = 0;
bool NameTaken = false;
public Form1()
{ InitializeComponent(); }
private void button1_Click(object sender, EventArgs e)
{
temp.Name = textBox1.Text;
NameTaken = false;
for (var i = 0; i < (examleArrayIndex); i++)
{
if (examleArray[i].Name == temp.Name)
{
NameTaken = true;
MessageBox.Show("Name taken!");
}
}
if (NameTaken == false)
{
examleArray[examleArrayIndex] = temp;
examleArrayIndex++;
}
}
}
public class example {
public string Name;
}
}
You only have one temp object, and you add keep adding it to the array. It's the same temp since you never create a new one. I've rewritten it for you:
List<example> examleArray = new List<example>();
private void button1_Click(object sender, EventArgs e)
{
if (examleArray.Any(e=>e.Name == textBox1.Text))
{
MessageBox.Show("Name taken!");
} else {
examleArray.Add(new example { Name = textBox1.Text });
}
}
I've also converted your fixed array into a List so you don't ever accidentally try and add 11 names and then blow up. And I've converted your search to LINQ to simplify.
You only create one example object. You are putting multiple references to the same object into the array. One solution is to create a new example object to put in the array:
public class example {
public string Name;
public example( string name ){
Name = name;
}
}
//...
examleArray[examleArrayIndex] = new example( temp.Name );
move temp object initialization inside the click event, otherwise you are updating same object
private void button1_Click(object sender, EventArgs e)
{
example temp = new example();
temp.Name = textBox1.Text;
NameTaken = false;
for (var i = 0; i < (examleArrayIndex); i++)
{
if (examleArray[i].Name == temp.Name)
{
NameTaken = true;
MessageBox.Show("Name taken!");
}
}
if (NameTaken == false)
{
examleArray[examleArrayIndex] = temp;
examleArrayIndex++;
}
}
you can use List
List<string> example =
new List<string>();
if(example.Contains(textBox1.Text))
{
MessageBox.Show("Name taken!");
}else
{
example.Add(textBox1.Text);
}
I have a List of string type in which I am storing some values and then inserting them into the database. Now I want to show those values into the Gridview when I fill my GridView data source with that List it only shows the total number of characters of each value in the list. Is there any procedure that I show the list values into the DataGridView.
My code below is as follows:
private void GenerateButton_Click(object sender, EventArgs e)
{
List<string> SerialNumberList = new List<string>();
int SerialNumberStart = Convert.ToInt32(Regex.Replace(StartSerialBox.Text, "[^0-9]+", string.Empty));
int SerialLimit = Convert.ToInt32(LimitBox.Text);
for (int i = 0; i < SerialLimit;i++ )
{
SerialNumberStart++;
SerialNumberList.Add("S" + SerialNumberStart);
}
for (int j = 0; j < SerialNumberList.Count;j++ )
{
Adapter.insertserialnumbers(SerialNumberList[j] , DateTime.Now.ToString()); //Insertiona Procedure which will save the values into the database.
}
SerialGridView.DataSource = SerialNumberList ;
}
you can use BindingList
for example :
protected void GenerateButton_Click(object sender, EventArgs e)
{
BindingList<ListType> SerialNumberList = new BindingList<ListType>();
int x = 5;
SerialNumberList.Add(new ListType(x.ToString()));
grid.DataSource = SerialNumberList;
grid.DataBind();
}
}
public class ListType
{
public ListType()
{ }
private string Itemname;
public ListType(string _ListItem)
{
ListItem = _ListItem;
}
public string ListItem
{
get { return Itemname; }
set { Itemname = value; }
}
}
You can add extention method for IEnumerable(here List) type object from this SO question. Use this extention method to create DataTable from SerialNumberList and bind to DGV like this:
SerialGridView.DataSource = SerialNumberList.ToDataTable();