How to change a Radgrid column value after binding? - sql

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>

Related

Quasar q-tabs: how to dynamically show/hide q-tab by code?

There is a dropdownlist, if user choose a option, some q-tab-panel will show/hide to make a response. But how can I dynamically set the q-tab-panel show/hide by code? Hope someone can make suggestions here. Thanks
<q-select filled
v-model="datasource.datasourcetype"
:options="datasource.options"
option-value="value"
option-label="label"
emit-value
map-options
:label="ui.datasourcetype" />
<q-tabs v-model="dataEntryTab"
dense
class="bg-grey-2 text-teal"
align="left">
<q-tab name="tabCustomized" v-if="dataentry.showOptionsTab" icon="mail" :label="ui.datasourceOptions" />
<q-tab name="tabEntryInfo" v-if="dataentry.showDataEntryTab" icon="alarm" :label="ui.datasourceEntryInfo" />
<q-tab name="tabCascadeField" v-if="dataentry.showCascadeFieldTab" icon="movie" :label="ui.datasourceCascadeField" />
</q-tabs>
<q-tab-panels v-model="dataEntryTab" animated>
<q-tab-panel name="tabCustomized">
<q-input :label="ui.dataentryOptions"
v-model="dataentry.options"
filled
type="textarea" />
</q-tab-panel>
<q-tab-panel name="tabEntryInfo">
</q-tab-panel>
<q-tab-panel name="tabCascadeField">
</q-tab-panel>
</q-tab-panels>
For example, there are 3 q-tabs, if the user only want to let 2 of them to show, and 1 of them to hide after a dropdown option selected.
There is an event #input about q-select, and we can trigger a model variable for every q-tab. It works for me
onDataSourceTypeChanged (event) {
var dstype = this.datasource.datasourcetype
if (dstype === 'datasourcetype.Customized') {
this.dataentry.showOptionsTab = true
this.dataentry.showDataEntryTab = false
this.dataentry.showCasacdeFieldTab = false
} else {
this.dataentry.showOptionsTab = false
this.dataentry.showDataEntryTab = true
this.dataentry.showCasacdeFieldTab = true
}
}

Hyperlink Control: Index was outside the bounds of the array

I have a SQL column with the name of "documents" that hold all the uploaded documents name like this: test1.doc;test2.pdf;test3.pdf. Some records for this column has no data or only has one or two documents. In my FormView I have 3 hyperlinks like this:
**//Hyperlink # 1**
<asp:HyperLink ID="HyperLink1" runat="server" Text='<%# If(Eval("documents") Is DBNull.Value, "No
document available", Eval("documents").ToString().Split(";")(0)) %>' NavigateUrl='<%#
String.Format("~/documents/uploads/{0}", Eval("documents").ToString().Split(";")(0)) %>' >
</asp:HyperLink><br />
**//Hyperlink # 2**
<asp:HyperLink ID="HyperLink2" runat="server" Text='<%# If(Eval("documents") Is DBNull.Value, "No
document available", Eval("documents").ToString().Split(";")(1)) %>' NavigateUrl='<%#
String.Format("~/documents/uploads/{0}", Eval("documents").ToString().Split(";")(1)) %>' >
</asp:HyperLink><br />
**//Hyperlink # 3**
<asp:HyperLink ID="HyperLink3" runat="server" Text='<%# If(Eval("documents") Is DBNull.Value, "No
document available", Eval("adocuments").ToString().Split(";")(2)) %>' NavigateUrl='<%#
String.Format("~/documents/uploads/{0}", Eval("documents").ToString().Split(";")(2)) %>'>
</asp:HyperLink>
When the document column has only 1 document, I'm getting the error message: Index was outside the bounds of the array and it points to Hyperlink # 2. But if a record has 3 documents name, it shows all 3 records as expected. I really appreciate any help or guide me to the right direction.
That is clear because creating an array with .Split you aren’t sure about array length.
So passing a parameter to get an element by this array you have to be sure that array contains the element which means you need to be sure the array length is > to index you want to get.
In this case just add a test for that as the code below shows (index is the parameter 0, 1, 2 etc….)
<%# If(Eval("documents") Is DBNull.Value OrElse Eval("documents").ToString().Split(";").Length < index, "No document available", Eval("documents").ToString().Split(";")(index)) %>

Conditional Display of Custom Button on DevExpress ASPxGridView in 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

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