I'm pretty new to C#. I want to increment an int variable id by 1 and insert it into a datagridview. The problem is, it doesn't increment, it stays at 1.
Here's my code for adding the data to datagridview
class QuantityCtrl : Quantity
{
private ManageSale _manageSale;
public QuantityCtrl(ManageSale manageSale)
{
_manageSale = manageSale;
}
private void BtnOk_Click(object sender, EventArgs e)
{
_manageSale.dgvItemList.Rows.Add
(
GenerateId(),
_manageSale.lblName.Text,
_manageSale.lblPrice.Text,
_manageQuantity.txtDiscount.Text,
_manageQuantity.txtQuantity.Text,
Total
);
}
}
Here's my code for incrementing
class Quantity
{
public int OrderId = 1;
public int GenerateId()
{
return OrderId++;
}
}
Another way of doing it would be creating a new class in a folder inside your solution which contains the list and the proprieties :
class IDS
{
#region Proprieties
public int Id { get; set; }
#endregion
#region Lists
public List<IDS> _ids = new List<IDS>();
#endregion
}
Now, you'll need to link the class to the main, for that, go in your main code and put at the top :
using SolutionName.Folder;
Next go to your button event and simply put this:
private void btnAutoGen_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
int iId = 0;
try
{
var req = (from value in _id
select value.Id).Max() + 1;
iId = req;
}
catch (InvalidOperationException)
{
iId = 1;
}
You now have a button that auto increment.
I solved it thanks to Brendan. I hope it could be a referrence for some developers :) and If someone has a better way of incrementing you can answer it Thank you.
public static int OrderId = 1;
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);
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 created a ListBoxItem where I have a property Name and override ToString() to give back name. That works nicely when I add new items.
But now I need to force the ListBox to update the labels when I change the name of my ship. I thought Refresh or Update would do that but that doesn't work.
I might be missing something very easy here.
public class ShipListBoxItem
{
public ListBox Parent { get; set; }
public ShipType Ship { get; set; }
public ShipListBoxItem()
{
Ship = new ShipType();
}
public ShipListBoxItem(ShipType st)
{
Ship = st;
}
public override string ToString()
{
return Ship.Name;
}
public void UpdateListBox()
{
Parent.Refresh(); //My problem is here. Update doesn't work either.
}
public static ShipListBoxItem AddToListBox(ListBox lb, ShipType ship)
{
ShipListBoxItem li = new ShipListBoxItem(ship);
li.Parent = lb;
lb.Items.Add(li);
return li;
}
}
If you use a List<T> as the DataSource for the listbox it is pretty easy to have changes to items show up. It also means there is no real reason to have a special class for adding a ShipListBoxItem to a ListBox, your basic Ship class may work:
class ShipItem
{
public enum ShipTypes { BattleShip, Carrier, Destroyer, Submarine, Frigate };
public ShipTypes Ship { get; set; }
public string Name { get; set; }
public ShipItem(string n, ShipTypes st)
{
Name = n;
Ship = st;
}
public override string ToString()
{
return String.Format("{0}: {1}", Ship.ToString(), Name);
}
}
The form related stuff:
private void Form1_Load(object sender, EventArgs e)
{
// add some ships
Ships = new List<ShipItem>();
Ships.Add(new ShipItem("USS Missouri", ShipTypes.BattleShip));
Ships.Add(new ShipItem("USS Ronald Reagan", ShipTypes.Carrier));
lb.DataSource = Ships;
}
private void button1_Click(object sender, EventArgs e)
{
// change a ship name
lb.DataSource = null; // suspend binding
this.Ships[0].Name = "USS Iowa";
lb.DataSource = Ships; // rebind
lb.Refresh();
}
As an alternative, you can also tell the Listbox to use a specific property for the display using DisplayMember:
lb.DataSource = Ships;
lb.DisplayMember = "Name";
This would use the Name property in the listbox instead of the ToString method. If your list is changing a lot, use a BindingList instead. It will allow changes to the list show up in the ListBox as you add them without toggling the DataSource.
Try this
ListBox.RefreshItems()
msdn
EDIT: You can use an extended class like this:
public class FooLisBox : System.Windows.Forms.ListBox
{
public void RefreshAllItems()
{
RefreshItems();
}
}
private void button1_Click(object sender, EventArgs e)
{
(listBox1.Items[0] as ShipListBoxItem).Ship.Name = "AAAA";
listBox1.RefreshAllItems();
}
I managed to solve my problem.
Mostly, thanks Jose M.
I ran into a problem however. RefreshItems() triggers OnSelectedIndexChanged()
so my overridden class looks like this
public class MyListBox : ListBox
{
public bool DoEvents{ get; set; } // Made it public so in the future I can block event triggering externally
public MyListBox()
{
DoEvents = true;
}
public void RefreshAllItems()
{
SuspendLayout();
DoEvents = false;
base.RefreshItems(); // this triggers OnSelectedIndexChanged as it selects the selected item again
DoEvents = true;
ResumeLayout();
}
// I only use this event but you can add all events you need to block
protected override void OnSelectedIndexChanged(EventArgs e)
{
if (DoEvents)
base.OnSelectedIndexChanged(e);
}
}
I have the following, and it works:
My player class:
public Player(string Str, string SP)
{
Strength = Str;
StatPoints = SP;
}
public string StatPoints
{
get;
set;
}
public string Strength
{
get;
set;
}
Now on my form1 I have a textbox, and a button. The button increments the value in the textbox by one so long as there is a value above 0 in the SP textbox. Problem is, I am declaring six variables in order to manage two values because I have to convert strings to ints and all that crap. Is there a way to replace text boxes with something that is inherently int? Here is my character sheet code so far.
private void AddButton_Click(object sender, EventArgs e)
{
Player PCStats = new Player(StrBox.Text, SPBox.Text);
int IntPCSP = Convert.ToInt16(PCStats.StatPoints);
int IntPCStr = Convert.ToInt16(PCStats.Strength);
if (IntPCSP >= 1 && IntPCStr <= 7)
{
IntPCStr++;
IntPCSP--;
PCStats.Strength = IntPCStr.ToString();
PCStats.StatPoints = IntPCSP.ToString();
StrBox.Text = PCStats.Strength;
SPBox.Text = PCStats.StatPoints;
}
else
{
MessageBox.Show("Earn more experience!");
}
/*
MessageBox.Show("PCStats.StatPoints equals" + PCStats.StatPoints);
MessageBox.Show("PCStats,Strength equals" + PCStats.Strength);
MessageBox.Show("IntPCSP Equals" + IntPCSP.ToString());
MessageBox.Show("IntPCStr Equals" + IntPCStr.ToString());
*/
}
Or is there an even easier way to do this I completely overlooked. I was super excited to finally get this bit to work after a lot of trial and error, but I am open to redoing it. I would rather however just replace the text boxes so I am not converting variables all over the place.
This is quick go, not at a computer with Visual Studio on it but should give you a start. Also, try naming your variables etc to have a bit more meaning. Also, this is to fix what you has as-is but see my update / suggestion further down about moving logic into the Player class...
My player class:
public Player(int strength, int statPoints)
{
this.Strength = strength;
this.StatPoints = statPoints;
}
public int StatPoints { get; set; }
public int Strength { get; set; }
My Form:
private void AddButton_Click(object sender, EventArgs e)
{
Player thePlayer = new Player(int.Parse(StrBox.Text), int.Parse(SPBox.Text));
if (thePlayer.StatPoints > 0 && thePlayer.Strength < 8)
{
thePlayer.Strength++;
thePlayer.StatPoints--;
StrBox.Text = thePlayer.Strength.ToString();
SPBox.Text = thePlayer.StatPoints.ToString();
}
else
{
MessageBox.Show("Earn more experience!");
}
}
Obviously you would need to check that the values in the text box were integers. You could use another control, mask the text box etc or on the code replace int.Parse with int.TryParse which checks it is possible before conversion. Just a few ideas to get you going!
- UPDATE -
Another thing you could do is more the logic into the Player class. This is better as it keep the logic contained in one place so you can see what a Player can DO rather than having to search the whole program:
New Player class:
// The Player class
public class Player
{
// Constructor
public Player(int strength, int statPoints)
{
this.Strength = strength;
this.StatPoints = statPoints;
}
// Method to gain strength if enough StatPoints
public bool GainStrength()
{
bool playerHasEnoughStatPoints = true;
if (this.StatPoints < 1)
{
playerHasEnoughStatPoints = false;
}
else if (this.Strength < 8)
{
this.Strength++;
this.StatPoints--;
}
return playerHasEnoughStatPoints;
}
// Property for StatPoints
public int StatPoints { get; set; }
// Property for Strength
public int Strength { get; set; }
}
New Form:
// The Form or similar
public class MyFormOrSimilar
{
// When button pressed try and add strength to the player
protected void AddButton_Click(object sender, EventArgs e)
{
// Create new INSTANCE of the player and try to give them strength
Player thePlayer = new Player(int.Parse(StrBox.Text), int.Parse(SPBox.Text));
if (thePlayer.GainStrength())
{
StrBox.Text = thePlayer.Strength.ToString();
SPBox.Text = thePlayer.StatPoints.ToString();
}
else
{
MessageBox.Show("Earn more experience!");
}
}
}
I am struggling with the WinForms DataGridView. I have a class, that I use as element to be displayed:
public class BorderFlowHistoryElement
{
public string nodeTitles { get; set; }
public double borderFlowRatio { get; set; }
...
}
I created a list of these elements:
List<BorderFlowHistoryElement> clusterHistory
which contains a list of thise elements, that should be displayed in my DataGridView. I bound the list at the DataSource of the Grid:
dataGridViewCluster.DataSource = clusterHistory;
Now the DataGridView displays the list. Now I want to format the columns which display the double values to display 5 digits. I tried it with:
dataGridViewCluster.Columns[1].DefaultCellStyle.Format = "n5";
but this has no effect on the column. Anyone knows, how I can do it right?
Additionally, I want to size the columnwidth to optimal fit for the largest entry.
Thanks in advance,
Frank
I have replicated what you have done and I had no issue whatsoever. Have you validated your data to ensure that you can actually get the results that you want?
Here is what I did just for your reference:
private void button1_Click(object sender, EventArgs e)
{
IList<BorderFlowHistoryElement> clusterHistory = FillClusterHistory();
dataGridView1.DataSource = clusterHistory;
dataGridView1.Columns[1].DefaultCellStyle.Format = "n5";
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
}
private static IList<BorderFlowHistoryElement> FillClusterHistory()
{
IList<BorderFlowHistoryElement> clusterHistory = new List<BorderFlowHistoryElement>();
for(int i = 5000; i < 5020; i++)
{
BorderFlowHistoryElement element = new BorderFlowHistoryElement();
element.nodeTitles = Guid.NewGuid().ToString();
element.borderFlowRatio = i * 3.3.1415672467234823499821D;
clusterHistory.Add(element);
}
return clusterHistory;
}
}
public class BorderFlowHistoryElement
{
private string _NodeTitles;
private double _BorderFlowRatio;
public string nodeTitles
{
get { return _NodeTitles; }
set { _NodeTitles = value;}
}
public double borderFlowRatio
{
get { return _BorderFlowRatio; }
set { _BorderFlowRatio = value;}
}
}
I hope that helps in some fashion. As you can see you can do the auto sizing as well.