calculating listview & textbox - c#

I have been researching for almost two weeks now and found nothing helpful.
I have a listview with a few columns, the last column is a price column, I need to have another column that calculates the price column and a textbox, for each row in the listview. Any help will be highly appreciated.
Sorry, I am new to programming and at the moment I can only sum the column, This is all I got.
List<string> last = new List<string>();
last.AddRange(new string[] { "one", "two", "three", "four" });
int column = 1 ; int.Parse(TextBox1.text)
int row = 0;
foreach (var value in last)
{
if (!(column >= listView1.Columns.Count))
{
ListViewItem item = new ListViewItem();
listView1.Items.Add(item);
ListViewItem.ListViewSubItem lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = value.ToString();
listView1.Items[row].SubItems.Insert(column, lvsi);
row++;
}
}

I think should be something like this (where n is the number of the column with the price calculated, and i the column with the initial price):
int currency = int.Parse(Textbox1.Text);
int markup = int.Parse(Textbox2.Text);
int shippingcost = int.Parse(Textbox3.Text).
foreach(ListViewItem item in listView.Items)
{
item.SubItems[n].value = ( ((int)item.SubItems[i].value * currency) + markup + shippingcost ).ToString();
}
With this, foreach ListViewItem you cast to int the value of the column with the price, calculate the final price with the value of a textbox, and convert it into a string and put the final value the desired column.

Related

How do i get the data stored in a list box by clicking on the particular row?

How do I get the data of a specific row stored in a list box by clicking on the particular row ? So if i click on the row i can then access that particular row by index then store it to be used later on
int myMaxResultValue = (int)nud_MaxResults.Value;
int myMaxSuggestValue = (int)nud_MaxSuggestions.Value;
findResults = objBvSoapClient( txt_Search.Text, txt_LastId.Text, cb_SearchFor.Text, text_Country.Text, text_LanguagePreference.Text, myMaxResultValue, myMaxSuggestValue);
if (txt_Search.Text.Length <= 2)// if less than two letters are entered nothing is displayed on the list.
{
ls_Output.Items.Clear();// Clear LstBox
ls_Output.Items.Add(String.Format(allDetails, "ID", "Text", "Highlight", "Cursor", "Description", "Next"));
MessageBox.Show("Please enter more than 2 Chars!!");
}
else if (txt_Search.Text.Length >= 3)// if greater than or equal to 3 letters in the search box continue search.
{
// Get Results and store in given array.
foreach (var items in findResults)
{
//Loop through our collection of found results and change resulting value.
ls_Output.Items.Add(String.Format(allDetails, items.Id, items.Text.ToString(), items.Highlight, items.Cursor, items.Description, items.Next));
}
}
Then to retrieve the whole string i have placed this function within the indexChanged event,:
if (ls_Output.SelectedIndex != -1)
{
int itemAtPostion = ls_Output.SelectedIndex;
string nextStep = "Retrieve";
if (ls_Output.Items[itemAtPostion].ToString().Contains(nextStep))
{
string selItem = ls_Output.SelectedItem.ToString();
MessageBox.Show("You have selected the following address: " + selItem);
lst_Retreive.Text = ls_Output.SelectedItem.ToString();
}
}
You can either get the index of the item or the item itself.
To get the item you can use
string item = listBox.SelectedItem.ToString();
To get the index of the item you can use
int idx = listBox.SelectedIndex;
If your listbox supports multiselect you can use
var items = listBox.SelectedItems();
and
var idx = listBox.SelectedIndices;
I was looking at this in a completly different way, and i should have been thinking about DataTables. I wanted to only be clicking on individual cells and hence the reason I was getting the whole string back rather than individual feilds. Heres how i Solved it
DataTable ss = new DataTable();
ss.Columns.Add("ID");
ss.Columns.Add("Text");
ss.Columns.Add("Highlight");
ss.Columns.Add("Cursor");
ss.Columns.Add("Description");
ss.Columns.Add("Next");
DataRow row = ss.NewRow();
row["ID"] = findResults[0].Id;
row["Text"] = findResults[0].Text;
row["Highlight"] = findResults[0].Highlight;
row["Cursor"] = findResults[0].Cursor;
row["Description"] = findResults[0].Description;
row["Next"] = findResults[0].Next;
ss.Rows.Add(row);
foreach (DataRow Drow in ss.Rows)
{
int num = dataGridView1.Rows.Add();
dataGridView1.Rows[num].Cells[0].Value = Drow["id"].ToString();
dataGridView1.Rows[num].Cells[1].Value = Drow["Text"].ToString();
dataGridView1.Rows[num].Cells[2].Value = Drow["Highlight"].ToString();
dataGridView1.Rows[num].Cells[3].Value = Drow["Cursor"].ToString();
dataGridView1.Rows[num].Cells[4].Value = Drow["Description"].ToString();
dataGridView1.Rows[num].Cells[5].Value = Drow["Next"].ToString();
}
if (txt_Search.Text.Length <= 2)// if less than two letters are entered nothing is displayed on the list.
{
MessageBox.Show("Please enter more than 2 Chars!!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
findResults.Clear();

Getting the selected rows' values in datagridview and adding them up

I am making a booking winsform application now. When a user chooses any number of rows, there will be a column called rental price that each row is under. Then the value of this cell under the column called rental price will be gotten and add up and display to the total cost label text.But the problem is the total cost is not displaying. Here is my code:
private void Payment_Load(object sender, EventArgs e)
{
NameOfUser.Text = UserAccounts[0].Name;
EmailOfUser.Text = UserAccounts[0].Email;
PaymentType.Text = UserAccounts[0].PaymentType;
double totalCost = 0;
foreach (DataGridViewRow row in b1.DataGridView1.SelectedRows)
{
int index = 0;
foreach (DataGridViewCell cell in row.Cells)
{
totalCost += (double)dataGridView1.Rows[index].Cells[4].Value;
}
index++;
}
TotalCost.Text = Convert.ToString(totalCost);
}
Yes the Mistake is in the looping, As of now you are iterating the rows in the SelectedRows and by using the inner loop you again looping through the cells of each row But taking values with respect to the actual grid instead for the cell. You can make this simple as you wanted to iterate through the selected rows and need to sums the value of .Cells[4] in each row. for that you have to do something like this:
foreach (DataGridViewRow row in b1.DataGridView1.SelectedRows)
{
string value = row.Cells[4].Value.ToString();
double currentCellValue = 0.0;
if(double.TryParse(value , out currentCellValue)
{
totalCost += currentCellValue;
}
}
TotalCost.Text = totalCost .ToString();

How to remove unwanted whitespace when filling listview with items (c#)

Using c#, winforms.
Background:
The user should be able to select items from my menu strip, and then based on that the list view columns should be populated. Example: Select percent from 100-80 % then columns 1 and 2 get populated. Select total trans from <1000 and then column 3 and 4 get populated.
Problem:
When adding items to my listview, say I select option 1 from menu strip. Then columns 1 and 2 get filled up. Good. BUT right after if I select option from total trans, the column 3 and 4 do get filled up, BUT there is a ton of WHITEspace in the columns. Basically, the columns should not have white space when getting filled up.
This is what I mean: Notice the whitespace (outlined by red). First I selected option 1, then as soon as I selecte the option to populate column 3 and 4, they filled, but with whitespace. The column values for col 3 and 4 should have nothing above them in white.
Also here: I select another option from menu strip (for col 1 and 2) , after selecting the option to fill column 3 and 4, and more whitespace:
Code:
// Fill Column 1 and 2 from option 1
private void toolStripMenuItem2_Click(object sender, EventArgs e)
{
int totItems = Seq3.Count - 1;
if (PercentPopTolerance1.Count - 1 > totItems) totItems = PercentPopTolerance1.Count - 1;
for (int i = 0; i <= totItems; i++)
{
ListViewItem lvi = new ListViewItem();
string item1 = "";
string item2 = "";
if (Seq3.Count - 1 >= i) item1 = Seq3[i].ToString();
if (PercentPopTolerance1.Count - 1 >= i) item2 = PercentPopTolerance1[i].ToString();
lvi.SubItems.Add(item1);
lvi.SubItems.Add(item2);
listView2.Items.Add(lvi);
}
}
// Percent tolerance from 80-60%
// Fill Column 1 and 2 from option 2
private void toolStripMenuItem3_Click_1(object sender, EventArgs e)
{
ClearColumn("columnHeader5");
int totItems = Seq4.Count - 1;
if (PercentPopTolerance2.Count - 1 > totItems) totItems = PercentPopTolerance2.Count - 1;
for (int i = 0; i <= totItems; i++)
{
ListViewItem lvi = new ListViewItem();
string item1 = "";
string item2 = "";
if (Seq4.Count - 1 >= i) item1 = Seq4[i].ToString();
if (PercentPopTolerance2.Count - 1 >= i) item2 = PercentPopTolerance2[i].ToString();
lvi.SubItems.Add(item1);
lvi.SubItems.Add(item2);
listView2.Items.Add(lvi);
}
}
// Fill columns 3 and 4 from option in total trans menustrip
// Total trans tolerance < 1000
private void etcToolStripMenuItem_Click(object sender, EventArgs e)
{
int totItems = YYMMt21.Count - 1;
if (TotalTransIrregularitiest21.Count - 1 > totItems) totItems = TotalTransIrregularitiest21.Count - 1;
for (int i = 0; i <= totItems; i++)
{
ListViewItem lvi = new ListViewItem();
string item1 = "";
string item2 = "";
if (YYMMt21.Count - 1 >= i) item1 = YYMMt21[i].ToString();
if (TotalTransIrregularitiest21.Count - 1 >= i) item2 = TotalTransIrregularitiest21[i].ToString();
// Skip first 2 columns
lvi.SubItems.Add(string.Empty);
lvi.SubItems.Add(string.Empty);
lvi.SubItems.Add(item1);
lvi.SubItems.Add(item2);
listView2.Items.Add(lvi);
}
}
EDIT: Trying User suggestion:
New problem arises: what is supposed to be in column 3 and 4 vertically now fills the listview from the first row horizontally:
My attempt:
private void etcToolStripMenuItem_Click(object sender, EventArgs e)
{
int totItems = YYMMt21.Count - 1;
if (TotalTransIrregularitiest21.Count - 1 > totItems) totItems = TotalTransIrregularitiest21.Count - 1;
for (int i = 0; i <= totItems; i++)
{
ListViewItem lvi = new ListViewItem();
string item1 = "";
string item2 = "";
if (YYMMt21.Count - 1 >= i) item1 = YYMMt21[i].ToString();
if (TotalTransIrregularitiest21.Count - 1 >= i) item2 = TotalTransIrregularitiest21[i].ToString();
// Skip first 2 columns
lvi.SubItems.Add(string.Empty);
lvi.SubItems.Add(string.Empty);
int rowToPopulate = 0;
int colToPopulate = 0;
if (rowToPopulate <= listView2.Items.Count - 1)
{
//Editing an existing row/ListViewItem
listView2.Items[rowToPopulate].SubItems.Insert(colToPopulate, new ListViewItem.ListViewSubItem() { Text = item1 });
// How would I also add item2?
// listView2.Items[rowToPopulate].SubItems.Insert(colToPopulate, new ListViewItem.ListViewSubItem() { Text = item2 });
}
else
{
//Adding a new row/ListViewItem
// ListViewItem lvi = new ListViewItem();
lvi.SubItems.Add(item1);
lvi.SubItems.Add(item2);
//Add all the other Subitems as usual
listView2.Items.Add(lvi);
}
//listView2.Items.Add(lvi);
}
}
You can alternate Items.Add and Items.SubItems.Insert. Sample code:
string curItem = "curVal";
int rowToPopulate = 0;
int colToPopulate = 0;
if (rowToPopulate <= listView2.Items.Count - 1)
{
//Editing an existing row/ListViewItem
listView2.Items[rowToPopulate].SubItems.Insert(colToPopulate, new ListViewItem.ListViewSubItem() { Text = curItem });
}
else
{
//Adding a new row/ListViewItem
ListViewItem lvi = new ListViewItem();
lvi.SubItems.Add(curItem);
//Add all the other Subitems as usual
listView2.Items.Add(lvi);
}
This code checks whether the row being analysed (rowToPopulate) has already been populated or not. If it hasn't been populated yet, you can use the code so far (under the else statement, including as many SubItems as columns by letting blank the ones for which no information is available). If this is the second time that you analyse this row (some columns have already been populated and some other ones were left blank), you take the given ListViewItem/row (listView2.Items[rowToPopulate]) and insert the new element in the SubItem/column you wish.
From what I can tell on your code, you just keep adding more items on the events, supplying String.Empty for the columns you're trying to skip. If you want the new values from the next event to appear on the same row as values already present, you'll have to update the already existing rows SubItems and supply which values are to go on which row.
Edit: I accomplished what you're trying to do with the below sample. This assumes that you know or can get the size of each list you're trying to add to each column. You'll have to implement some null checking etc to make sure you're not referencing null cells in the lists. Just expand on this sample and tailor it to your exact situation.
List<string> sList = new List<string>() { "1", "2", "3", "4", "5" };
List<string> lList = new List<string>() { "1", "2", "3", "4", "5", "6", "7", "8" };
private void button1_Click(object sender, EventArgs e)
{
listView1.Clear();
addColumns();
for (int i = 0; i < sList.Count(); i++)
{
var item1 = new ListViewItem(sList[i]);
item1.SubItems.Add(String.Empty);
listView1.Items.Add(item1);
}
}
private void button2_Click(object sender, EventArgs e)
{
listView1.Clear();
addColumns();
for (int i = 0; i < lList.Count(); i++)
{
if (i < sList.Count())
{
var item2 = new ListViewItem(sList[i]);
item2.SubItems.Add(lList[i]);
listView1.Items.Add(item2);
}
else
{
var item3 = new ListViewItem(String.Empty);
item3.SubItems.Add(lList[i]);
listView1.Items.Add(item3);
}
}
}
private void addColumns()
{
listView1.Columns.Add("Column 1", -2, HorizontalAlignment.Left);
listView1.Columns.Add("Column 2", -2, HorizontalAlignment.Left);
}

How to vertically populate each column of listview with lists

I have data which I import from textfiles, transfer to an sqlite db, then transfer that into LISTS. Now I want to show these lists to the user in a LISTVIEW. Each column should contain a list.
Below, the contents of the second column are perfectly fine. But, the 3rd and the fourth column should be vertically filled with the items that correspond to their color values.
I.e from the code below, I want to populate the 3rd and 4th column with the MaxLen list and PercentPopList list. (Yes I know that I skipped a column, but i'll fix that later)
I'm new to programming and I cant figure out how to make that work.
ListViewItem lvi = new ListViewItem();
foreach (object o in SeqIrregularities)
{
lvi.SubItems.Add(o.ToString());
listView1.Items.Add(lvi);//Adds a new row
lvi = new ListViewItem();
}
listView1.Items.Add(lvi);//Adds a new row
lvi = new ListViewItem();
foreach (object a in MaxLen)
{
lvi.SubItems.Add(a.ToString());
}
listView1.Items.Add(lvi);//Adds a new row
lvi = new ListViewItem();
foreach (object b in PercentPopList)
{
lvi.SubItems.Add(b.ToString());
}
listView1.Items.Add(lvi);//Adds a new row
Your data is in the wrong format. Simplifying, you seem to have data like this:
var firstColumnValues = new List<int>();
var secondColumnValues = new List<int>();
var thirdColumnValues = new List<int>();
While each individual list may make sense on its own, they currently don't relate to each other in any meaningful way. What you need to do is think about the format of the object which represents one "record" of data. Still overly-simplified, something like this:
class RecordOfValues
{
public int FirstValue { get; set; }
public int SecondValue { get; set; }
public int ThirdValue { get; set; }
}
Then you'd just have one list of them:
var listOfRecords = new List<RecordOfValues>();
At this point you would have a list of "records" to bind to the ListView.
As far as I understand that you don't have too much experience and cannot easily come up with an algorithm accounting for the suggested modifications; here you have a sample code showing how to extend your code to populate three different columns from 3 different lists:
List<string> SeqIrregularities = new List<string>();
SeqIrregularities.Add("1");
SeqIrregularities.Add("2");
SeqIrregularities.Add("3");
List<string> MaxLen = new List<string>();
MaxLen.Add("4");
MaxLen.Add("5");
MaxLen.Add("6");
List<string> PercentPopLis = new List<string>();
PercentPopLis.Add("7");
PercentPopLis.Add("8");
PercentPopLis.Add("9");
PercentPopLis.Add("10");
PercentPopLis.Add("11");
int totItems = SeqIrregularities.Count - 1;
if (MaxLen.Count - 1 > totItems) totItems = MaxLen.Count - 1;
if (PercentPopLis.Count - 1 > totItems) totItems = PercentPopLis.Count - 1;
for (int i = 0; i <= totItems; i++)
{
ListViewItem lvi = new ListViewItem();
string item1 = "";
string item2 = "";
string item3 = "";
if (SeqIrregularities.Count - 1 >= i) item1 = SeqIrregularities[i];
if (MaxLen.Count - 1 >= i) item2 = MaxLen[i];
if (PercentPopLis.Count - 1 >= i) item3 = PercentPopLis[i];
lvi.SubItems.Add(item1);
lvi.SubItems.Add(item2);
lvi.SubItems.Add(item3);
listView1.Items.Add(lvi);
}

Calculate total from datagridview into textbox

i have a datagridview which are used to display a transaction record.
And one of the columns in datagridview is "Total", which is "SubTotal" times with "Quantity".
My question is, how do i gonna make "GrandTotal" by calculating all "Total" in datagridview into textbox?
Here is the screenshot:
if you see in the datagridview above, there is column named "Total", this "Total" was got from "Quantity" times "SubTotal", what i want is i want to calculate the "Total" (Sum all of the "Total" in the column) into textbox.
How do i gonna do that?
I already thought about it, but i cannot came with an idea how do i calculate (sum) the "Total" column in the datagridview into the textbox.
I appreciate your answer.
Thank you very much!
Iterate through each row and find cell which hold the total value. convert this total value to double(any numeric data structure) and calculate grand total by adding each one with previous grand total.
Without Linq
double result = 0;
foreach (DataGridViewRow row in DataGridView.Rows)
{
result += Convert.ToDouble(row.Cells["Total"].Value);
}
With Linq
double result = DataGridView.Rows.Cast<DataGridViewRow>().Sum(row => Convert.ToDouble(row.Cells["Total"].Value));
if you are binding a List or DataTable then just simply use LINQ's SUM method
// You can use it in the click event of button
str = "YOUR SQL QUERY";
objCom = new SqlCommand(str, objCon);
objDataAdapter = new SqlDataAdapter(objCom);
objDataSet = new DataSet();
objDataAdapter.Fill(objDataSet, "TABLE NAME");
dataGridView2.DataMember = "TABLE NAME";
dataGridView2.DataSource = objDataSet;
dataGridView2[3, dataGridView2.Rows.Count - 1].Value = "Total";
dataGridView2.Rows[dataGridView2.Rows.Count - 1].Cells[3].Style.ForeColor = Color.White;
dataGridView2.Rows[dataGridView2.Rows.Count - 1].Cells[3].Style.BackColor = Color.Green;
dataGridView2.Rows[dataGridView2.Rows.Count - 1].Cells[4].Style.ForeColor = Color.White;
double sum = 0;
for (int row = 0; row < dataGridView2.Rows.Count; row++)
{
sum = sum + Convert.ToDouble(dataGridView2.Rows[row].Cells[4].Value);
}
dataGridView2.Rows[dataGridView2.Rows.Count - 1].Cells[4].Value = sum.ToString();

Categories

Resources