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
Related
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"
my .aspx design source code is
<asp:GridView ID="grdPaymentStatus" runat="server"
AutoGenerateColumns="false"
CssClass="table table-responsive table-striped table-bordered table-advance table-hover"
HeaderStyle-CssClass="ProjectStatusHeader"
OnRowDataBound="grdPaymentStatus_RowDataBound" >
<Columns>
<asp:BoundField DataField="instCount" HeaderText="Installments" HeaderStyle-BackColor="#dddddd" HeaderStyle-Font-Bold="false" />
<asp:BoundField DataField="instPayment" HeaderText="Amount" HeaderStyle-BackColor="#dddddd" HeaderStyle-Font-Bold="false" />
<asp:BoundField DataField="instWord" HeaderText="Words" HeaderStyle-BackColor="#dddddd" HeaderStyle-Font-Bold="false" />
<asp:BoundField DataField="instPaymentMode" HeaderText="Payment Mode" HeaderStyle-BackColor="#dddddd" HeaderStyle-Font-Bold="false" />
<asp:BoundField DataField="instPaymentdat" HeaderText="Payment Done On" HeaderStyle-BackColor="#dddddd" HeaderStyle-Font-Bold="false" />
<asp:BoundField DataField="instIspaid" HeaderText="Payment Status" HeaderStyle-BackColor="#dddddd" HeaderStyle-Font-Bold="false" />
</Columns>
</asp:GridView>
.aspx.cs code is
protected void grdPaymentStatus_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[2].Text != "Paid")
{
Button sendRequestButton = new Button();
sendRequestButton.ID = "PaymentRequest" + Row.Cells[0].Text;
sendRequestButton.Text = "Send Request";
sendRequestButton.CssClass = "btn blue";
sendRequestButton.UseSubmitBehavior = false;
sendRequestButton.CausesValidation = false;
sendRequestButton.Click += new EventHandler(sendRequestButton_OnClick);
e.Row.Cells[2].Controls.Add(sendRequestButton);
}
}
}
protected void sendRequestButton_OnClick(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(AckNo))
BindDetailsPayment(AckNo);
}
Data is binding at page load in (! isPostback) method and whenever i am trying to click on button added in gridview the button click event (sendRequestButton_OnClick) is not firing
please help me out
thanks in advance.....
Even though you bound it on row bound, you need to handle the event in RowCommand.
See the following link.
<telerik:RadGrid runat="server" ID="rdReport" AutoGenerateColumns="false" AllowPaging="true" Skin="Metro" OnItemCommand="ItemCommand" OnItemDataBound="rdReport_ItemDataBound" OnPreRender="rdReport_PreRender" DataSourceID="FountainSource" AllowAutomaticUpdates="true" AllowAutomaticDeletes="true">
<MasterTableView DataKeyNames="ID" CommandItemDisplay="None">
<Columns>
<telerik:GridEditCommandColumn ButtonType="ImageButton" />
<telerik:GridBoundColumn DataField="LocName" HeaderText="Location" ReadOnly="true" />
<
<telerik:GridBoundColumn DataField="Field1Value" HeaderText="Custom Field1" />
<telerik:GridBoundColumn DataField="Field2Value" HeaderText="Custom Field2" />
<telerik:GridBoundColumn DataField="Field3Value" HeaderText="Custom Field3" />
<telerik:GridButtonColumn ConfirmText="Delete?" ConfirmDialogType="RadWindow"
ConfirmTitle="Delete" ButtonType="ImageButton" CommandName="Delete" />
</Columns>
<EditFormSettings>
<EditColumn ButtonType="ImageButton" />
</EditFormSettings>
</MasterTableView>
<PagerStyle Mode="NextPrevAndNumeric" />
</telerik:RadGrid>
On Edit, I like to make a field invisible.
I am using the following code which works but want to check to see if it is best practice:
protected void rdReport_ItemDataBound(object sender, GridItemEventArgs e)
{
// Edit Mode
if ((e.Item is GridEditFormItem) && (e.Item.IsInEditMode))
{
GridEditFormItem fndColumn = (GridEditFormItem)e.Item;
fnColumn["Field1Value"].Parent.Visible = false;
}
}
The solution which was provided by you is perfect but it would be nice if you will also add UniqueName property in each column. If we will not assign the UniqueName than it is consider DataField value as UniqueName.
ASPX
<telerik:GridButtonColumn DataField="Field1Value" HeaderText="Custom Field1" UniqueName="Field1Value" />
ASPX.CS
protected void rdReport_ItemDataBound(object sender, GridItemEventArgs e)
{
// Edit Mode
if ((e.Item is GridEditFormItem) && (e.Item.IsInEditMode))
{
GridEditFormItem fndColumn = (GridEditFormItem)e.Item;
fnColumn["Field1Value"].Parent.Visible = false; // "Field1Value" is column uniquename
}
}
Let me know if you required more information.
This is just a suggested alternative. I've worked with telerik a few times, and it is a pain to say the least. What you could do is also add a tertiary condition to the parent container. If in edit mode, then show a class, such as 'edit', or 'current'. If not in edit mode, don't show the class. Then, in your CSS you can select for whatever element you want to hide.
<div>
<input type="text" id="whateverisgenerated" class="uniqueclass" />
</div>
Then, when in edit mode, you will have
<div class="edit">
<input type="text" id="whateverisgenerated" class="uniqueclass" />
</div>
With your CSS:
div.edit input.uniqueclass { display: none; }
As for your telerik control (I just grabbed something from your code), you can do the following to add your class:
<telerik:GridButtonColumn ConfirmText="Delete?" ConfirmDialogType="RadWindow" ConfirmTitle="Delete" ButtonType="ImageButton" CommandName="Delete" CssClass="uniqueclass" />
I added CssClass="uniqueclass" in the control above.
What I provided is just an example. I hope you find a use for it. Thanks
I have an ASP.NET WebForms Application and am encountering one of the oddest problems in my nine months of coding in ASP.NET.
I added two new pages that both use Telerik Radgrids. Both Radgrids are identical, so I will focus on one of them in the hopes that solving one of the problems will solve the other.
Html
<telerik:RadGrid ID="_radgrid" runat="server" Width="100%" Visible="true"
AutoGenerateColumns="false" OnSortCommand="_btnSearch_Click" PagerStyle-AlwaysVisible="true"
Skin="Office2007" AllowFilteringByColumn="true" AllowSorting="true" AllowPaging="true"
PageSize="50" OnNeedDataSource="_radgrid_NeedDataSource" OnItemDataBound="_radgrid_OnItemDataBound"
AllowMultiRowSelection="true">
<MasterTableView AllowFilteringByColumn="true" CommandItemDisplay="TopAndBottom">
<CommandItemTemplate>
<asp:Button ID="_btnResolve" runat="server" Text="Resolve" OnClick="_btnResolve_Click"
Visible="False" ClientIDMode="Inherit" />
</CommandItemTemplate>
<NoRecordsTemplate>
No records to display.</NoRecordsTemplate>
<Columns>
<telerik:GridBoundColumn DataField="Id" Visible="false" />
<telerik:GridBoundColumn DataField="Resolved" Visible="false" />
<telerik:GridClientSelectColumn UniqueName="CheckboxSelectColumn" FooterText="CheckBoxSelect footer"
Visible="false" />
<telerik:GridHyperLinkColumn DataNavigateUrlFields="Id" AllowFiltering="false"
DataNavigateUrlFormatString="~/UpdatePage.aspx?Id={0}"
Text="Update" UniqueName="UpdateHyperLink" />
<telerik:GridBoundColumn DataField="TradingPartnerName" HeaderText="Trading Partner Name" />
<telerik:GridBoundColumn DataField="DocumentType" HeaderText="Transaction Set" />
<telerik:GridBoundColumn DataField="DocumentID" HeaderText="Document ID" />
<telerik:GridBoundColumn DataField="Description" HeaderText="Description" />
</Columns>
</MasterTableView>
<ClientSettings>
<Selecting AllowRowSelect="true" />
<ClientEvents OnRowDblClick="RowDblClick" />
</ClientSettings>
</telerik:RadGrid>
Code Behind
protected void _radgrid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
Fill_radgrid();
}
private void Fill_radgrid(bool dataBind = false)
{
//Data Manager is a class that I built that makes all of the Database calls. It returns a DataSet
_grdNegativeAck.DataSource = DataManager.GetRecords(_txtBoxId.Text, txtBoxDocumentType.Text, _chkBoxIncludeResolved.Checked, int.Parse(_ddlTradingPartner.SelectedValue));
if (dataBind)
_grdNegativeAck.DataBind();
}
protected void _radgrid_OnItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
if (e.Item is GridCommandItem)
{
//If the current user is authorized to resolve, show the Resolve button on the grid
if (currentUser.IsAuthorized))
{
GridCommandItem cmditem = (GridCommandItem)e.Item;
Button _btnResolve = (Button)cmditem.FindControl("_btnResolve");
_btnResolve.Visible = true;
_grdNegativeAck.MasterTableView.GetColumn("CheckboxSelectColumn").Visible = true;
}
}
else if (e.Item is GridDataItem)
{
//If the record is already resolved, do not show the checkbox on the side and color the record green
GridDataItem GDItem = e.Item as GridDataItem;
if (GDItem["Resolved"].Text.ToUpper() == "TRUE")
{
((e.Item as GridDataItem)["CheckboxSelectColumn"].Controls[0] as CheckBox).Visible = false;
(e.Item as GridDataItem).BackColor = System.Drawing.Color.Green;
}
}
}
Here's where things get interesting. On my localhost, when using the same database, I get 0 records returned. I checked the DataSet that I'm binding to, and there is literally 0 rows. When I query the database, I get 185 records no problem. I double-checked the parameters I pass to the query, and they're the same. When I put this same code on the Test site, the page will get 184 records... when it should be matching exactly and get 185 records.
The other page doesn't get any records on either my localhost or my test site.
I'm really at my wit's end here. Anyone encounter a similar situation or have somewhere they can point me?
_grdNegativeAck.DataSource = DataManager.GetRecords(_txtBoxId.Text, txtBoxDocumentType.Text _chkBoxIncludeResolved.Checked, int.Parse(_ddlTradingPartner.SelectedValue));
In the above line, you are missing a comma(,) after txtBoxDocumentType.Text.
Hope this will resolve your problem.
I have a grid like below.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" s
onrowcommand="GridView1_RowCommand">
<Columns>
<asp:ButtonField DataTextField="Name" HeaderText="Name" />
<asp:BoundField DataField="ArrDate" DataFormatString="{0:MM/dd/yyyy}"
HeaderText="Arr Date" />
<asp:BoundField HeaderText="Dep Date" DataField="DepDate"
DataFormatString="{0:MM/dd/yyyy}" />
<asp:BoundField HeaderText="Mail" DataField="Mail" />
<asp:BoundField HeaderText="Status" DataField="Status" />
<asp:BoundField DataField="ResId" HeaderText="ResId" Visible="False" />
</Columns>
</asp:GridView>
In Code Behind:-
try
{
string text = GridView1.Rows[2].Cells[5].Text;
ScriptManager.RegisterStartupScript(this, GetType(), "Message", "alert('ResId = " + text + ".');", true);
}
catch { }
Now the message shows - RegId =.
I can't get the value. So I change the RedId BoundField as vissible. Now I got the Value.
that is RegId =6.
I have two issue now -
1) How to get the RegId value in Non Visible Column.
2) How I find the Row value which i click... bzs the only i can change the ROWVALUE in code..
string text = GridView1.Rows[ROWVALUE].Cells[5].Text;
That is certainly not the right way to do it. You might want to look at using DataKeys to achieve this. With current approach, when you add a new column to your grid your code will fail.
Add your RegId column inside DataKeys property on your gridview
Reference your gridview datakey for the current row in codebehind like this
int regId= Convert.ToInt32(YourGridview.DataKeys[rowIndex]["RegId"].ToString());