I am using a website which contains a gridview for view details of Product details... It contains columns like name,area,phnoe no,quantity,price,total.... now I want to calculate total value for that I have to multiply the columns quantity and Price and also put that answer to total column in grid... How shall I do this?
There are three(may be more) ways to accomplish this.
First is query database and show result on grid
To do this : Query like
select name,area,phone,quantity,price,quantity * price as Total from YOUR_TABLE
Then bind it into your datagrid
Second is before binding your source which is here datatable into the grid,loop for this table for your sum.
To do this: You have datatable but not you have column named Total this time.
Now you need to add a new column as Total into the datatable.
DataColumn totalColumn = new DataColumn("Total");
totalColumn.Expression = "Quantity * Price";
totalColumn.DataType = //double,integer
dataTable.Columns.AddAt(totalColumn, 0);
All we have done above is generating a computed column
Third,use javascript for cells to assemble your specific values to sum,but this time you need to find your datagrid then your cells in which you should prefer using a javascript framework like jquery.I do not know any reference point for this,but First and second options will be much easier to do
Best Regards
Myra
Its simple yaar,
if the row index is 0 and your column name in price means ,the following is the way to getvalues,
GridViewID.Rows[0].cells["Price"].ToString()
It depends on your requirement/ wish, you can use Javascript to calculate total on client side if you are not fetching data from database.
You can also do it in code behind but it would be better to use JQuery to fetch the data and calculate it on client side.
but i have to it in code behind only
Ok then. You need to a template column to your GridView
<asp:TemplateField>
<ItemTemplate>
<asp:Literal ID="litTotal" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Subscribe to the RowDataBound Event.
protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == RowType.DataRow)
{
YourObject _item = (YourObject)e.Row.DataItem; // use quickwatch to figure out how to cast into your desired type
Literal _litTotal = (Literal)e.Row.FindControl("litTotal");
_litTotal.Text = _item.Quantity * _item.Price;
}
}
Related
I have a data table with data like "insurance name, plantype, premium...." for each row.
So on my front end I have to show like below:
Insurance Name HealthNet Harvard UniCare
Plan Type HMO PPO HMO
Premium 100 150 200
So sometimes I may have only two columns to show HealthNet and Harvard. Sometimes more than three. How to use repeater in this case to make it dynamic based on data table count?
Thanks
Sample:
aspx markup as shown below:
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="true">
</asp:GridView>
In codebehind simply do this:
gv.DataSource = yourDataTable; // doesn't matter how many columns are there, it will handle it automatically
gv.DataBind();
This will help how to pivot a data table:
http://geekswithblogs.net/dotNETvinz/archive/2009/05/10/pivot-data-in-gridview---a-generic-pivot-method-with.aspx
I have a GridView and one of the columns has a TemplateField using a LinkButton (ButtonField)
I can get the value of a specific cell in my Grid Just fine. Using:
GridViewRow row = GridView1.SelectedRow;
lblSalesmanCustomers.Text = row.Cells[2].Text;
I then display the text from that cell in a Label.
However I cannot get this to work with a ButtonField Template. It only works with a non Template column.
How can I get the value of a specific cell in a column that is using a ButtonField / TemplateField?
EDIT: This is My Button Field Code inside my GridView:
<asp:ButtonField DataTextField="Customer" HeaderText="Customer" ButtonType="Link" CommandName="Select" />
Also, this is happening in this event:
protected void gvManagerCustomers_SelectedIndexChanged(object sender, EventArgs e)
See if var Button = row.Cells["Customer"].Controls[0]; would retrieve the button you need.
You might need to cast it to the correct type.
I know there are issues with hyperlinkfield and buttonfield but there is a work around. Say you are binding buttonfield text based on a column called ButtonNames, and in that column you have all your names, such as "button bob", "button jerry" etc. In your GridView, add an invisible column as your very first column and bind its value as ButtonNames. You make it invisible by setting one of the visibility properties. Forgot what it was from top of my head. Then, when you want to get the text for the buttonfield simply get the data from that invisible column instead Same applies to hyperlinkfiends.
EDIT: here's some code.
<asp:BoundColumn ItemStyle-HorizontalAlign="Left" DataField="ButtonNames" SortExpression="ButtonNames" HeaderText="TriageId" Visible="false" ReadOnly="true"></asp:BoundColumn>
Then you retrieve it via string s = e.Item.Cells[0].Text where e is a DataGridCommandEventArgs or something to that nature.
There will be a controls collection in the cell - you may be able to access it there.
Though a simpler way would be to use something like:
Label l = row.FindControl("myControlId");
EDIT: true the exact approach above does not work - but you can use the controls, the following does work, note that what we are doing here is pretty much rife with bad practices (but then we are using a GridView for convenience sake after all).
protected void gvManagerCustomers_SelectedIndexChanged(object sender, EventArgs e)
{
var x = ((sender as GridView).SelectedRow.Cells[0].Controls[0] as LinkButton).Text;
}
In order to figure this out set up a debug environment and breakpoint in the handler method then drill down through the class hierarchy. The debugger is our friend ;)
EDIT just to mention the obvious - the column is hard coded here - you will probably have to change it.
I need to find and display the number of rows returned by the query. This query is made using an SQLDataSource object, which is bound to an asp.net GridView control. How can I find this information?
You can't use the Rows property on the grid, because that only gives you what the GridView is currently rendering. You need to hook up to the Selected event on the SqlDataSource and then you can pull the AffectedRows property.
protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e) {
int totalRows = e.AffectedRows;
}
I would suggest that you handle the SQLDataSource.Selected event and check the e.AffectedRows property. It returns the number of selected rows. Also, it is possible to obtain this information programmatically:
DataView dv = (DataView)SQLDataSource1.Select(DataSourceSelectArguments.Empty);
int rowCount = dv.Count;
NOTE: this code will result in selecting data once again. So, the best solution is to use the Selected event for this purpose.
I'm creating a dynamic GridView from a DataTable that is returned from a stored procedure. I call and bind with the following code:
DataTable dt = Sql.reportData(Convert.ToInt32(Session["userID"]));
this.GridView1.DataSource = dt.DefaultView;
this.GridView1.DataBind();
I need to restyle certain columns but they are not always the same column number, and only have the headers text string to identify it. Is there an easy way to track a column down like this so I can edit its attributes?
Thanks,
Alex
I've run into this myself. You've got to loop through the column names, get the index, and then refer to the index to manipulate the style.
Muhammad is right about the timing, but you won't be searching for a label--it seems you want to style the entire column, right?
http://forums.asp.net/p/1076872/1584635.aspx
the above has several versions of a solution.
The best place to find the control and use it will be in the RowCreated event. RowDataBound should not be used because you dont have to manipulate the data with which the column is being binded. So restyle the elements in the column by searching them in the RowCreated event.
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.FindControl("");
}
I have a report page that can display two different reports. So I have a GridView with no columns on my aspx page. I am adding 4 BoundFields to the GridView in the button click event handler. The first column is the one I need to set the width of for one of the reports (the code I'm using to add this column is below).
gvReport.Columns.Clear();
BoundField bf1 = new BoundField();
...
if (ddReportType.SelectedValue == "full") {
bf1.HeaderText = "Facility";
bf1.DataField = "Facility";
bf1.ItemStyle.Wrap = true;
bf1.ItemStyle.Width = 150;
bf1.Visible = true;
gvReport.Columns.Add(bf1);
...
The problem is there is one row that has a SHA512 hash in this column. Since there is no space in the middle of it, the gridview won't wrap it (I think that's what is happening, anyway)! So I thought I'd catch this column in the OnRowDataBound event and add a space in the middle of the hash so it will wrap, but I can't figure out how to reference the BoundField. There's no ID property. Does anyone have a suggestion? Either on how to reference the BoundField, or another way to get this to display nicely?
I had the columns in the aspx file originally and tried using:
gvReport.Columns[0].ItemStyle.Width = 150;
gvReport.Columns[0].ItemStyle.Wrap = true;
but that didn't work either. This is very frustrating!
So we went with Plan C. I never did figure out how to reference the BoundField. We got around that problem by creating two GridViews in the markup and just changing which one is visible. To solve the problem of the text that won't wrap, we're catching it in the OnRowDataBound event handler and checking the length of the text. We just insert a space in the middle, and voila! It wraps!
The BoundField is a wrong thing. It is more like a definition. Later, when binding or creating rows, you are dealing with rows, cells, and data items.
You could do something like this:
protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string value = e.Row.Cells[1].Text;
if (!string.IsNullOrEmpty(value))
e.Row.Cells[1].Text = value.Insert(value.Length / 2, " ");
}
}
where Cell[1] is the column containing long values. In the same place, you could use e.Row.DataItem to get actual data, but then you'd need to know its type.
You could create a template field and bind to an expression or use its child's data bound event to do the same.
Also, if you were using a DataSet, you could set up calculated field and bind to it. Anyway...