How to Multiply Data Gridview two columns and show the result in another column - c#-4.0

I have a gridview (Order) with three columns:
Price
Quantity
Total
I want to multiply Price with Quantity and show the result in Total column of dataGridview.
Remember: my dataGridview isn't bind with any table.
I am trying this code to achieve my goal but this isn't working means value isn't being returned:
private void totalcal()
{
// is the foreach condition true? Remember my gridview isn't bound to any tbl
foreach (DataGridViewRow row in gvSale.Rows)
{
int a = Convert.ToInt32(row.Cells[3].Value) * Convert.ToInt32(row.Cells[4].Value); // value is null why??
row.Cells[5].Value = a;
}
}
This is the method which I am calling on a button click. (It is not working reason define inside of my code above)
And plus I want to know which is the suitable Datagridview event for this calculation?? I don't want to calculate the total on button click

try
int.Parse(row.Cells[3].Value.toString()) * int.Parse(row.Cells[4].Value.toString())
insted of
Convert.ToInt32(row.Cells[3].Value) * Convert.ToInt32(row.Cells[4].Value)
And you know you can call this method anytime, if you dont want it to be with button click. Call it after gvSale's row populating operations finished.
EDIT
I guess you want the calculations to be done while the user is entering Price or Quanitity. For that you need to write a EditingControlShowing method for your datagridview. Here's a piece of code. I tested it actually and got it working.
Add this code in your main class definition after InitializeComponent(); line
gvSale.EditingControlShowing += new System.Windows.Forms.DataGridViewEditingControlShowingEventHandler(this.gvSale_EditingControlShowing);
And then add this methods :
TextBox tb = new TextBox(); // this is just a textbox to use in editing control
int Price_Index = 3; // set this to your Price Column Index
int Quantity_Index = 4; // set this to your Quantity Column Index
int Total_Index = 5; // set this to your Total Column Index
private void gvSale_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (gvSale.CurrentCell.ColumnIndex == Price_Index || gvSale.CurrentCell.ColumnIndex == Quantity_Index)
{
tb = e.Control as TextBox;
tb.KeyUp += new KeyEventHandler(Calculate_Total);
}
}
private void Calculate_Total(object sender, KeyEventArgs e)
{
int Price_Value = 0;
int Quantity_Value = 0;
int.TryParse(gvSale.CurrentCell.ColumnIndex != Price_Index ? gvSale.CurrentRow.Cells[Price_Index].Value.ToString() : tb.Text, out Price_Value);
int.TryParse(gvSale.CurrentCell.ColumnIndex != Quantity_Index ? gvSale.CurrentRow.Cells[Quantity_Index].Value.ToString() : tb.Text, out Quantity_Value);
gvSale.CurrentRow.Cells[Total_Index].Value = Price_Value * Quantity_Value;
}

Related

Android: Passing Checked items from a ListView to another activity with a ListView

I am trying to pass checked items from one listview to another listview in a separate activity. Ideally, the user would click all of the items they wanted, then click a button; then, the button would take all of the items from the rows clicked to the new activity. The problem that I keep having is when I click on the row; all of the information shows up on the next activity instead of the individual rows there were selected.
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adapterTwo.setCheckBox(position);
adapterTwo.notifyDataSetChanged();
}
});
practiceFinal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String entry = "";
String judge ="";
Integer points = 0;
Integer work = 0;
Integer design = 0;
Integer doc = 0;
Integer pres= 0;
Integer safety= 0;
Integer diff = 0;
String ribbon ="";
Intent intent = new Intent(CSS.this, FinalCSS.class);
for (Team hold: adapterTwo.getTeamArrayList())
{
if (hold.isChecked())
{
}
else
{
entry += " "+ hold.getEntryNumber();
judge += hold.getTeamJudgeNumber();
points+= hold.getTotalPoints();
work+= hold.getWorkmanship();
design += hold.getDesign();
doc += hold.getDocumnetation();
pres+= hold.getPresentation();
safety += hold.getSafety();
diff += hold.getDifficulty();
ribbon += hold.getRibbon();
intent.putExtra( "KeyEntry", entry);
intent.putExtra("KeyJudge", judge);
intent.putExtra("KeyPoints", points);
intent.putExtra("KeyWork", work);
intent.putExtra("KeyDesign", design);
intent.putExtra("KeyDoc",doc);
intent.putExtra("KeyPres", pres);
intent.putExtra("KeySafety", safety);
intent.putExtra("KeyRibbon", ribbon);
intent.putExtra("KeyDiff", diff);
}
}
startActivity(intent);
}
});
listView = findViewById(R.id.listViewFinal);
teamsList= new ArrayList<>();
String entry = getIntent().getStringExtra("KeyEntry");
String judge=getIntent().getStringExtra("KeyJudge");
Integer points= getIntent().getIntExtra("KeyPoints",0);
Integer workmanship=getIntent().getIntExtra("KeyWork",0);
Integer design=getIntent().getIntExtra("KeyDesign",0);
Integer documentation =getIntent().getIntExtra("KeyDoc",0);
Integer pres = getIntent().getIntExtra("KeyPres",0);
Integer difficulty =getIntent().getIntExtra("KeyDiff",0);
Integer safety =getIntent().getIntExtra("KeySafety",0);
String ribbon= getIntent().getStringExtra("KeyRibbon");
Team teams = null;
teams = new Team(judge,entry,points, workmanship,design,documentation,pres,difficulty,safety,ribbon,true);
teamsList.add(teams);
Team teamsT = null;
teamsT = new Team(judge,entry,points, workmanship,design,documentation,pres,difficulty,safety,ribbon,true);
teamsList.add(teamsT);
TeamAdapterTwo adapterTwo = new TeamAdapterTwo(FinalCSS.this, teamsList);
listView.setAdapter(adapterTwo);
Second ActivityFirst ActivitySecond Activity
You are concatenate the information on a global variable. Thus, if we trace the points attribute evolution, we have:
points = 0
points += 1 (points = 1)
points += 2 (points = 3)
points += 3 (points = 6)
points += 4 (points = 10)
Moreover, intent.putExtra erase the old value associated to a key, so at each iteration of the loop, you are replacing the old value of points by the new one. Therefore, at the end, you will give points = 10 to the second Activity.
You have two options:
Create a unique key for each hold but it will not be easy for the second Activity to know this unique key.
Instead of put an integer as extra, put an array of integers (I recommend this way)
However, you seem to have an other issue because the final value of points is the sum of all lines rather than the sum of the checked ones.

Javafx 2 : How do I delete a row or column in Gridpane

If I want to add a row of text fields programatically in JavaFx, i can simply use the gridpane add method
This adds a set of text fields to row 1.
for (int i = 0; i < Fields.size(); i++) {
gridpane.add(new TextField(), i, 1);
}
Similarly, How do I delete a row?. I dont find a suitable method to delete a row/column conveeniently in JavaFX.
There's no directly equivalent method. To remove nodes, just use
gridpane.getChildren().remove(...); or gridpane.getChildren().removeAll(...); and pass in the nodes you want to remove from the pane.
In Java 8+, you can use removeIf:
gridPane.getChildren().removeIf(node -> GridPane.getRowIndex(node) == rowNumber);
Caveat
If removing items from the 0th row, also check GridPane.getRowIndex(node) == null, i.e.,
node -> GridPane.getRowIndex(node) == null || GridPane.getRowIndex(node) == 0
(I think this is JavaFX leaving the row number as null when no row number is given in the corresponding element in FXML, even though giving no row number in FXML means the element is in the 0th row, since the default row is the 0th row.)
This works pretty well:
while(MainGridPane.getRowConstraints().size() > 0){
MainGridPane.getRowConstraints().remove(0);
}
while(MainGridPane.getColumnConstraints().size() > 0){
MainGridPane.getColumnConstraints().remove(0);
}
JavaFX APIs are pretty lacking (like easily removing rows from GridPane) and unintuitive (like returning null instead 0 for GridPane.getRowIndex). Here is solution I came up with:
Utils:
package io.github.againpsychox.javaspeedrunsapp.utils;
import javafx.scene.Node;
import javafx.scene.layout.GridPane;
public class GridPaneUtils {
/**
* Gets row index constrain for given node, forcefully as integer: 0 as null.
* #param node Node to look up the constraint for.
* #return The row index as primitive integer.
*/
public static int getRowIndexAsInteger(Node node) {
final var a = GridPane.getRowIndex(node);
if (a == null) {
return 0;
}
return a;
}
/**
* Removes row from grid pane by index.
* Note: Might not work correctly if row spans are used.
* #param grid Grid pane to be affected.
* #param targetRowIndexIntegerObject Target row index to be removed. Integer object type, because for some reason `getRowIndex` returns null for children at 0th row.
*/
public static void removeRow(GridPane grid, Integer targetRowIndexIntegerObject) {
final int targetRowIndex = targetRowIndexIntegerObject == null ? 0 : targetRowIndexIntegerObject;
// Remove children from row
grid.getChildren().removeIf(node -> getRowIndexAsInteger(node) == targetRowIndex);
// Update indexes for elements in further rows
grid.getChildren().forEach(node -> {
final int rowIndex = getRowIndexAsInteger(node);
if (targetRowIndex < rowIndex) {
GridPane.setRowIndex(node, rowIndex - 1);
}
});
// Remove row constraints
grid.getRowConstraints().remove(targetRowIndex);
}
}
Example usage:
GridPaneUtils.removeRow(this.grid, GridPane.getRowIndex(this.idTextField));
Posting my solution for further readers...

Count the number of frequency for different characters in a string

i am currently tried to create a small program were the user enter a string in a text area, clicks on a button and the program counts the frequency of different characters in the string and shows the result on another text area.
E.g. Step 1:- User enter:- aaabbbbbbcccdd
Step 2:- User click the button
Step 3:- a 3
b 6
c 3
d 1
This is what I've done so far....
public partial class Form1 : Form
{
Dictionary<string, int> dic = new Dictionary<string, int>();
string s = "";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
s = textBox1.Text;
int count = 0;
for (int i = 0; i < s.Length; i++ )
{
textBox2.Text = Convert.ToString(s[i]);
if (dic.Equals(s[i]))
{
count++;
}
else
{
dic.Add(Convert.ToString(s[i]), count++);
}
}
}
}
}
Any ideas or help how can I countinue because till now the program is giving a run time error when there are same charachter!!
Thank You
var lettersAndCounts = s.GroupBy(c=>c).Select(group => new {
Letter= group.Key,
Count = group.Count()
});
Instead of dic.Equals use dic.ContainsKey. However, i would use this little linq query:
Dictionary<string, int> dict = textBox1.Text
.GroupBy(c => c)
.ToDictionary(g => g.Key.ToString(), g => g.Count());
You are attempting to compare the entire dictionary to a string, that doesn't tell you if there is a key in the dictionary that corresponds to the string. As the dictionary never is equal to the string, your code will always think that it should add a new item even if one already exists, and that is the cause of the runtime error.
Use the ContainsKey method to check if the string exists as a key in the dictionary.
Instead of using a variable count, you would want to increase the numbers in the dictionary, and initialise new items with a count of one:
string key = s[i].ToString();
textBox2.Text = key;
if (dic.ContainsKey(key)) {
dic[key]++;
} else {
dic.Add(key, 1);
}
I'm going to suggest a different and somewhat simpler approach for doing this. Assuming you are using English strings, you can create an array with capacity = 26. Then depending on the character you encounter you would increment the appropriate index in the array. For example, if the character is 'a' increment count at index 0, if the character is 'b' increment the count at index 1, etc...
Your implementation will look something like this:
int count[] = new int [26] {0};
for(int i = 0; i < s.length; i++)
{
count[Char.ToLower(s[i]) - int('a')]++;
}
When this finishes you will have the number of 'a's in count[0] and the number of 'z's in count[25].

How to use the repaint method

I am trying to use the repaint method in the following code to update the screen after user input. The game is a card game where the user has to click on two cards to reveal their pictures. If the pictures match the cards remain visible however if the pictures don't match the cards flip over to hide the pictures once again.
The first card becomes visible after clicking it, however when the second card is selected either both cards become visible if a matching picture is selected or the first card just flips over without the second picture being revealed.
Thanks for your help.
addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
int row = e.getX() / (Card.SIZE*2);
int col = e.getY() / (Card.SIZE*3);
//OPEN means the picture is visible
if(cards[row][col].getState() == Card.CLOSED)
cards[row][col].setState(OPEN);
repaint();
compareCards(row,col);
}
});
}
public void compareCards(int row, int col){
if(clickNum == 1){
r1 = row;
c1 = col;
clickNum++;
}
else if(clickNum == 2){
r2 = row;
c2 = col;
//The OR accounts for clicking twice on the same tile
if(cards[r1][c1].getNum() != cards[r2][c2].getNum() || (r1 == r2 && c1 == c2)){
cards[r1][c1].setState(CLOSED);
cards[r2][c2].setState(CLOSED);
}
clickNum = 1;
}
}
Your compare cards function is setting the card states to CLOSED much too quickly, and so they are not displaying. Try using:
public void compareCards(int row, int col){
try
{
Thread.sleep(5000);//sleep for five seconds
}catch(Exception e){}
if(clickNum == 1){
r1 = row;
c1 = col;
clickNum++;
}
else if(clickNum == 2){
r2 = row;
c2 = col;
//The OR accounts for clicking twice on the same tile
if(cards[r1][c1].getNum() != cards[r2][c2].getNum() || (r1 == r2 && c1 == c2)){
cards[r1][c1].setState(CLOSED);
cards[r2][c2].setState(CLOSED);
}
clickNum = 1;
}
}
This should display both cards for about five seconds before turning them over. You'll also have to implement a method which handles flipping the cards back over if they are the same if you don't already have one. I only say this because I don't see one here.

AutoFit Columns Width using jxl library in java [duplicate]

How to autofit content in cell using jxl api?
I know this is an old question at this point, but I was looking for the solution to this and thought I would post it in case someone else needs it.
CellView Auto-Size
I'm not sure why the FAQ doesn't mention this, because it very clearly exists in the docs.
My code looked like the following:
for(int x=0;x<c;x++)
{
cell=sheet.getColumnView(x);
cell.setAutosize(true);
sheet.setColumnView(x, cell);
}
c stores the number of columns created
cell is just a temporary place holder for the returned CellView object
sheet is my WriteableSheet object
The Api warns that this is a processor intensive function, so it's probably not ideal for large files. But for a small file like mine (<100 rows) it took no noticeable time.
Hope this helps someone.
The method is self explanatory and commented:
private void sheetAutoFitColumns(WritableSheet sheet) {
for (int i = 0; i < sheet.getColumns(); i++) {
Cell[] cells = sheet.getColumn(i);
int longestStrLen = -1;
if (cells.length == 0)
continue;
/* Find the widest cell in the column. */
for (int j = 0; j < cells.length; j++) {
if ( cells[j].getContents().length() > longestStrLen ) {
String str = cells[j].getContents();
if (str == null || str.isEmpty())
continue;
longestStrLen = str.trim().length();
}
}
/* If not found, skip the column. */
if (longestStrLen == -1)
continue;
/* If wider than the max width, crop width */
if (longestStrLen > 255)
longestStrLen = 255;
CellView cv = sheet.getColumnView(i);
cv.setSize(longestStrLen * 256 + 100); /* Every character is 256 units wide, so scale it. */
sheet.setColumnView(i, cv);
}
}
for(int x=0;x<c;x++)
{
cell=sheet.getColumnView(x);
cell.setAutosize(true);
sheet.setColumnView(x, cell);
}
It is fine, instead of scanning all the columns. Pass the column as a parameter.
void display(column)
{
Cell = sheet.getColumnView(column);
cell.setAutosize(true);
sheet.setColumnView(column, cell);
}
So when you wiill be displaying your text you can set the particular length. Can be helpfull for huge excel files.
From the JExcelApi FAQ
How do I do the equivilent of Excel's "Format/Column/Auto Fit Selection"?
There is no API function to do this for you. You'll need to write code that scans the cells in each column, calculates the maximum length, and then calls setColumnView() accordingly. This will get you close to what Excel does but not exactly. Since most fonts have variable width characters, to get the exact same value, you would need to use FontMetrics to calculate the maximum width of each string in the column. No one has posted code on how to do this yet. Feel free to post code to the Yahoo! group or send it directly to the FAQ author's listed at the bottom of this page.
FontMetrics presumably refers to java.awt.FontMetrics. You should be able to work something out with the getLineMetrics(String, Graphics) method I would have though.
CellView's autosize method doesn't work for me all the time. My way of doing this is by programatically set the size(width) of the column based on the highest length of data in the column. Then perform some mathematical operations.
CellView cv = excelSheet.getColumnView(0);
cv.setSize((highest + ((highest/2) + (highest/4))) * 256);
where highest is an int that holds the longest length of data in the column.
setAutosize() method WILL NOT WORK if your cell has over 255 characters. This is related to the Excel 2003 max column width specification: http://office.microsoft.com/en-us/excel-help/excel-specifications-and-limits-HP005199291.aspx
You will need to write your own autosize method to handle this case.
Try this exemple:
expandColumns(sheet, 3);
workbook.write();
workbook.close();
private void expandColumn(WritableSheet sheet, int amountOfColumns){
int c = amountOfColumns;
for(int x=0;x<c;x++)
{
CellView cell = sheet.getColumnView(x);
cell.setAutosize(true);
sheet.setColumnView(x, cell);
}
}
Kotlin's implementation
private fun sheetAutoFitColumns(sheet: WritableSheet, columnsIndexesForFit: Array<Int>? = null, startFromRowWithIndex: Int = 0, excludeLastRows : Int = 0) {
for (columnIndex in columnsIndexesForFit?.iterator() ?: IntProgression.fromClosedRange(0, sheet.columns, 1).iterator()) {
val cells = sheet.getColumn(columnIndex)
var longestStrLen = -1
if (cells.isEmpty()) continue
for (j in startFromRowWithIndex until cells.size - excludeLastRows) {
if (cells[j].contents.length > longestStrLen) {
val str = cells[j].contents
if (str == null || str.isEmpty()) continue
longestStrLen = str.trim().length
}
}
if (longestStrLen == -1) continue
val newWidth = if (longestStrLen > 255) 255 else longestStrLen
sheet.setColumnView(columnIndex, newWidth)
}
}
example for use
sheetAutoFitColumns(sheet) // fit all columns by all rows
sheetAutoFitColumns(sheet, arrayOf(0, 3))// fit A and D columns by all rows
sheetAutoFitColumns(sheet, arrayOf(0, 3), 5)// fit A and D columns by rows after 5
sheetAutoFitColumns(sheet, arrayOf(0, 3), 5, 2)// fit A and D columns by rows after 5 and ignore two last rows

Resources