Showing posts with label Devexpress. Show all posts
Showing posts with label Devexpress. Show all posts

Wednesday, June 6, 2012

ASPxSpinEdit validation: number greater than 0

The only way I could find is to use the client-side validation event




or use regex if you find a good expression

Friday, April 13, 2012

AppendDataboundItems for ASPxCombobox

In order to mimic the 'AppendDataBound' feature found in normal ASP.NET comboboxes for devexpress and add items to a bound control, you need to use the databound event to insert the new values if you need a server side solution

protected void myComboBox_DataBound(object sender, EventArgs e)
        {
            myComboBox.Items.Add("All", "0").Index = 0;
            myComboBox.SelectedIndex = 0;
        }

You can also do it at client side by using the following code

comboBox.ClientSideEvents.Init = "function(s, e) {s.InsertItem(0, '(ALL)', '');}";



Tuesday, January 17, 2012

Check if control exists by ClientInstanceName

In order to check whether a specific Devexpress control exists using javascript, you can use the ASPxClientUtils.IsExists method. If the control exists, the method words as expected. The problem rises when the control you are looking for doesn't exist as this will cause the error 'ReferenceError: myControl is not defined' in javascript. In order to solve this, first use the eval function to check whether the object exists and put it inside a try catch.
var obj = null;
try { obj = eval('myClientASPxGridview'); } catch (e) { }
if (ASPxClientUtils.IsExists(obj))
    myClientASPxGridview.PerformCallback();
Link to ASPxClientUtils.IsExists documentation

Tuesday, January 3, 2012

ASPxGridview Error: LinqDataSource '' does not support the Update operation unless EnableUpdate is true

When using ASPxGridview binded to a LinqServerModeDataSource, make sure that EnableUpdate is set to false when you are handling the update in the rowupdating event. I was getting the error

LinqDataSource '' does not support the Update operation unless EnableUpdate is true

because I forgot to add the following lines in the rowupdating event, which tells the grid that the event has been handled. Omitting these 2 lines causes the code to think that the update needs to be handled by the linqdatasource, which results in the above error

void MyGrid_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
{
   //Code to update, example:
   //int pb_pk; int.TryParse(Convert.ToString(e.Keys[0]), out pb_pk);
   //int pb_w3_Budget_fk; int.TryParse(Convert.ToString(e.NewValues["pb_w3_Budget_fk"]), out pb_w3_Budget_fk);
   //SqlDataProvider.PurchasingBudgets_Update(pb_pk, pb_w3_Budget_fk);
   e.Cancel = true;
   (sender as ASPxGridView).CancelEdit();
}

Thursday, December 22, 2011

How To - Cascading dropdowns using AJAX Callbacks

Filtering data for the users is very important for 2 reasons

  1. Results in a more user friendly experience
  2. Reduces data, therefore reduces load time.  

One of the most common scenarios is to have multiple dropdownlists which filter each other. For example: categories and sub-categories.
The below code uses the MS database adventureworks to retrieve data.

MS AJAX Toolkit

In the following example, we will be using the AJAX Control Toolkit. In order to start using the toolkit, you will first need to add the toolkit reference to the project, then add the following line at the top of the aspx page
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit"  %>
In order to use any control or extender from the toolkit, you will need to drop a scriptmanager in the page (this can be in the masterpage as well)

In the aspx file, copy the following code
Category
Sub Category
and in the webservice use the following code
 [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {
        [WebMethod]
        public CascadingDropDownNameValue[] GetCategories(string knownCategoryValues, string category)
        {
            DataTable dt = SqlHelper.ExecuteDataset(
            ConfigurationManager.ConnectionStrings["AdventureWorksConnectionString"].ConnectionString,
            CommandType.Text, "SELECT * FROM [Production].[ProductCategory]").Tables[0];

            List values = new List();

            foreach (DataRow dr in dt.Rows)
            {
                values.Add(new CascadingDropDownNameValue((string)dr["Name"], 
                dr["ProductCategoryID"].ToString()));
            }
            return values.ToArray();
        }

        [WebMethod]
        public CascadingDropDownNameValue[] GetSubCategories(string knownCategoryValues, string category)
        {
            StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

            int categoryId;
            if (!kv.ContainsKey("category") || !Int32.TryParse(kv["category"], out categoryId))
            {
                return null;
            }

            DataTable dt = SqlHelper.ExecuteDataset(
            ConfigurationManager.ConnectionStrings["AdventureWorksConnectionString"].ConnectionString,
            CommandType.Text, "SELECT * FROM [Production].[ProductSubcategory] WHERE ProductCategoryID = "
             + categoryId).Tables[0];

            List values = new List();

            foreach (DataRow dr in dt.Rows)
            {
                values.Add(new CascadingDropDownNameValue((string)dr["Name"],
                dr["ProductSubcategoryID"].ToString()));
            }
            return values.ToArray();
        }
    }
Do not forget to uncomment the part [System.Web.Script.Services.ScriptService] or else it will not work.

Devexpress

Another way to implement this is to use the devexpress combobox (ASPxCombobox). Aspx:
code behind
protected void ddlSubCategory_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
{
      if (string.IsNullOrEmpty(e.Parameter)) return;
      dsSubCategory.SelectParameters["ProductCategoryID"].DefaultValue = e.Parameter;
      ddlSubCategory.DataBind();
}
Personally, I prefer using the DevExpress controls as it involves much less tedious work and you do not need to create a webservice. Obviously this comes with a price tag, so if you have a limited budget, the ASP.net toolkit still offers a very good solution.

Friday, September 30, 2011

ASPxComboBox: Add button to clear selection

The Devexpress ASPxComboBox contains a Buttons collection to which you can add a number of buttons. By default the button will contain ellipsis (...) as Text but you can change this by using the Text property. You can also add an image like in the code below. In order to remove the selection you will need to add the clientsideevent button click and check for the buttonindex. If the buttonindex is 0 (the button will create will be the first on displayed), then set the selectedindex to -1, thus removing selection.


                                                            
                                                            
                                                            


Thursday, July 28, 2011

ASPxGridView: How To - Creating custom delete column with image at runtime

It took me a while to find a way to a add a delete column with an embedded image so I thought it would be better in this blog for easy reference. Naturally, I wanted the confirm message before deleting as well. There seems to be 2 ways to do this:

Using the in-built Delete button: GridViewCommandColumn.DeleteButton

GridViewCommandColumn commandColumn = new GridViewCommandColumn();
commandColumn.Width = new Unit("40");
commandColumn.ButtonType = ButtonType.Image;
commandColumn.DeleteButton.Image.IsResourcePng = true;
commandColumn.DeleteButton.Image.Url = Page.ClientScript.GetWebResourceUrl(typeof(xxx.Controls.DynamicGrid), @"xxx.Controls.DeleteBin.png");
commandColumn.DeleteButton.Visible = true;
commandColumn.DeleteButton.Text = "Delete"; //Tooltip
                    
gvMyDataGrid.Columns.Add(commandColumn); // add custom column to grid
gvMyDataGrid.SettingsBehavior.ConfirmDelete = true; // display popup confirmation upon clicking delete button
gvMyDataGrid.SettingsText.ConfirmDelete = "Are you sure you want to delete this item?"; //Text you want to be displayed.  This can also be retrieved from the resource file

Or creating your own button from scratch

GridViewCommandColumn commandColumn = new GridViewCommandColumn();
commandColumn.Width = new Unit("40");
commandColumn.ButtonType = ButtonType.Image;

GridViewCommandColumnCustomButton deleteButton = new GridViewCommandColumnCustomButton();
deleteButton.Image.IsResourcePng = true;
deleteButton.Image.Url = Page.ClientScript.GetWebResourceUrl(typeof(xxx.Controls.DynamicGrid), @"xxx.Controls.DeleteBin.png");
deleteButton.Visibility = GridViewCustomButtonVisibility.AllDataRows;
deleteButton.Text = "Delete";
deleteButton.ID = "cmdDelete";

commandColumn.CustomButtons.Add(deleteButton); // add custom button to new command column
gvMyDataGrid.Columns.Add(commandColumn);
//We need the next line of code to add the confirmation popup ourselves.  Notice the 'cmdDelete' parameter which is the custom delete button's ID above.
gvMyDataGrid.ClientSideEvents.CustomButtonClick = "function (s, e) { if (e.buttonID == 'cmdDelete'){ e.processOnServer = confirm('Are you sure you want to delete this item?'); }}";

//confirm() method will return the user's selection:  true if OK, false if cancel.  Therefore if return this value and set it to e.processOnServer, this will tell the button to not commit a callback if the user selects 'cancel'

In both examples I am using an embedded image as I wanted the grid to be used by just adding a reference to the DLL and not having to add the image to every project.

In order to embed the image:

  1. Go to the image's Properties.  
  2. Set Build Action to Embedded Resource
  3. Go to AssemblyInfo.cs
  4. Add using System.Web.UI; 
  5. Add [assembly: WebResource("YourNamespace.ImageFileName.png", "image/png")]
  6. Get the image url as described above Page.ClientScript.GetWebResourceUrl(typeof(xxx.Controls.DynamicGrid), @"xxx.Controls.DeleteBin.png");

Wednesday, July 6, 2011

Validate Devexpress controls at client-side using javascript

In order to validate devexpress controls in the page using javascript, use the following code:

ASPxClientEdit.ValidateGroup(null); or ASPxClientEdit.ValidateGroup('validationgroup');

This method returns true if all controls on the current page with the specified validationgroup pass validation and false if they don't

Example:

<dx:ASPxButton ID="btnAdd" runat="server" Text="Add" AutoPostBack="false">
     <ClientSideEvents Click="function(s,e){ if(ASPxClientEdit.ValidateGroup(null)) { alert('Validation OK'); } }" />
</dx:ASPxButton>

or using a normal button
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClientClick="if(ASPxClientEdit.ValidateGroup(null)) { alert('Validation OK'); return false; } " />

Don't forget to use return false; OR e.processOnServer=false;  OR AutoPostBack=false; if you do not want the button to cause a postback.

Check Online Documentation for more details