aspx Gridview conditional format - asp.net

I have a simple gridview and code behind to conditionally format some rows. It runs but nothing gets colored. I've tried various autoformatting and finally removed all in the hope that there was some magic but to no avail
protected void GridviewRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int CellValue = Convert.ToInt32(e.Row.Cells[2].Text);
if (CellValue >= 0)
{
e.Row.Cells[2].BackColor = System.Drawing.Color.Green;
}
if (CellValue < 0)
{
e.Row.Cells[2].BackColor = System.Drawing.Color.Red;
}
}
}
<%# Page Language="VB" CodeBehind="TrainPurch.aspx.vb" %>
<!DOCTYPE html>
<html lang="en" xmlns=http://www.w3.org/1999/xhtml>
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="D:\Inetpub/wwwroot\dealerinfo\oracledealerinfo.mdb" SelectCommand=" SELECT tblDealerMifTrained.R12Account, tblDealerMifTrained.GroupOwner, tblDealerMifTrained.Units AS Units, tblDealerMifTrained.ProductCode, ProdToEDP.Model, qry6aTrainedPurchase.Trained FROM (ProdToEDP INNER JOIN tblDealerMifTrained ON ProdToEDP.ProductCode = tblDealerMifTrained.ProductCode) INNER JOIN qry6aTrainedPurchase ON (tblDealerMifTrained.ProductCode = qry6aTrainedPurchase.ProductCode) AND (tblDealerMifTrained.R12Account=qry6aTrainedPurchase.R12Account) WHERE (((tblDealerMifTrained.Type)='Purchase')) GROUP BY tblDealerMifTrained.R12Account, tblDealerMifTrained.GroupOwner, tblDealerMifTrained.Units, tblDealerMifTrained.ProductCode, ProdToEDP.Model, qry6aTrainedPurchase.Trained;"></asp:AccessDataSource>
<div style="height:750px; overflow:auto">
<asp:GridView
id="GridView2"
runat="server"
AllowSorting="True"
DataSourceID="AccessDataSource1" Caption="Trained Purchased" PageSize="25" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="R12Account" HeaderText="R12Account" SortExpression="R12Account" />
<asp:BoundField DataField="GroupOwner" HeaderText="GroupOwner" SortExpression="GroupOwner" />
<asp:BoundField DataField="Units" HeaderText="Units" SortExpression="Units" />
<asp:BoundField DataField="ProductCode" HeaderText="ProductCode" SortExpression="ProductCode" />
<asp:BoundField DataField="Model" HeaderText="Model" SortExpression="Model" />
<asp:BoundField DataField="Trained" HeaderText="Trained" SortExpression="Trained" />
</Columns>
</asp:GridView> </div>
</form>
</body>
</html>

Display the page in design mode, right click on the gridview, and display the property sheet.
Like this:
Now that you display the property sheet, eg this:
In above, click on the event icon (lighting bolt).
You now see this:
So, double click on the Row data bound text area, and that should jump you to your code behind editor, and you can now type in code for that event.
However, I do note that the page you have has the code behind set for VB, and not c#. So I would REALLY suggest that you create a blank new page, and then copy the parts of the old web form into the new one - don't copy the WHOLE page markup, but JUST the parts inside of the form tags that you require. And then try the above set of steps to create the row data bound event.

In your code RowDataBound event missing.
<asp:GridView id="GridView2" runat="server" AllowSorting="True" OnRowDataBound= "GridviewRowDataBound"

Related

retrieve the value of hidden column of grid view on submit button click

How can I retrieve the value of hidden column of grid view on submit button click. I searched on internet but mostly found methods on row button click.
<asp:GridView ID="GridBilling">
<Columns>
<asp:BoundField Visible="false" DataField="ID"/>
<asp:TemplateField HeaderText="S No." ItemStyle-Width="8%">
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
... other fields ommitted
</Columns>
</asp:GridView>
<br />
<div style="width:100%"><asp:Button ID="btn_SubmitGrid" runat="server" Text="SUBMIT" OnClick="btn_SubmitGrid_Click" /></div>
protected void btn_SubmitGrid_Click(object sender, EventArgs e)
{
int iRowCnt = 0;
foreach (GridViewRow row in GridBilling.Rows)
{
dr = dt_mnthlybilling.NewRow();
dt_mnthlybilling.Rows.Add(dr);
iRowCnt += 1;
}
}
If you set visible to false on the hidden field, then you can't access it in the back-end code. This is because the data doesn't get rendered. However you can do do by accessing the dataKeys. Set the DataKeyNames on GridView. e.g:
<asp:GridView ID="GridBilling" runat="server" DataKeyNames="ID">
Then in code you can retrieve the value as
GridBilling.DataKeys[ROW_INDEX].Value; // This should return an object. I believe you can set to multiple keys (per row).
Alternatively you hide the column with css (on both header and item)
<asp:BoundField DataField="ID" HeaderStyle-CssClass="hidden" ItemStyle-CssClass="hidden" />
Css add:
<style type="text/css">
.hidden
{
display: none;
}
</style>
In back-end code, the bound column can be accessed as
GridBilling.Rows[*ROW_INDEX*].Cells[0].Text; // If you have a html control you can replace text with FindControl("control_name")
Also in your cs code you have a call to NewRow(). If you accessing a row then you should be calling row. eg:
int iRowCnt = GridBilling.Rows.Count;
foreach (GridViewRow row in GridBilling.Rows)
{
// row.Cells[0].Text
dt_mnthlybilling.Rows.Add(row);
}
(It's been years since I've done web forms, so the syntax may be slightly incorrect.)

ASP.NET - GridView, adding header row in code

I've scoured the web looking at the various examples and have tried every single one of them. I get the same error no matter what. I am trying to add the headerrow to the GridView control in code. I have tried adding the below code in every possible event from gridview prerender to all of the events of the page. Same deal. Always get the error: The table must contain row sections in order of header, body, then footer.
I have stripped down the page to the bare essentials - removing the master page and all CSS.
Here is the aspx and grid view code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Shipping.Admin.Default" Title="Apps - Shipping" %>
<html>
<head><title></title></head>
<body>
<form runat="server" id="form1">
<br />
<h1>Admin Page</h1>
<br />
<asp:GridView ID="gvShipments" runat="server" AllowSorting="True"
AutoGenerateColumns="False" onsorting="gvShipments_Sorting" Width="100%"
AllowPaging="True" onpageindexchanging="gvShipments_PageIndexChanging"
PageSize="50">
<PagerSettings Position="TopAndBottom" />
<Columns>
<asp:BoundField DataField="RequestDate" HeaderText="Request Date" SortExpression="dtRequestDate" />
<asp:BoundField DataField="Requestor" HeaderText="Requestor" SortExpression="Requestor" />
<asp:BoundField DataField="CompanyName" HeaderText="Company" SortExpression="CompanyName" />
<asp:BoundField DataField="ShipmentDescription" HeaderText="Description" SortExpression="ShipmentDescription" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
<asp:BoundField DataField="State" HeaderText="State" SortExpression="State" />
<asp:BoundField DataField="ShipmentType" HeaderText="Shipment Type" SortExpression="ShipmentType" />
<asp:BoundField DataField="ServiceLevel" HeaderText="Service Level" SortExpression="ServiceLevel" />
<asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status" />
<asp:HyperLinkField DataNavigateUrlFields="ShipmentId" DataNavigateUrlFormatString="Shipment.aspx?CatId=Admin&sID={0}" Text=" edit" />
</Columns>
</asp:GridView>
<br />
</form>
</body>
</html>
Here is a snipped of the code-behind. This method is called in the Page_Load method:
private void LoadGridView()
{
DataSet ds = new DataSet();
ds = GetDataset();
DataTable dtRequests = ds.Tables["Admin"];
DataView dv = new DataView(dtRequests);
if (ViewState["sortexpression"] != null)
{
dv.Sort = ViewState["sortexpression"].ToString() + " " + ViewState["sortdirection"].ToString();
}
else
{
dv.Sort = "dtRequestDate DESC";
}
gvShipments.DataSource = dv;
gvShipments.DataBind();
**if (gvShipments.Rows.Count > 0)
{
this.gvShipments.UseAccessibleHeader = true;
this.gvShipments.HeaderRow.TableSection = TableRowSection.TableHeader;
}**
ds.Dispose();
}
I have tried adding the code inside bolded the IF statement everywhere. I am stumped. Please help!
Thanks
Try this add Page_PreRender event and post your code inside it, then your code look like as below
protected void Page_PreRender(object sender, EventArgs e)
{
if (gvShipments.Rows.Count > 0)
{
gvShipments.UseAccessibleHeader = true;
gvShipments.HeaderRow.TableSection = TableRowSection.TableHeader;
}
}
PageLifeCycle

How to collapse and expand devexpress master/detail asp.net gridview

I have two asp.net devexpress gridviews in master/detail configuration. I expand a master row to display the child rows and do manipulations on the child rows such as edit, add new and delete rows. After that I want the parent gridview to collapse and both the gridviews to refresh with new data. Please let me know how could I do it. On devexpress site I see the mention of CollapseRow and ExpandRow javascript clientside methods. But couldn't find any sample code describing how to call those.
Thanks
First assign clientInstanceName to grid as:
<dx:ASPxGridView ID="ASPxGridView1" runat="server" KeyFieldName="ID"
ClientInstanceName="grid">
When you complete update or delete as you said call grid.CollapseAllDetailRows(); after the operation that you have completed. or on ASPxClientGridView.DetailRowExpanding Event set the expanded detail row visibleindex. check the following code snippet and code as per your requirement.
<html>
<head runat="server">
<title></title>
<script language ="javascript" type ="text/javascript">
var focusedIndex;
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<dx:ASPxGridView ID="ASPxGridView1" runat="server" KeyFieldName="ID" ClientInstanceName="grid">
<ClientSideEvents DetailRowExpanding="function(s, e) {
focusedIndex = e.visibleIndex;
}" />
<SettingsBehavior AllowFocusedRow="True" AllowSelectByRowClick = "true" />
<SettingsDetail ShowDetailRow="True" />
</dx:ASPxGridView>
<dx:ASPxButton ID="ASPxButton1" runat="server" AutoPostBack="False" Text="ASPxButton">
<ClientSideEvents Click="function(s, e) {
//var visibleindex = grid.GetFocusedRowIndex();
//grid.CollapseAllDetailRows();
if( focusedIndex != 'undefined')
{
grid.CollapseDetailRow(focusedIndex );
}
}"/>
</dx:ASPxButton>
</div>
</form>
</body>
</html>

Optionally display a text in place of GridView when the GridView has no rows

I have a basic GridView that displays a list of tasks to do (just an example)
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AllowSorting="True" >
<Columns>
<asp:BoundField DataField="todo" HeaderText="To Do" ReadOnly="True" SortExpression="todo" />
<asp:BoundField DataField="byDate" HeaderText="By When" ReadOnly="True"
SortExpression="byDate" />
the data source is specified within the aspx page and it is a result set from a stored procedure
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="..."
SelectCommand="pToDoList" SelectCommandType="StoredProcedure">
</asp:SqlDataSource>
So the rendered page presents tasks as rows of data (a row per task)
My question is
When there is not data returned by stored procedure the page remains blank. I would like to have a text instead saying for example: "nothing to do today"
How to do that? Thank you
Use the EmptyDataTemplate:
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="true"
runat="server">
<emptydatarowstyle backcolor="LightBlue"
forecolor="Red"/>
<emptydatatemplate>
<asp:image id="NoDataImage"
imageurl="~/images/Image.jpg"
alternatetext="No Image"
runat="server"/>
No Data Found.
</emptydatatemplate>
</asp:gridview>
Example from http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.emptydatatemplate.aspx
there is a property "EmptyDataText" that allows you to specify text if the gridview is empty
Add a Label to the page, call it ErrorLabel, then do something like this in the DataBound event of the GridView:
protected void GridView1_DataBound(object sender, EventArgs e)
{
if(GridView1.Rows.Count <= 0) ErrorLabel.Text = "Nothing to do today";
else ErrorLabel.Visible = false;
}
Although a Google search would have probably gotten that for you.
One option is to use the Footer to display this message. During the ItemDataBound, if the ItemType is the footer, check if the DataSource is empty and if it is, display the message.
Or if you want to work declaritvely in the ASPX you can use the EmptyDataTemplate and add your message there.
I would simply would add a label control noDataLabel containing the text "Nothing to do today", and add some code in the Page_Load event:
if (GridView1.Rows == 0)
{
GridView1.Visible = false;
}
else
{
noDataLabel.Visible = false;
}
It is a bit crude, but it beats have embedded C# inside your webform HTML. If there is no data, and the form is rendered, the GridView is simply ignored.

Can I add an additional action to a DetailsView in ASP.NET?

Currently I have a DetailsView attached to a GridView. When you select an item from the GridView the details show up in the DetailsView (duh). Right now there are 3 event options on the DetailsView: Edit, Delete, and New. I would like to add a 4th, Format. This will simply run some queries and then perform a delete. Is this possible and how?
Another possibility would be to add this event to the GridView instead (maybe while in Edit mode?)
If you add your own buttons to the DetailsView as suggested you can hook the ItemCommand event on the DetailsView and add any logic for each CommandName in the ItemCommand method
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void CustomerDetailView_ItemCommand(Object sender, DetailsViewCommandEventArgs e)
{
// Use the CommandName property to determine which button
// was clicked.
if (e.CommandName == "Add")
{
// Add the current store to the contact list.
// Get the row that contains the store name. In this
// example, the store name is in the second row (index 1)
// of the DetailsView control.
DetailsViewRow row = CustomerDetailView.Rows[1];
// Get the store's name from the appropriate cell.
// In this example, the store name is in the second cell
// (index 1) of the row.
String name = row.Cells[1].Text;
// Create a ListItem object with the store's name.
ListItem item = new ListItem(name);
// Add the ListItem object to the ListBox, if the
// item doesn't already exist.
if (!ContactListBox.Items.Contains(item))
{
ContactListBox.Items.Add(item);
}
}
}
</script>
<html >
<head runat="server">
<title>
DetailsView ItemCommand Example</title>
</head>
<body>
<form id="Form1" runat="server">
<h3>
DetailsView ItemCommand Example</h3>
<asp:DetailsView ID="CustomerDetailView"
DataSourceID="DetailsViewSource"
AutoGenerateRows="false"
DataKeyNames="CustomerID"
AllowPaging="true"
OnItemCommand="CustomerDetailView_ItemCommand"
runat="server">
<FieldHeaderStyle BackColor="Navy" ForeColor="White" />
<Fields>
<asp:BoundField DataField="CustomerID" HeaderText="Store ID" />
<asp:BoundField DataField="CompanyName" HeaderText="Store Name" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:ButtonField CommandName="Add" Text="Add Contact" />
</Fields>
</asp:DetailsView>
<hr />
Contacts:<br />
<asp:ListBox ID="ContactListBox" runat="server" />
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Northwind sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the web.config file. -->
<asp:SqlDataSource ID="DetailsViewSource" runat="server"
ConnectionString=
"<%$ ConnectionStrings:NorthWindConnectionString%>"
InsertCommand="INSERT INTO [Customers]([CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country]) VALUES (#CustomerID, #CompanyName, #Address, #City, #PostalCode, #Country)"
SelectCommand="Select [CustomerID], [CompanyName],
[Address], [City], [PostalCode], [Country] From
[Customers]">
</asp:SqlDataSource>
</form>
</body>
</html>

Resources