how String.Format of RadGrid(Telerik) Sum result in footer? - telerik

my radgrid column like below :
<telerik:GridTemplateColumn FilterControlAltText="Filter TemplateColumn_Benefit" DataField="Benefit"
HeaderText="Benefit" UniqueName="TemplateColumn_Benefit" FilterImageToolTip="Filter">
<ItemTemplate>
<asp:Label ID="lblBenefitInsideGrd" runat="server" Font-Size="11px" Text='<%# (bool)Convert.IsDBNull(Eval("Benefit")) ? "<span class=\"lblInsideGrd\">Empty</span>" : String.Format("{0:#,0 Dollar;#,0- Dollar}", Eval("Benefit")) %>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="60px" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="60px" />
</telerik:GridTemplateColumn>
how can i String.Format(reformat) Sum result in footer for this template column ?
mean i want something like {0:#,0 Dollar;#,0- Dollar} in output...
thanks in advance

the below link solved my problem :
http://demos.telerik.com/aspnet-ajax/grid/examples/generalfeatures/aggregates/defaultcs.aspx
/// <summary>
/// The MasterTableView.DataBinding event is used to preserve the applied formatting to
/// data values in the column aggregate and still be able to add the name of the currently
/// selected aggregate function.
/// </summary>
protected void MasterTableView_DataBinding(object sender, EventArgs e)
{
GridNumericColumn unitPriceCol = RadGrid1.MasterTableView.GetColumnSafe("UnitPrice") as GridNumericColumn;
unitPriceCol.FooterAggregateFormatString = unitPriceCol.Aggregate.ToString() + ": {0:C}";
}

You can add an additional Format argument to the Eval function:
Eval("Benefit", "{0:#,0 Dollar;#,0- Dollar}")

Related

How Can I get Cell Values from Telerik RadGrid

I am having a problem getting the values from the Radgrid auto generated Insert form.
I have my radgrid setup as shown in code shown below. I am only doing inserts and deletes and am using the edit form that is automatically opened when I click the add new record button.
<div id ="specialrequestGrid" class="container">
<div class="row">
<div class="col-md-12">
<telerik:RadAjaxPanel runat="server">
<telerik:RadGrid ID="SpecialRequests" runat="server" OnInsertCommand="SpecialRequests_InsertCommand"
OnUpdateCommand="SpecialRequests_UpdateCommand"
OnItemCommand="SpecialRequests_ItemCommand"
AllowAutomaticInserts="false"
AutoGenerateColumns="false"
OnNeedDataSource="SpecialRequests_NeedDataSource">
<MasterTableView CommandItemDisplay="Top" DataKeyNames="CaseId_FK, ReqId" Font-Size="Medium" NoMasterRecordsText="No Special Requests">
<CommandItemSettings AddNewRecordImageUrl="../Images/Add.png" />
<Columns>
<telerik:GridTemplateColumn HeaderText="Request Date" UniqueName="DateTemplateColumn">
<ItemTemplate>
<asp:Label ID="DateEditItemTemplate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Date","{0:MM/dd/yyyy}") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadDatePicker ID="dpRideDate" runat="server" DateInput-DateFormat="MM/dd/yyyy" DbSelectedDate='<%# Bind("Date") %>' MinDate="1999/1/1" UniqueName="dpRideDate">
</telerik:RadDatePicker>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn HeaderText="Requested By ID" UniqueName="RequestorTemplateColumn">
<ItemTemplate>
<asp:Label ID="Requestor" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "RequesterEID_FK") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<button id="btnRequestEID" type="button" class="btn" data-toggle="modal" data-target="#myModal" >--Please Select--</button>
<div>
<input type="text" Id="TxtSPRequestName" disabled />
</div>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn HeaderText="Request Reason" UniqueName="RequestReason">
<ItemTemplate>
<asp:Label ID="ItemTemplatelblRequestReason" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Reason") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblRequestReason" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Reason") %>' Visible="false">
</asp:Label>
<asp:TextBox runat="server" ID="txtReason" Text='<%# DataBinder.Eval(Container.DataItem, "Reason") %>'></asp:TextBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridCheckBoxColumn DataField="IsWOO" HeaderText="Is Out of Order" UniqueName="ISWOO"></telerik:GridCheckBoxColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
</telerik:RadAjaxPanel>
</div>
</div>
</div>
This is the screenshot of the auto generated form I get when I click the add new record
When I click the Insert link on the form I run this C# code
protected void SpecialRequests_InsertCommand(object sender, GridCommandEventArgs e)
{
GridEditableItem editedItem = e.Item as GridEditableItem;
UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
T_SpecialRequests t = new T_SpecialRequests();
t.IsWOO = (userControl.FindControl("IsWOO") as CheckBox).Checked;
}
Note the IsWOO is a control in the Radgrid that I did not show in the Screenshot. When I click the save link the Insert Function, shown above Runs but I get the following error:
Unhandled exception at line 1, column 123034 in http://localhost:52028/bundles/MsAjaxJs?v=c42ygB2U07n37m_Sfa8ZbLGVu4Rr2gsBo7MvUEnJeZ81
0x800a139e - JavaScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: Object reference not set to an instance of an object.
The strange part is I use this same code in several other projects without any problems. The only difference is this is the first time I have used this auto generated form. I don't want to use the another type of control for this Radgrid due to such a small number of fields, only have 4 control.
I have spent several hours searching for an answer but just can't find the solution.
How can I get the values from this auto generated form?
You can use
t.IsWOO = (editedItem["ISWOO"].Controls[0] as CheckBox).Checked;
or
var newValues = new Dictionary<string, object>();
e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
t.IsWOO = (bool)newValues["IsWOO"];
The first approach references the control by index because unfortunately it has no ID.
The second one is a bit verbose for just one property but I would surely prefer it if there were more properties.
While #Michal Nawrocik was correct I found that I still had some problems reading all of the controls in the Radgrid. I was able to track down the answer on the Telerik forum and found that you have to use different code based on the Column Type. I had 2 different type of columns.
the code below shows what I used to get all of the control values on the form
protected void SpecialRequests_InsertCommand(object sender, GridCommandEventArgs e)
{
try
{
using(LatentEntities db = new LatentEntities())
{
if (e.Item is GridEditableItem)
{
T_SpecialRequests T = new T_SpecialRequests();
var editableItem = ((GridEditableItem)e.Item);
RadDatePicker picker = (RadDatePicker)editableItem.FindControl("dpDate"); // in EditItem Template
DateTime dt = Convert.ToDateTime(picker.DbSelectedDate);
T.Date = dt;
TextBox Reason = (TextBox)editableItem.FindControl("txtReason"); //This Control was in an Edit Item Template
T.Reason = Reason.Text;
T.IsWOO = (editableItem["ISWOO"].Controls[0] as CheckBox).Checked; //In CheckBox Column
}
}
And if the control is in a Telerik:GridtboundColumn I used this code:
string strFirstName = (editableItem["firstname"].Controls[0] as TextBox).Text;

Telerik : Get Column name from FilterTemplate controls Client Event

I am trying to add RadCombobox to a telerik:GridTemplateColumn as a FilterTemplate control. I have multiple columns and all have RadCombobox with same filter values.
<telerik:GridTemplateColumn AutoPostBackOnFilter="true" HeaderStyle-Width="90px"
UniqueName="Date1" HeaderText="Date1" DataField="Day1">
<FilterTemplate>
<telerik:RadComboBox ID="RadComboBoxDate1" Height="90px" AppendDataBoundItems="true"
Width="105px" runat="server" OnClientSelectedIndexChanged="Date1IndexChanged">
</telerik:RadComboBox>
<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
<script type="text/javascript">
function Date1IndexChanged(sender, args) {
var tableView = $find("<%# TryCast(Container,GridItem).OwnerTableView.ClientID %>");
var selectedValue = sender.get_value();
if (selectedValue) {
if (parseInt(selectedValue) < 0) {
tableView.filter("Date1", selectedValue, "NoFilter");
}
else { tableView.filter("Date1", selectedValue, "EqualTo");
}
}
}
</script>
</telerik:RadScriptBlock>
</FilterTemplate>
<ItemTemplate>
<asp:Label runat="server" ID="lblday1"></asp:Label>
<asp:HiddenField ID="hdDay1" runat="server" Value='<%# DataBinder.Eval(Container.DataItem,"Day1") %>' Visible="false" />
</ItemTemplate>
</telerik:GridTemplateColumn>
I have 7 such columns and I want to use a single RadCodeBlock to handle the filter. Is there any better way to do this?
Solution given on Telerik website worked for me
http://www.telerik.com/forums/how-to-get-column-name-from-filter-template-control-s-js-event

Telerik rad grid combo box event

I m using telerik rad grid
I have used combo box to display company Type.
If company Type is ABC than Design Firm type should not be displayed
how to write code on combobox in telerik radgrid ![enter image description here][1]
You will need to take two steps to make this work. First, set up an EditForm Template in your RadGrid. Next, you'll need to use related RadComboBoxes (as shown in this example) to achieve your desired functionality.
EditForm Template example code
<telerik:GridTemplateColumn UniqueName="ContactTitle" HeaderText="ContactTitle">
<EditItemTemplate>
<telerik:RadComboBox ID="RadComboBox1" AutoPostBack="true" runat="server" SelectedValue='<%# Bind("CountryID") %>' DataSourceID="SqlDataSource1" DataTextField="CountryID" OnSelectedIndexChanged="RadComboBox1_SelectedIndexChanged">
</telerik:RadComboBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn UniqueName="TemplateColumn">
<EditItemTemplate>
<telerik:RadComboBox ID="RadComboBox2" runat="server">
</telerik:RadComboBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
Cascading ComboBox example
protected void RadComboBox1_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
{
RadComboBox rdcbx = (RadComboBox)o;
GridEditableItem editedItem = rdcbx.NamingContainer as GridEditableItem;
RadComboBox ddList = editedItem.FindControl("RadComboBox2") as RadComboBox;
// change the data source for ddList here
.....
}
source

Ajax Tab error Specified argument was out of the range of valid values. Parameter name: value

I am trying to create ajax tabs dynamically and storing their ID's in a session. I am getting an error "Specified argument was out of the range of valid values.
Parameter name: value". I am able to create the first tab by invoking the click button event. When I click the button and invoke the same event on the second try...I get the error. Seems like I am referencing a tab ID or container\tab that is no longer defined or contained in session?
I have researched this thoroughly and can't seem to find the answer. Any help would be greatly appreciated.
I have the correct scriptmanager and assembly references on my asp page. Here is the asp code and the code behind snippet.
<div>
<asp:Button ID ="AddTab" Text="Add Tab" OnClick = "addTab_Click" runat="server"/>
<AjaxToolkit:TabContainer ID="TabContainerContent" runat="server" Height="150px" BackColor="White" AutoPostBack="True"
OnActiveTabChanged="TabContainerContent_OnActiveTabChanged" >
</AjaxToolkit:TabContainer>
<asp:Label ID="currentTabIndex" runat="server"></asp:Label>
</div>
</td>
Code Behind
private List<string> dynamicTabIDs;
protected void Page_Init(Object sender, EventArgs e)
{
if (Session["dynamicTabIDs"] != null)
{
dynamicTabIDs = (List<string>)Session["dynamicTabIDs"];
foreach (string tabID in dynamicTabIDs)
{
AjaxControlToolkit.TabPanel tab = new AjaxControlToolkit.TabPanel();
tab.ID = tabID;
tab.HeaderText = "Tab " + (TabContainerContent.Tabs.Count + 1).ToString();
Label tabContent = new Label();
tabContent.ID = "lbl_tab_" + TabContainerContent.Tabs.Count.ToString();
tabContent.Text = "Tab " + (TabContainerContent.Tabs.Count + 1).ToString();
tab.Controls.Add(tabContent);
TabContainerContent.Tabs.Add(tab);
}
}//end if
else
{
dynamicTabIDs = new List<string>();
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
Session["dynamicTabIDs"] = dynamicTabIDs;
}
protected void TabContainerContent_OnActiveTabChanged(object sender, EventArgs e)
{
currentTabIndex.Text = TabContainerContent.ActiveTab.ID;
}
public void addTab_Click(object sender, EventArgs e)
{
AjaxControlToolkit.TabPanel tab = new AjaxControlToolkit.TabPanel();
tab.ID = "tab" + Convert.ToString(TabContainerContent.Tabs.Count);
tab.HeaderText = "Tab " + (TabContainerContent.Tabs.Count + 1).ToString();
Label tabContent = new Label();
tabContent.ID = "lbl_tab_" + TabContainerContent.Tabs.Count.ToString();
tabContent.Text = "Tab " + (TabContainerContent.Tabs.Count + 1).ToString();
tab.Controls.Add(tabContent);
TabContainerContent.Tabs.Add(tab);
TabContainerContent.ActiveTab = tab;
dynamicTabIDs.Add(tab.ID);
}
I tried a different approach to accomplsih this. I created static tabs and just set them to visible true/false depending if they are used or not. I couldn't get dynamic tabs to work. I did have to restrict the number of customer numbers to 15 orders with this approach.
I found that it was very easy to bind data to a gridview within Ajax tabs. Of course you needed you script manager ajax reference declared in the asp page and ajax reference update to web.config file. You also need to add the ajax css style to an existing style sheet. i tried using a seperate one and it didn't work.
ASP HTML
<AjaxToolkit:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="0"
Visible="false" ScrollBars="Both"
CssClass="Tab2" Width="1326px" Height="464px" >
<AjaxToolkit:TabPanel ID="TabPanel1" runat="server" HeaderText="Empty" Enabled="true" ScrollBars="Both" CssClass="Tab2">
<ContentTemplate>
<div style="overflow:auto;width:1287px; height: 418px;">
<font color="white" size="1" face="Verdana">
<asp:GridView ID="SalesOrderView1" runat="server" BackColor="White" BorderColor="#DEDFDE"visible="False"BorderStyle="None" BorderWidth="1px"
CellPadding="4" ForeColor="Black"
GridLines="Vertical" HorizontalAlign="Center">
<AlternatingRowStyle BackColor="White" />
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
</div>
</font>
</ContentTemplate>
</AjaxToolkit:TabPanel>
<AjaxToolkit:TabPanel ID="TabPanel2" runat="server" HeaderText="Empty" ScrollBars="Both" CssClass="Tab2">
<ContentTemplate >
</AjaxToolkit:TabContainer>
C# Code to bind data to the gridview on click button event.
SalesOrderView1.Visible = true;
TabPanel1.Visible = true;
TabPanel1.HeaderText = Order_List[multi_order_count];

Unable to sort a GridView populated by DataView in ASP.NET 2.0 using C#

I am working on extending an ASP.NET 2.0 application using an InterBase database. My experience is in PHP/MySQL, so my familiarity with ASP is currently in the 2-week range, and is pieced together from examining a co-worker's code, the first 90 pages of my ASP book, and Google. In the application, I have an SqlDataSource control connecting to my database and selecting the information I need. Then the results are copied into a DataView where I modify the data in one of the columns, and then I push that DataView to a GridView for output. The issue I'm having is that I cannot sort the GridView at this point. I followed instructions here: http://forums.asp.net/p/956540/1177923.aspx, but to no avail.
Here is the page code:
<form id="form1" runat="server">
<div>
<asp:SqlDataSource ID="Products" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>"
ProviderName="<%$ ConnectionStrings:ConnectionString1.ProviderName %>" OnLoad="ProductsDS_Load"
OnSelected="ProductsDS_Selected" DataSourceMode="DataSet">
</asp:SqlDataSource>
<br />
<asp:Label ID="testlabel" runat="server"></asp:Label>
<br />
<asp:Label ID="testlabel2" runat="server"></asp:Label>
<br /><br />
This table lists all 2000+ numbered projects which are at least partially in process.<br />
The Project number link leads to a more detailed view of that project.<br />
<br />
<asp:Label runat="server" ID="numrows"></asp:Label> results returned.
<br />
<asp:GridView ID="ProductsView" runat="server" EnableModelValidation="True"
AutoGenerateColumns="False" CellPadding="4" OnSorting="ProductsView_Sorting"
ForeColor="#333333" GridLines="None" AllowSorting="True">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:HyperLinkField HeaderText="Project" SortExpression="PROJECT"
DataTextField="PROJECT" Target="subweeklyreport" DataNavigateUrlFields="PROJECT"
DataNavigateUrlFormatString="Products.aspx?p={0}" />
<asp:BoundField Visible="false" DataField="PROJECTID" />
<asp:BoundField DataField="PART" HeaderText="Part #"
SortExpression="PART" />
<asp:BoundField DataField="DESCRIPTION" HeaderText="Description"
SortExpression="DESCRIPTION" />
<asp:BoundField DataField="ENGMGR" HeaderText="Eng. Mgr."
SortExpression="ENGMGR" />
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
</asp:GridView>
</div>
</form>
And here is the code behind:
protected void ProductsDS_Load(object sender, EventArgs e)
{
string SQLQuery = Query would go here;
testlabel2.Text = SQLQuery;
Products.SelectCommand = SQLQuery;
Products.DataBind();
DataView dv = (DataView)Products.Select(new DataSourceSelectArguments());
foreach (DataRow dr in dv.Table.Rows)
{
string name = dr["ENGMGR"].ToString();
string[] explode = name.Split(' ');
string newname;
if (explode.Length == 3)
{
newname = explode[2] + ", " + explode[0];
}
else
{
newname = explode[1] + ", " + explode[0];
}
dr["ENGMGR"] = newname;
//testlabel.Text = dr["ENGMGR"].ToString();
}
Products.DataBind();
//ProductsView.DataSourceID = "Products";
ProductsView.DataSource = dv;
ProductsView.DataBind();
ProductsView.Enabled = true;
ProductsView.Visible = true;
}
protected void ProductsDS_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
numrows.Text = e.AffectedRows.ToString();
}
protected void ProductsView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = ProductsView.DataSource as DataTable;
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
ProductsView.DataSource = dataView;
ProductsView.DataBind();
}
}
private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
What I think is happening is that whenever the GridView does the postback for the sort, it causes the query to be executed again and overwrite the attempt to sort the existing data in the GridView, but I don't know enough about ASP right now to prevent this behavior. Any help would be much appreciated.
I ended up solving my own problem. I created a session variable to store the dataview between page loads, and checking to see if the dataview is stored before executing the query, and sorting it if it is, and just performing the regular query otherwise. Since I don't expect data to be introduced between the initial page view and the sort, I don't think using a stored copy of the data would be a major issue.

Resources