sum values which are loaded in gridview - c#

How can I plus all values of one selected row of a gridview in C# asp.net application?
For example I have a gridview in which is only one row. Values of this row are only number. So I want to plus this numbers.
I tried this loop but it writes all gridview numbers(it isn't summing them).
for (int i = 2; i < GridView1.Columns.Count; i++)
{
int x = 0;
x += int.Parse(GridView1.Rows[0].Cells[i].Text);
Response.Write(x.ToString());
}

I think you should approach this from a different perspective. The GridView is just a display control and doesn't 'hold' the data it is displaying. You are trying to use data that it really doesn't contain using a 'screen scrape' approach. You should be looking to the DataSource you bound to the grid in the first place and using the data there.
For example:
List<YourObjectWithTheNumbers> lst = something;
yourGridView.DataSource = lst;
ViewState["YourData"] = lst; // you could use Session instead: Session["YourData"]
So at this point your data is bound and saved for later use so now just update your numbers and rebind to the GridView again:
List<YourObjectWithTheNumbers> lst =
(List<YourObjectWithTheNumbers>)(ViewState["YourData"]);
int rowTotal = 0;
rowTotal += lst[0].Field1;
rowTotal += lst[0].Field2;
//etc...
yourLiteral.Text = rowTotal.ToString();
At this point you are using the actual data, not pulling it out of the grid that should be used for display purposes. It's also more secure in that you can keep the data source securely stored on the server if necessary (don't use ViewState if this is a concern) so that it can't be manipulated.

In HTML GridView render as table , better you can use Jquery to add the values ,
var total=0;
$('#gridview1').find('tr td').each(function(i, td){
var data= parseInt( $(td).val());
total+=data;
});

I created method in which I had loop and it worked !!!!!!!
public int Sum()
{
int z = 0;
int i;
int x = 0;
for (i = 0; i < GridView1.Columns.Count; i++)
{
x += int.Parse(GridView1.Rows[0].Cells[i].Text);
}
return x;
}
It was #N4TKD idea. Thanks to you !!!!

Related

Count the frequency of each elements in a DataGridView in .Net Windows Application Form

I have some datasets that I read from csv files into DataGridViews and I need to plot some charts where I count the frequency of each different variable on each column.
I found a code that count the frequency of array elements and then print them, I tried using the same logic on my datagrid.
I started with a column ("SEX" column) that has only 2 values (2.0 or 1.0), but when I try to view the count result I always get 1 (which means it didn't count a thing). It's supposed to show the count of the last different value found in the column (in my case 2.0 which has 140ish occurence).
Edit: I tried appending the count result to the textbox and I see that I end up with 1 for each loop, while I am supposed to get only 2 values (which are the count 2.0and then the count of 1.0)
I also need to plot the output, so I am guessing I could use a dictionary where I store the variable name + the frequency.
public void countFreq() //function to count the frequency of each var in a column -not working yet-
{
var n = dataGridView1.RowCount;
var visited = new bool[n];
// Traverse through array elements and
// count frequencies
for (var i = 0; i < n; i++)
{
// Skip this element if already processed
if (visited[i] || dataGridView1.Rows[i].Cells["SEX"].Value
== null)
continue;
// Count frequency
var count = 1;
for (var j = i + 1; j < n; j++)
if (dataGridView1.Rows[i].Cells["SEX"].Value == dataGridView1.Rows[j].Cells["SEX"].Value)
{
visited[j] = true;
count++;
}
textFile.Text += count.ToString(); //for testing purposes I used a textfield to print the last count value
}
}
I know that for a column where the values are explicit I can just loop on my datagrid rows and use the count method (which I did) but for most my data I don't explicitly know the values in each row so I needed to find a way to do that.
I am not sure if this is what you are looking for. In addition, the code below loops through the rows in the grid, however, if the grid has a data source I suggest looping though that collection instead of the grid rows.
Below is a method that takes a column index and returns a Dictionary<string, int>. A simple loop through each cell in the given column and if the cell's Value is not in the dictionary, we will add it. If the cells value is already in the dictionary will simply increment its int Value. After the loop finishes, the dictionary is returned. Something like…
private Dictionary<string, int> GetCountOfValues(string columnName) {
string curKey = "";
Dictionary<string, int> valuesAndCounts = new Dictionary<string, int>();
foreach (DataGridViewRow row in dataGridView1.Rows) {
if (!row.IsNewRow) {
if (row.Cells[columnName].Value != null) {
curKey = row.Cells[columnName].Value.ToString();
if (valuesAndCounts.ContainsKey(curKey)) {
valuesAndCounts[curKey]++;
}
else {
valuesAndCounts.Add(curKey, 1);
}
}
}
}
return valuesAndCounts;
}
Usage may look something like…
Dictionary<string, int> column0Counts = GetCountOfValues("Col0");
Dictionary<string, int> column1Counts = GetCountOfValues("Date");
You should really load your CSV data into a datatable and then query that
var dt = SomeFunctionThatReadsCsvIntoDatatable(..);
yourDataGridView.DataSource = dt;
Your query is then answered, simply, by grouping the datatable using linq;
(yourDataGridView.DataSource as DataTable).Rows
.Cast<DataRow>()
.GroupBy(r => r["someColumn"])
.Select(g => new { K = g.Key, C = g.Count() });
"someColumn" would be "SEX"
K would end up as an object holding whatever Type the data is ` - it's hard to tell from the information posted whether you've just got your csv as strings or whether they're eg doubles, dates etc
If you want to do it for all columns, it would probably be easiest to do it in a loop on the datatable Columns collection. DataColumn.ColumnName provides the "someColumn"

FindControl and Get Selected Value of Dropdown

This scenario is occurring when using C# code behind to find HTML Controls added dynamically from SQL Data Results.
Using the following there is an iteration though the Table rows and row each table row, we write the Controls value, in this case a HtmlSelect. The Html Select Element is in Cell 3
for (int i = 1; i <= Table1.Rows.Count - 1; i++)
{
HtmlSelect select = Form.FindControl("MainContent_selectBoxstatus" + i) as HtmlSelect;
System.Diagnostics.Debug.Write(select.Value);
}
Resulting in:
A first chance exception of type 'System.NullReferenceException'
occurred in project.dll
If i use the following:
for (int i = 1; i <= Table1.Rows.Count - 1; i++)
System.Diagnostics.Debug.Write(Table1.Rows[i].Cells[0].Text);
I get the desired result, of the text from Cell 1.
How the Select Dropdown is created:
for (int i = 0; i < dr.FieldCount; i++)
HtmlSelect sStatus = new HtmlSelect();
sStatus.Items.Add(new ListItem("Working", "0"));
sStatus.Items.Add(new ListItem("Fault", "1"));
sStatus.SelectedIndex = 0;
sStatus.Attributes.Add("class", "dropdownlist");
sStatus.ID = "selectBoxstatus" + rowindex;
cell.Controls.Add(sStatus);
That's what usually happens when you are trying to "hack" ASP.NET internals. I mean "hack" because using magic strings to resolve the auto-generated ids assigned to child controls is extremely unsafe. There are much better and safer ways to do this.
1- If you want to render a tabular layout, I'd strongly recommend using a databound control such as a GridView, ListView, etc where you can intersect its RowDatabound event and retrieve the child controls in a safe manner
2- If you can't afford to do a re-write then replace your code as follows...
for (int i = 0; i < Table1.Rows.Count; i++)
{
HtmlSelect select = Table1.Rows[i].Cells[0].FindControl(string.Format("selectBoxstatus{0}", i)) as HtmlSelect;
if(select != null)
System.Diagnostics.Debug.Write(select.Value);
}
Option 2 Code Analysis
for (int i = 0; i < Table1.Rows.Count; i++)
Nitpicking, but initializing i to 0 this makes it easier to read...believe it
HtmlSelect select = Table1.Rows[i].Cells[0].FindControl(string.Format("selectBoxstatus{0}", i)) as HtmlSelect;
I'm not too sure what Form meant in your original post but it makes more sense to use the object you're iterating....Table1 rows collection. I also refer to Cell[0] which is the first cell in the iteration's current row(feel free to adjust it)...this is still not safe but it's the only way to achieve it in the current scenario, if you need more code safety, then resort to option one. Also notice that FindControl doesn't mess around with auto-generated id, it simply uses the actual Id specified for the child control
if(select != null)
After you attempt to retrieve the select control make sure to check whether the control was successfully retrieved or not.
Hope it makes sense
Try changing your loop so that you call findcontrol on the row instead:
for (int i = 1; i <= Table1.Rows.Count - 1; i++)
{
HtmlSelect select = Table1.Rows[i].FindControl("MainContent_selectBoxstatus" + i) as HtmlSelect;
}

DevExpress GridView | DataGridView

I want to do the following but using GridView of DevExpress , how Can I do that please ?
List<RCDATA_INDEX> somethings = new List<RCDATA_INDEX>();
foreach (DataGridViewRow row in (IEnumerable)this.dataGridView1.Rows)
{
AZ.RCDATA_INDEX items = new AZ.RCDATA_INDEX
{
datasize = Convert.ToUInt32(row.Cells[5].Value.ToString())
};
item.filenum = Convert.ToUInt32(row.Cells[2].Value.ToString()[7].ToString());
item.hash = row.Cells[1].Value.ToString();
item.realname = row.Cells[3].Value.ToString();
item.offset = Convert.ToUInt32(row.Cells[4].Value.ToString());
item.new_value = row.Cells[6].Value.ToString();
somethings.Add(items);
}
You can traverse through all the data rows within a GridView one-by-one, using the following approach:
// Obtain the number of data rows.
int dataRowCount = gridView.DataRowCount;
// Traverse data rows
for (int i = 0; i < dataRowCount; i++) {
object cellValue = gridView.GetRowCellValue(i, "... specify field name here ...");
// do something with cell Value
}
Please refer the Traversing Rows and Obtaining and Setting Cell Values help-articles to learn more;
I would prefer using BindingSource and bind it into Gridview. After that if you want to making manipulation of your data. You just need to call like this :
List<RCDATA_INDEX> somethings = new List<RCDATA_INDEX>();
var Result = RCDataBS.Cast<RCDATA_INDEX>();
somethings.AddRange(Result);
It would be much easier using this code and you don't need to spend your resource to convert all the data into your model.

asp.net: How to manually (c#) select radiobutton in radiobuttonlist inside gridview from Session

Im having problems after postback in asp.net / c#. All radiobuttlists in gridview are cleared on postback (one radiobuttonlist on each row). So I save them to a Session variable.
But I cant set them back from the Session variable. Here is the code in page_load:
//.. testing for null,etc
for (int i = 0; i < lstRadioButtons.Count; i++)
{
RadioButtonList rbl = (RadioButtonList)gwTract.Rows[i].FindControl("RadioButtonList1");
rbl.SelectedItem.Value = lstRadioButtons[i]; //list with strings "0", etc
Debug.WriteLine("yep...");
}
Thanks in advance!
Assuming lstRadioButtons contains the value for a given row:
for (int itemIndex = 0; itemIndex < rbl.Items.Count; itemIndex++)
if (rbl.Items[i].Value == lstRadioButtons[i])
rbl.SelectedIndex = itemIndex;
Assuming lstRadioButtons contains the index for a given row:
rbl.SelectedIndex = int.Parse(i); //You may want to use TryParse to handle failure

Finding an item in asp.ListView with Value when paging is enabled

I'm trying to find the selected Item in an aspx ListView that is on a separate page, then switch the page and select the item. I have the value property of the ListViewItem I am looking for, but cannot seem to get it to work. Here is what I tried:
for (int i = 0; i < lvProject.Items.Count; i++)
{
if (((Label)lvProject.Items[i].FindControl("Project_IDLabel")).Text == project.ToString())
{
lvProject.SelectItem(i);
break;
}
}
So lvProject is my list view. The project Variable is an Int64 which represents the UID of my Project. This is also the Value of my ListViewItems. The problem with the code above is that when paging is enabled, and the item is on a different page this will not work because the listView.Items.Count is set to the # of Items on the current page only.
My goal is to find the item, set the listview to display the correct page, and finally select the item. You would figure that I could just set the SelectedValue property, but this is not that simple as it is read only. Any ideas would help greatly, thanks in advance.
--Roman
In order to get the total record count from the object data source, you should use the Selected event as follows:
protected void ObjectDataSource1_Selected(object sender, ObjectDataSourceStatusEventArgs e)
{
// Get total count from the ObjectDataSource
DataTable dt = e.ReturnValue as DataTable;
if (dt != null) recordCount = dt.Rows.Count; // recordCount being declared outside the method
}
You would then be able to search for the item as follows:
for (int i = 0; i < recordCount; i++)
{
Label lblItem = (Label)lvProject.Items[i].FindControl("IdLabel");
if (lblItem.Text.Equals(itemToSearch))
{
lvProject.SelectedIndex = i;
break;
}
}
Hope it helps!
How do you bind ListView Items?
If you are using database level paging (stored procedure, query) - you should do search in the same way - using database query/stored procedure by passing a search criteria.
If you are bind ListView Items to a collection of items which are provided by a business/data layer - you have to create search method on layer which provides items so this method will be able to loop through the items.
You should set the SelectedIndex property to i
for (int i = 0; i < lvProject.Items.Count; i++)
{
if (((Label)lvProject.Items[i].FindControl("Project_IDLabel")).Text == project.ToString())
{
lvProject.SelectedIndex = i;
break;
}
}

Categories

Resources