Conditional Display of Custom Button on DevExpress ASPxGridView in VB.NET - vb.net

I have an ASPxGridView control that needs a button that is visible on a conditional basis. I have searched and read several articles but have not found a fix for my particular situation. The button is called btnAllocatePlan and it should only be displayed if the value in a column called PayPlanFlg is true. Below is the markup for the grid and two things I tried in the codebehind, which is where I'd rather do this. Actually neither of these events even fired. Any help is greatly appreciated!
<dx:ASPxGridView ID="grdPayments" runat="server" CssClass="tblLined" SettingsPager-PageSize="50"
AutoGenerateColumns="False" KeyFieldName="PaymentKey" Width="100%">
<SettingsBehavior AllowFocusedRow="True" ProcessFocusedRowChangedOnServer="True" />
<Columns>
<dx:GridViewDataTextColumn Caption="CaseKey" FieldName="CaseKey" Visible="False" VisibleIndex="0">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Name" FieldName="Name" VisibleIndex="1" Width="10%">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Association" FieldName="AssociationName" VisibleIndex="2" Width="15%">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Address" FieldName="Address1" VisibleIndex="3" Width="15%">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Amount Paid" FieldName="Amount" VisibleIndex="4" Width="5%">
<PropertiesTextEdit DisplayFormatString="c"></PropertiesTextEdit>
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Payment Date" FieldName="TransactionTime" VisibleIndex="5" Width="12%">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Payment Type" FieldName="PaymentType" VisibleIndex="6" Width="3%">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Amount Owed" FieldName="Balance" VisibleIndex="7" Width="5%">
<PropertiesTextEdit DisplayFormatString="c">
</PropertiesTextEdit>
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Amount Available" FieldName="AmountAvailable" VisibleIndex="8" Width="6%">
<PropertiesTextEdit DisplayFormatString="c">
</PropertiesTextEdit>
</dx:GridViewDataTextColumn>
<dx:GridViewDataHyperLinkColumn Name="AllocationLink" VisibleIndex="9" Caption=" " UnboundType="String" Width="5%">
<DataItemTemplate>
<!--<%#"Allocate"%>-->
<dx:ASPxButton ID="btnAllocate" runat="server" Text="Allocate" OnClick="btnAllocate_Click" />
</DataItemTemplate>
</dx:GridViewDataHyperLinkColumn>
<dx:GridViewDataHyperLinkColumn Name="PlanLink" VisibleIndex="10" Caption=" " UnboundType="String" Width="5%">
<DataItemTemplate>
<!--<%#"Allocate"%>-->
<dx:ASPxButton ID="btnAllocatePlan" runat="server" Text="Pay Plan" OnClick="btnAllocatePlan_Click" />
</DataItemTemplate>
</dx:GridViewDataHyperLinkColumn>
<dx:GridViewDataTextColumn Caption="PayPlanFlg" FieldName="PayPlanFlg" Visible="false" VisibleIndex="11">
</dx:GridViewDataTextColumn>
</Columns>
</dx:ASPxGridView>
Codebehind attempts:
Protected Sub grdPayments_CustomButtonInitialize(sender As Object, e As ASPxGridViewCustomButtonEventArgs)
If e.Button.ID = "btnAllocatePlan" Then
If grdPayments.GetRowValues(e.VisibleIndex, 11, "PayPlanFlg") = 1 Then
e.Button.Visibility = GridViewCustomButtonVisibility.Invisible
End If
End If
End Sub
Protected Sub ASPxGridView1_HtmlDataCellPrepared(sender As Object, e As ASPxGridViewTableDataCellEventArgs)
If e.DataColumn.FieldName = "ID" Then
Dim textBox As ASPxButton = TryCast(ASPxGridView1.FindRowCellTemplateControl(e.VisibleIndex, e.DataColumn, "btn"), ASPxButton)
If Convert.ToString(e.GetValue("ItemName")).Equals("B") Then
textBox.Text = Convert.ToString(e.CellValue)
textBox.Visible = True
Else
textBox.Visible = False
End If
End If
End Sub

The best approach is to handle the Button's Init/Load event. This
recommended technique is described in the The general technique of
using the Init/Load event handler KB article.
Check below example code for hiding a particular button in a row..
aspx
<dx:GridViewDataHyperLinkColumn Name="AllocationLink" VisibleIndex="9" Caption=" " UnboundType="String" Width="5%">
<DataItemTemplate>
<!--<%#"Allocate"%>-->
<dx:ASPxButton ID="btnAllocate" runat="server" Text="Allocate" OnInit="btnAllocate_Init" />
</DataItemTemplate>
</dx:GridViewDataHyperLinkColumn>
.cs
protected void btnAllocate_Init(object sender, EventArgs e)
{
DevExpress.Web.ASPxButton btn = (DevExpress.Web.ASPxButton)sender;
GridViewDataItemTemplateContainer container = btn.NamingContainer as GridViewDataItemTemplateContainer;
// You can remove the if statement, and try to insert a new record. You'll catch an exception, because the DataBinder returns null reference
if (container != null && !container.Grid.IsNewRowEditing)
btn.Visible = !(bool)DataBinder.Eval(container.DataItem, "PayPlanFlg");
}
Reference:
ASPxGridView - Hide the control in the DataItemTemplate conditionally

Related

How to replace IDs of users with their fullNames in the current scenario?

I have two databases with the following schema:
tbl_users(userID, fullName, emailID, password)
userID is the Primary Key
tbl_savings(savingsID, creditorName, amount, interestRate, interestType, interestCalculationMethod, ownerID, dataEnteredByID)
savingsID is the Primary Key.
ownerID is a Foreign Key on userID of tbl_users with a one-to-many relationship.
ownerID specifies the ID of the owner of the saving. Similarly, dataEnteredByID specifies the ID of the person who entered the data.
I have a GridView with the following specification:
<asp:GridView ID="GridViewSavingsTracker" AutoGenerateColumns="false" runat="server" DataKeyNames="savingsID" OnRowCommand="GridViewSavingsTracker_RowCommand" AllowPaging="true" OnSelectedIndexChanged="GridViewSavingsTracker_SelectedIndexChanged" OnPageIndexChanging="GridViewSavingsTracker_PageIndexChanging" PageSize="10">
<Columns>
<asp:CommandField ShowSelectButton="true" />
<asp:BoundField DataField="creditorName" HeaderText="Creditor Name" />
<asp:BoundField DataField="amount" HeaderText="Principal Amount" />
<asp:BoundField DataField="interestRate" HeaderText="Interest Rate" />
<asp:BoundField DataField="interestType" HeaderText="Interest Type" />
<asp:BoundField DataField="interestCalculationMethod" HeaderText="Interest Calculation Method" />
<asp:BoundField DataField="insertedDate" HeaderText="Date" />
<asp:BoundField DataField="ownerID" HeaderText="Owner" />
<asp:BoundField DataField="dataEnteredByID" HeaderText="Data Entered By" />
</Columns>
</asp:GridView>
What I want to do: Instead of printing the ownerID and dataEnteredByID, I want to print the fullNames of the corresponding IDs. How can I do that?
What I already have: I have the following server side code for GridView. I have a method ShowGridView() that populates the data into the GridView from the database(s).
protected void ShowGridView()
{
string connectionString = GetConnString();
OleDbConnection con = new OleDbConnection(connectionString);
con.Open();
string showGridViewQuery = "(SELECT s.creditorName, s.amount, s.interestRate, s.interestType, s.interestCalculationMethod, s.insertedDate, u.fullName FROM tbl_savings s LEFT JOIN tbl_users u ON s.ownerID = u.usersID) UNION (select s.creditorName, s.amount, s.interestRate, s.interestType, s.interestCalculationMethod, s.insertedDate, u.fullName from tbl_savings s LEFT JOIN tbl_users u ON s.dataEnteredByID = u.usersID)";
OleDbCommand showGridViewCommand = new OleDbCommand(showGridViewQuery, con);
showGridViewCommand.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter olda = new OleDbDataAdapter(showGridViewCommand);
olda.Fill(dt);
GridViewSavingsTracker.DataSource = dt;
GridViewSavingsTracker.DataBind();
con.Close();
}
You can create a separate code-behind method that gets the full name and call it from the gridview.
Create an ItemTemplate for the field. The Text property calls the method. Replace UserID with your field's name.
<ItemTemplate>
<asp:Label ID="lblUserNameItem" runat="server"
Text='<%# GetUserNameByID(Eval("UserID").ToString()) %>'></asp:Label>
</ItemTemplate>
Code behind:
protected string GetUserNameByID(string userID)
{
// your data-code...
... uname = GetUserByID(int.Parse(userID));
return uname;
}
Do the same with the other id, with the same method or another.

Display ContactName from Guid in Gridview using SQLDataSource / Asp.Net

I have set the following code up to display player1 v player2 in a Gridview. However, It currently displays tblFixtures.player1 v tblFixtures.player2 which are UniqueIdentifiers, I need it to display their corresponding contact names instead. tblaccounts has columns accountID(uniqueidentifier) and contactName(varchar) but not sure how to join this in such a way that I can display them in the Gridview below.
<asp:SqlDataSource ID="DSFixtures" runat="server" ConnectionString="
<%$ ConnectionStrings:DBConnectionString %>" SelectCommand="SELECT
tblFixtures.player1, tblFixtures.player2, tblFixtures.compID,
tblFixtures.round
FROM tblFixtures INNER JOIN tblCompetitions ON tblFixtures.compID =
tblCompetitions.compID WHERE tblFixtures.compID = #Event_ID and round =
#Round ">
<SelectParameters>
<asp:QueryStringParameter QueryStringField="compID" Name="Event_ID" />
<asp:QueryStringParameter QueryStringField="round" Name="Round" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Gridview ID="gdvFixtures" visible="false" width="100%"
runat="server" AllowPaging="True" AutoGenerateColumns="False"
CssClass="mGrid" DataKeyNames="compID" DataSourceID="DSFixtures"
PageSize="20" AllowSorting="True">
<AlternatingRowStyle CssClass="alt" />
<Columns>
<asp:BoundField DataField="player1" HeaderText="player1" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
V
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="player2" HeaderText="player2" />
</Columns>
</asp:GridView>
You can do a nested select
SELECT tblFixtures.player1, (SELECT name FROM tblaccounts WHERE
(accountID = tblFixtures.player1)) AS player1_name, ...
Or create another 2 joins, one for each player. You can do that by renaming the tables with AS so you can join the same table multiple times.
INNER JOIN tblaccounts AS acc1 ON acc1.accountID = tblFixtures.player1 INNER JOIN
tblaccounts AS acc2 ON acc1.accountID = tblFixtures.player2
UPDATE
Your entire query should look like this. And player1_name and player2_name become the column names you can use in a GridView.
SELECT
tblFixtures.player1,
(SELECT name FROM tblaccounts WHERE (accountID = tblFixtures.player1)) AS player1_name,
tblFixtures.player2,
(SELECT name FROM tblaccounts WHERE (accountID = tblFixtures.player2)) AS player2_name,
tblFixtures.compID,
tblFixtures.round
FROM tblFixtures INNER JOIN tblCompetitions ON tblFixtures.compID =
tblCompetitions.compID WHERE tblFixtures.compID = #Event_ID and round =
#Round

How to change a Radgrid column value after binding?

I have a Radgrid and I bind it with SqlAdapter. My problem is that I want to change just one column's value. Is that possible?
My column name is IsShadow and it binds true or false. I cannot change it. If value is false or true, I change column text appearence, not database update.
Code I've tried
foreach (Telerik.Web.UI.GridDataItem dataItem in gridShadow.MasterTableView.Items)
{
bool flag = Convert.ToBoolean(dataItem.GetDataKeyValue("IsShadow"));
GridEditableItem editedItem = dataItem as GridEditableItem;
if (!flag)
{
TableCell tableCell = editedItem["IsShadow"] = ???
}
}
Thank you.
Please try with the below code snippet and let me know if any concern.
// Normal Mode
if (e.Item is GridDataItem)
{
GridDataItem item = (GridDataItem)e.Item;
item["IsShadow"].Text = "Your new text";
}
// Edit Mode
if ((e.Item is GridEditableItem) && (e.Item.IsInEditMode))
{
GridEditableItem editItem = (GridEditableItem)e.Item;
(editItem["IsShadow"].Controls[0] as TextBox).Text = "Your new text";
}
You probably need a GridTemplateColumn
In the ItemTemplate you will check the value of IsShadow and display some text, but in EditItemTemplate you would probably need to just have a checkbox for true/false.
<telerik:GridTemplateColumn HeaderText="Is Shadow" UniqueName="TemplateColumn">
<EditItemTemplate>
<asp:CheckBox id="editChkBox" runat="server"
Checked='<%# Bind("IsShadow") %>'>
</asp:CheckBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Lable id="lblIsShadow" runat="server"
Text='<%# Convert.ToBoolean(Eval("IsShadow")) == true ? "it is shadow" : "Not shadow" %>'>
</asp:CheckBox>
</ItemTemplate>
</telerik:GridTemplateColumn>

Getting sum of an unbound data column in asp.net Gridview

I am trying to get the sum of an unbound data column. Basically I have a gridview with dropdown list and an Amount column. I select quantity from that list and the price is multiplied with the quantity and the amount is shown in the "Amount" column. The Price is fetched from the database and itemID also. Now I want to sum up all the values in the "Amount" column. As I run this code, every row is updated successfully with the quantity and price multiplication but the total amount logic is adding the item_price + any value in the "amount" column. I only want the data to be added in the "Amount" column. I have a label in the bottom of the grid view where I am trying to get the total result value. HELP!!
The aspx file is like this:
<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server"
OnRowDataBound="GridView1_RowDataBound" ShowFooter="true">
<footerstyle backcolor="LightCyan"
forecolor="MediumBlue"/>
<Columns>
<asp:BoundField DataField="item_ID" HeaderText="ID" />
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:DropDownList ID="ddlQuantity" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlQuantity_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="purchase_price">
<ItemTemplate>
<asp:Label ID="lblPrice" Text='<%#Eval("purchase_price") %>' runat="server" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:Label ID="lblAmount" Text="0.00" runat="server" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Here is the code behind:
protected void ddlQuantity_SelectedIndexChanged(object sender, EventArgs e)
{
int quantity;
GridViewRow gvr = ((DropDownList)sender).NamingContainer as GridViewRow;
var ddlQuantity = gvr.FindControl("ddlQuantity") as DropDownList;
var lblAmount = gvr.FindControl("lblAmount") as Label;
var lblPrice = gvr.FindControl("lblPrice") as Label;
int.TryParse(ddlQuantity.SelectedValue, out quantity);
//Label1.Text = quantity.ToString();
int pr = int.Parse(lblPrice.Text);
int qt = int.Parse(ddlQuantity.SelectedValue);
//Label2.Text += (pr*qt).ToString();
lblAmount.Text = (pr * qt).ToString();
int sum = 0;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
sum += int.Parse(lblAmount.Text);
}
Label2.Text = sum.ToString();
}
You were pretty close. In your sum loop, you are only adding the same amount each time. Within that loop, you need to look up each lblAmount (for that row) and sum each one.
Try this code for your loop:
int sum = 0;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
gvr = GridView1.Rows[i] as GridViewRow;
var lblRowAmount = gvr.FindControl("lblAmount") as Label;
sum += int.Parse(lblRowAmount.Text);
}
Label2.Text = sum.ToString();

RadGrid value from row on doblue click

I have a radgrid populated with data in double click I launch a rad window manager with texbox that need to fill with the data selected on the radgrid. I fail to get the value of the row. I can only get the index of the selected item.
this is my grid aspx:
<telerik:RadGrid ID="rgBuscar" runat="server" CellSpacing="0" Culture="es-ES"
GridLines="None" Height="469px" Skin="Hay" Width="944px">
<ClientSettings>
<Scrolling AllowScroll="True" UseStaticHeaders="True" />
</ClientSettings>
<MasterTableView>
<CommandItemSettings ExportToPdfText="Export to PDF"></CommandItemSettings>
<RowIndicatorColumn Visible="True" FilterControlAltText="Filter RowIndicator column">
<HeaderStyle Width="20px"></HeaderStyle>
</RowIndicatorColumn>
<ExpandCollapseColumn Visible="True" FilterControlAltText="Filter ExpandColumn column">
<HeaderStyle Width="20px"></HeaderStyle>
</ExpandCollapseColumn>
<EditFormSettings>
<EditColumn FilterControlAltText="Filter EditCommandColumn column"></EditColumn>
</EditFormSettings>
<PagerStyle PageSizeControlType="RadComboBox"></PagerStyle>
</MasterTableView>
<ClientSettings>
<Selecting AllowRowSelect="True" />
<ClientEvents OnRowDblClick="RowDblClick"/>
</ClientSettings>
<PagerStyle PageSizeControlType="RadComboBox"></PagerStyle>
<FilterMenu EnableImageSprites="False"></FilterMenu>
and my JS:
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
<script type="text/javascript">
function RowDblClick(sender, args) {
var index = args.get_itemIndexHierarchical();
sender.get_masterTableView().fireCommand("RowDblClick", index);
}
</script>
and finally my VB:
Protected Sub rgBuscar_ItemCommand(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles rgBuscar.ItemCommand
If e.CommandName = "RowDblClick" Then
Dim var As String = e.CommandArgument
idValor = e.Item.Cells(2).Text
MostrarVentana(idValor)
End If
End Sub
Public Sub MostrarVentana(ByVal IdCampo As Integer)
lector = objBd.obtenerConfiguraciones("Cambio Ordenes")
While lector.Read
rwmCambio.Windows(0).NavigateUrl = lector("OCON_Url") & "?IdCampo=" & IdCampo
rwmCambio.Windows(0).Width = Unit.Pixel(lector("OCON_Width"))
rwmCambio.Windows(0).Height = Unit.Pixel(lector("OCON_Height"))
End While
rwmCambio.Windows(0).VisibleOnPageLoad = True
End Sub
Telerik provides a rich API for the RadGrid, by assigning a value to the DataKeyValues (or ClientDataKeyNamesif you want to access them using the Client API rather than posting back) attributes of the MasterTableView you can access the data related to the item through the code; to add multiple columns to the data key collection, separate the column names with a comma.
Example Data Key Definitions:
<MasterTableView DataKeyNames="idColumnName,foreignKeyColumnName" ClientDataKeyNames="idColumnName,anotherColumnName">
Example OnRowSelected event client-side (JavaScript) event handler:
function OnGridRowSelected(sender, args) {
var idDataKey = args.getDataKeyValue("idColumnName");
var nameDataKey = args.getDataKeyValue("idColumnName");
document.getElementById("myElement").value = "(" + idDataKey + ") " + nameDataKey;
}
Example ItemCommand event server-side (VB) event Handler:
Protected Sub PerformActionOnGridItem(sender As Object, e As Telerik.Web.UI.GridCommandEventArgs) Handles grdCustomerAccountInvoiceSummary.ItemCommand
If (TypeOf (e.Item) Is Telerik.Web.UI.GridDataItem) Then
Dim item As Telerik.Web.UI.GridDataItem = CType(e.Item, Telerik.Web.UI.GridDataItem)
Select Case e.CommandName
Case "RowDblClick"
' Insert required code here
...
' Example: Set session variable to data key value
Session("idColumnName") = item.GetDataKeyValue("idColumnName")
End Select
End If
End Sub