Calculate total from datagridview into textbox - c#

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();

Related

Set value of each DataTable row in specific column

I'm having some problem while trying to set column value.
I'v had a dataTable which get some values from SQL and then im adding two new columns by :
dataTable.Columns.Add("dest", typeof(int));
dataTable.Columns.Add("amount", typeof(int));
Which works great but now i want to put 0 in every row in column name dest - and later user will edit this, and then i want to set amount value as
amount = all(this column is in dataTable before I add these 2 columns) + dest;
int columnNumber = 5; //Put your column X number here
for (int i = 0; i < yourDataTable.Rows.Count; i++)
{
yourDataTable.Rows[i][columnNumber] = "0";
}
You can use foreach too.
foreach (DataRow row in myDataTable.Rows)
//if (row["X"] has condition) // or if any condition
row["colName"] = row[colIndex] = "abc";

Add rows to datagridview dynamically

I usually don't post questions, and I know this answer is already out there somewhere but I'm not finding it for some reason. Basically, I have a datagridview that has a variable number of columns, and variable number of rows. So when I'm building it for the screen, I first add the columns using this code:
// Set column names
for (int i = 0; i < count; i++)
{
fieldName = fromFileFields[i];
dtaRecordDisplay.Columns.Add(fromFileFields[i}, fromFileFields[i});
}
Now, I would like to populate the rows in the view with something like this:
// Set row data
for (int i = 0; i < count; i++)
{
dtaRecordDisplay.Rows.Add(Row1, Row2, etc., etc., etc..........);
}
I'm having a hard time figuring out the loop to be able to add all rows of data at once. Does anyone have any ideas on how to accomplish that?
Thanks in advance!
In this case I would fill a DataTable with columns and rows to work with, and bind that to the grid.
DataTable dt = new DataTable();
// first add your columns
for (int i = 0; i < count; i++)
{
dt.Columns.Add(fromFileFields[i]);
}
// and then add your rows
for (int i = 0; i < count; i++)
{
var row = dt.NewRow();
// Set values for columns with row[i] = xy
dt.Rows.Add(row);
}
datagridview.DataSource = dt;
You need to make a DataTable, and bind that to your grid view. Then add the rows and colums to that, like Marc says:
https://stackoverflow.com/a/35604744/5882760
The reason for that is, that the columns of the grid view instance only contain information on how to display the data from the attached DataTable.
They contain the information about what columbs to display, in what order, etc.
Try following code, you can add rows to dataGridViews without out any data Sources or data table.
dataGridView1.AllowUserToAddRows = true;
dtaGridView1 row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
row.Cells[0].Value = "Your cell 0 Data";
row.Cells[1].Value = "Your cell 1 Data";
row.Cells[2].Value = "Your cell 2 Data";
………….
row.Cells[n].Value = "Your cell n Data";
dataGridView1.Rows.Add(row);

Not displaying data from a dataset properly in a table, while using a for loop to generate table and cells

I have a dataset that I am using to create an html table with a loop. I am able to populate the cells with the subjects from the dataset but its not laying out properly.
When I run it the table is showing the subjects as
Subject1 Subject1 Subject1
Subject2 Subject2 Subject2
Subject3, Subject3, Subject3
and I'm trying to get it look like,
Subject1 Subject2 Subject3
Subject4 Subject5 Subject6
Subject7 Subject8 Subject9
My code is..
// Current row count.
int rowCtr;
// Total number of cells per row (columns).
int cellCtr;
// Current cell counter.
int cellCnt;
//count number of rows in dataset
int rN = test.dsSubjects.Tables[0].Rows.Count;
cellCnt = 3;
for (rowCtr = 1; rowCtr <= rN; rowCtr++)
{
// Create a new row and add it to the table.
TableRow tRow = new TableRow();
Table1.Rows.Add(tRow);
for (cellCtr = 1; cellCtr <= cellCnt; cellCtr++)
{
// Create a new cell and add it to the row.
TableCell tCell = new TableCell();
tRow.Cells.Add(tCell);
// Add a literal text as control.
string myStr = test.dsSubjects.Tables[0].Rows[rowCtr -1]["SubjectName"].ToString();
tCell.Controls.Add(new LiteralControl(myStr));
}
}
I know this is basic but I haven't used a for loop to do this before.
( Just a side note, I have the rowCtr with a -1 when going through the dataset because if not it throws an error )
Can anyone point out where I am going wrong in my loop to get the layout that I need?, I'm guessing it is something simple that I am missing..
Thanks
As said, you are repeating same data three times. Increase the rowcounter once you read a row, like this:
string myStr = test.dsSubjects.Tables[0].Rows[rowCtr -1]["SubjectName"].ToString();
rowCtr++;
EDIT : Regarding your second question in the comment, Index is 0 based and Count is always LastIndex + 1.
When you do like this:
int rN = test.dsSubjects.Tables[0].Rows.Count;
then the last row you can access is rN - 1, actually you are doing this here: test.dsSubjects.Tables[0].Rows[rowCtr -1]["SubjectName"].ToString();.
The code above should work fine, you can test replacing rowCtr by 1 to 7.
Your nested for loop executing for three times but here:
test.dsSubjects.Tables[0].Rows[rowCtr -1]["SubjectName"].ToString();
You always getting same value.So your values are repeating three time.Check your value and try again.
Try this one:
for (rowCtr = 0; rowCtr < rN; rowCtr+=3)
{
// Create a new row and add it to the table.
TableRow tRow = new TableRow();
Table1.Rows.Add(tRow);
int temp = rowCtr;
for (int i = 0; i<3; i++)
{
if(temp >=rN) break;
// Create a new cell and add it to the row.
TableCell tCell = new TableCell();
tRow.Cells.Add(tCell);
// Add a literal text as control.
string myStr = test.dsSubjects.Tables[0].Rows[temp]["SubjectName"].ToString();
tCell.Controls.Add(new LiteralControl(myStr));
temp++;
}
}

How to bind datagridview after giving datasource?

Hello sir i have one question
i am binding my data to datagridview like this
dataGridView1.DataSource = dt1;
Now based upon one of the column in datagridview i am adding no of columns to datagridview for example
this is the coding of binding columns to dynamic columns after binding datasource
for (int j = 0; j < i; j++)
{
if (j >= (dataGridView1.Columns.Count - 10))
{
DataGridViewColumn col = new DataGridViewTextBoxColumn();
col.DataPropertyName = "";
col.HeaderText = j.ToString();
col.Name = j.ToString();
dataGridView1.Columns.Add(col);
}
}
So now my real question starts now
now from database i have to bind values for this dynamic columns
so code looks likes
foreach (DataGridViewRow dgvr in this.dataGridView1.Rows)
{
foreach (DataGridViewColumn dgvc in this.dataGridView1.Columns)
{
string query3 = "select pcs from purchase_sr_details where purchase_details_id='" + dataGridView1.Rows[dgvr.Index].Cells[1].Value + "'";
if (dgvc.Index > 8)
{
DataTable dt2 = connection.getexecuted(query3);
if (dt2.Rows.Count > 0)
{
for (int i = 0; i < dt2.Rows.Count; i++)
{
dataGridView1.Rows[dgvr.Index].Cells[""+i+""].Value = dt2.Rows[i]["pcs"].ToString();
}
}
}
}
}
All is working fine but i can't retrivew values to columns nothing displays nothing retrieved dynamic columns generated but values not binded to that one this one is very confused i am stuck 2 days in this one
I think your problem is you are using a mixture of binding and non-binding. You can't change the cells directly if you are binding to the datagridview. You have two choices:
Change your original query so that you get the dynamic columns as well. Let sql do the work, not your code. That's what I would try and do.
If that is not possible you need to get the datatable that the grid is binding to, add your columns to it (i.e. DataColumns), and rebind to the new datatable.

Datagridivew DataGridViewComboBoxColumn select value member

i have datagridview which has one combobox column. i populate combobox column. when i select any text from combobox column then i need to get the value when i read the data in for loop.
dgFilter is here datagridview
DataGridViewComboBoxColumn dgcoSpec = new DataGridViewComboBoxColumn();
dgcoSpec = new DataGridViewComboBoxColumn();
dgcoSpec.DataSource = loadOperators();
dgcoSpec.DisplayMember = "Operatortxt";
dgcoSpec.ValueMember = "Operatorvalue";
dgcoSpec.AutoComplete = true;
dgcoSpec.HeaderText = "Operators";
dgcoSpec.Name = "Operators";
dgcoSpec.DefaultCellStyle.NullValue = "--Select--";
dgcoSpec.Width = 130;
dgFilter.Columns.Insert(1, dgcoSpec);
here this way i read data from combobox column
for (int i = 0; i <= dgFilter.Rows.Count - 1; i++)
{
strOperator = dgFilter.Rows[i].Cells[1].Value.ToString().Trim();
}
but the problem is i am not getting the combox value member rather i am getting display member.
so how to extract value member from for loop. please guide me with code. thanks
The value member is the string that is displayed inside the DataGridViewComboboxCell.
The actual Combobox control only exists during the time frame in which the user is editing the cell.
If you mean that you would like to get the index of the value in the list of the DataGridViewComboboxCell items, you can query the index of the value:
for (int i = 0; i <= dgFilter.Rows.Count - 1; i++)
{
var cell = dgFilter.Rows[i].Cells[1] as DataGridViewComboboxCell;
int index = cell == null || cell.Value == null ? -1 : cell.Items.IndexOf(cell.Value);
Console.WriteLine(index);
}
In this example, I am using -1 as an invalid value.
EDIT Just noticed you are using a DataSource;
See DataGridViewComboBoxColumn name/value how? for possible duplicate.

Categories

Resources