Friday, April 27, 2012

Disable DropDownList without blur effect in Asp.Net

In View mode, we will set the .Enabled property of controls false, to prevent the users from modifying the values in the control, but this will create a blur effect on the controls and the text in the controls will not be visible clearly.  Especially in the DropDownList control, when the control is disabled the user will not be able to see the other options available in the DropDownList control.

We can overcome this with the help of some JavaScript, adding this script will enable the users to view the other options in the dropdown, but still makes sure that the user cannot change the currently selected option in the View mode.

ListBox with Multi Selection in Asp.Net


ListBox with Multi Selection in Asp.Net

In general we use the DropDownList control in Asp.Net when the user needs to select an item from a list of available options, but there are situations where we need to allow the user to select more than one item from the available options, in these situations we can use the ListBox control.

Here is the design code in the .aspx page to place the ListBox and the various options, not that the SelectionMode property is set to Multiple, this will allow the user to select more than one option by pressing the CTRL (Control) key.

ListBox structure in .aspx page
<asp:ListBox
ID="lstBasePackageAsset"
runat="server"
SelectionMode="Multiple">
<asp:ListItem Value="0">-Select-</asp:ListItem>
<asp:ListItem Value="1">Name1</asp:ListItem>
<asp:ListItem Value="2">Name2</asp:ListItem>
<asp:ListItem Value="3">Name3</asp:ListItem>
</asp:ListBox>

Once the design code is in place, we can use the following code in the code-behind file to loop through the list items and find the ones which are selected. The selected items can be inserted into a database by using appropriate INSERT queries.

Reading the values (Multi-Select) from the ListBox & insert to the Database
for (int i = 0; i < lstNames.Items.Count; i++)
{
  if (lstNames.Items[i].Selected == true)
   {
sbInsertQuery.Append("insert into EMP_LIST (ID)VALUES (" + lstNames.Items[i].Value)");
    }
}

Once the items are inserted into the database, we will have to display them in the View mode, for a normal DropDownList control, we will use the SelectedValue or SelectedText property to set the selected value, but here we are dealing with multiple selection items, hence we need to run a loop of the list items and another loop on the selected ID’s and set the selected items in the list, here the code to set the selected items.

Selecting Multiple Items in the ListBox
strQuery = "SELECT ID FROM EMP_LIST;

DataSet
 dsNames = DataAccessLayer.GetDataSet(strQuery,"dtNames");

for (int j = 0; j < dsNames.Tables[“dtNames”].Rows.Count; j++)
{
  String strID = dsNames.Tables["dtNames"].Rows[i]["ID"].ToString()
  for (int k = 0; k < lstNames.Items.Count; k++)
  {
    if (lstNames.Items[k].Value == strID)
    {
      lstNames.Items[k].Selected = true;
    }
  }
}

That’s it we have seen how to restried/set multi-select items from an Asp.Net ListBox.

Wednesday, April 25, 2012

Enable / Disable controls in an Asp.Net Panel


Enable / Disable controls in an Asp.Net Panel

In general for Asp.Net forms we maintain different modes like Create mode, View mode & Edit mode.

In the View mode we will disable all the controls to make sure that the user does not, modify any of the details. To disable the controls which are placed directly in the page, we can just iterate through the Page.Controls collection and Enable/Disable the controls. Refer the Post Enable / Disable all controls in an Asp.Net Page to see how to accomplish this.

However if there are Panel controls in the page then a mere iteration with the Page.Controls collection will not reflect the controls which are placed inside the Panel, to Enable/Disable controls in the Panel, we need to iterate throught the Controls in the Panel.

Here is the code to enable the controls in a Panel.

if (strMode.ToUpper() == "VIEW"))
{
    EnableControls(false);
}
else if (strMode.ToUpper() == "EDIT"))
{
    EnableControls(true);
}

Based on the mode VIEW/EDIT we will pass false/true to the EnableControls function, and the same will DISABLE/ENABLE controls in the Panel.
private void EnableControls(bool ctrlStatus)
{
 foreach (Control c in Page.Controls)
 {
  foreach (Control ctrl in c.Controls)
  {
    if (ctrl is Panel)
    {
foreach (Control plnCtrl in ctrl.Controls)
{
        if (plnCtrl is TextBox)
         ((TextBox) plnCtrl).ReadOnly = (ctrlStatus == true) ? false : true;

        else if (plnCtrl is Button)
         ((Button) plnCtrl).Enabled = ctrlStatus;

        else if (plnCtrl is RadioButtonList)
         ((RadioButtonList) plnCtrl).Enabled = ctrlStatus;

        else if (plnCtrl is ImageButton)
         ((ImageButton) plnCtrl).Enabled = ctrlStatus;

        else if (plnCtrl is CheckBox)
         ((CheckBox) plnCtrl).Enabled = ctrlStatus;

        else if (plnCtrl is DropDownList)
          ((DropDownList) plnCtrl).Enabled = ctrlStatus;

         else if (plnCtrl is HyperLink)
          ((HyperLink) plnCtrl).Enabled = ctrlStatus;

         else if (plnCtrl is HtmlImage)
    ((HtmlImage) plnCtrl).Visible = ctrlStatus;
    }
  }
 }
}

Notice the we are setting the .Enabled property for all other controls except the textBox control, when a TextBox is disbled the contents in the TextBox will not be clearly visible to the users hence we are setting the ReadOnly property for the TextBox, and this functions opposite to the Enable/Disable

If Enable is set to true then ReadOnly should be set to false
If Enable is set to false then ReadOnly should be set to true

To achieve this we are using a conditional operator to reverse the value for the ReadOnly property.

((TextBox)ctrl).ReadOnly = (ctrlStatus == true) ? false : true;

That’s it we have Enabled/Disabled the controls of an Asp.net Panel by iterating through the collection.


Related Post

Enable / Disable all controls in an Asp.Net Page


Enable / Disable all controls in an Asp.Net Page

In general for Asp.Net forms we maintain different modes like Create mode, View mode & Edit mode.

In the View mode we will disable all the controls to make sure that the user does not, modify any of the details. If the form is small then we can manually set the .Enabled property to false for all the controls in the form to achieve the effect, however if we have a huge form with hundreds of controls then this becomes a tedious task to set the property for each of the controls, in these scenarios we can make use of the Page.Controls collection to loop throught all the controls in the page and Enable/Disable the controls.

Here is the code to enable all the controls in an Asp.net page.

if (strMode.ToUpper() == "VIEW"))
{
    EnableControls(false);
}
else if (strMode.ToUpper() == "EDIT"))
{
    EnableControls(true);
}

Based on the mode VIEW/EDIT we will pass false/true to the EnableControls function, and the same will DISABLE/ENABLE controls in the page.

private void EnableControls(bool ctrlStatus)
{
  foreach (Control c in Page.Controls)
   {
    foreach (Control ctrl in c.Controls)
    {
      if (ctrl is TextBox)
        ((TextBox)ctrl).ReadOnly = (ctrlStatus == true) ? false : true;

        else if (ctrl is Button)
         ((Button)ctrl).Enabled = ctrlStatus;

        else if (ctrl is RadioButtonList)
         ((RadioButtonList)ctrl).Enabled = ctrlStatus;

        else if (ctrl is ImageButton)
         ((ImageButton)ctrl).Enabled = ctrlStatus;

        else if (ctrl is CheckBox)
         ((CheckBox)ctrl).Enabled = ctrlStatus;

        else if (ctrl is DropDownList)
         ((DropDownList)ctrl).Enabled = ctrlStatus;

        else if (ctrl is HyperLink)
         ((HyperLink)ctrl).Enabled = ctrlStatus;

        else if (ctrl is HtmlImage)
   ((HtmlImage)ctrl).Visible = ctrlStatus;
}
   }
}


Notice the we are setting the .Enabled property for all other controls except the textBox control, when a TextBox is disbled the contents in the TextBox will not be clearly visible to the users hence we are setting the ReadOnly property for the TextBox, and this functions opposite to the Enable/Disable

If Enable is set to true then ReadOnly should be set to false
If Enable is set to false then ReadOnly should be set to true

To achieve this we are using a conditional operator to reverse the value for the ReadOnly property.

((TextBox)ctrl).ReadOnly = (ctrlStatus == true) ? false : true;

This logic will work fine for the controls which are placed directly in the form, if the form has a Panel, we need to add another iteration, which will iterate through the controls in the Panel to Enable/Disable the panel controls. Refer to the Post Enable / Disable controls in an Asp.Net Panel, to see how to achieve this. 

That’s it we have Enabled/Disabled the controls of an Asp.net page by iterating through the Page.Controls collection.



Related Post

Tuesday, April 24, 2012

Using conditional (?:) Operator to save Check box state


Using conditional (?:) Operator to save Check box state

Saving the state of a CHECKBOX to the database in the INSERT mode and setting the status in the View mode is a normal operations in any form based application. 

Conventionally we use to write a code block to check the state of the CHECKBOX (Checked/Unchecked) and save/set its state. The conventional code goes like this.

Conventional Method

To insert data into the Database

StringBuilder sbInsertQuery = null;
sbInsertQuery = new StringBuilder();
....
if (chkValid.Checked == true)
{
    sbInsertQuery.Append("'Y',");
}
else
{
    sbInsertQuery.Append("'N',");
}
...
DataAccessLayer.ExcuteQuery(sbInsertQuery.ToString());

To set the Checkbox state from the Database data

if(dsDetails.Tables["dtDetails"].Rows[0]["VALID"].ToString() == "Y")
{
 chkValid.Checked = true;
}
else
{
 chkValid.Checked = false;
}

As you could see we have written 8 lines of code to check the state of the CHECKBOX and insert the state into the Database, again we had to write 8 more lines of code to fetch the details from the database and set it on the form field.

Now let us see on how this can be optimized using the conditional (?:) Operator, here is the code using the conditional (?:) Operator


Using the conditional (?:) Operator

To insert data into the Database
StringBuilder sbInsertQuery = null;
sbInsertQuery = new StringBuilder();
....
sbInsertQuery.Append("'" + ((chkValid.Checked) ? "Y" : "N") + "',");
...
DataAccessLayer.ExcuteQuery(sbInsertQuery.ToString());

To set the Checkbox state from the Database data
chkValid.Checked = (dsDetails.Tables["dtDetails"].Rows[0]["VALID"].ToString() == "Y")? true:false;


Just 2 lines of code, 1 to form the Insert query and the other to set the state in the Form. Using the conditional (?:) Operator we have reduced the total lines of code from 16 to just 2 lines.

That's it, we have seen, the use of conditional (?:) Operator, in optimizing the code in saving/setting the state of a CHECKBOX and to reducing the number of lines of code.

Monday, April 23, 2012

Operation is not valid due to the current state of the object


When the number of controls / fields in an Asp.Net 3.0 form exceeds 1000, the following error message will be thrown.

Operation is not valid due to the current state of the object.  
  at System.Web.HttpValueCollection.ThrowIfMaxHttpCollectionKeysExceeded()    
  at System.Web.HttpValueCollection.FillFromEncodedBytes(Byte[] bytes, Encoding encoding)    
  at System.Web.HttpRequest.FillInFormCollection()



This is because the Microsoft security update MS11-100 limits the maximum number of form keys, files, and JSON members to 1000 in an HTTP request.

When there is a HTTP request requesting for a page which has more than 1000 fields/controls, this exception in thrown.

The good thing is, that there is a fix for the issue, which can be made by altering the settings in the web.config file. Adding the following line to the <appSettings> section will increase the limit from 1000 to 2000, you can configure the <appSettings> section based on your needs.

<appSettings>
    <add key="aspnet:MaxHttpCollectionKeys" value="2001" />
appSettings>

For more information please visit the following post in Microsoft’s support center.




http://support.microsoft.com/kb/2661403

Thursday, April 19, 2012

Filter a List <T> using LINQ


LINQ can be used effectively to filter out a set of objects from a List of objects, in todays post we shall see on how to accomplish object filtering using LINQ.

To know more about binding a List object to a DropDownList refer to the post, Binding a List <T> object to a DropDownList control


First let us create a class whoose objects will be stored in the List <T> here is the code for the class.

public class clsCountry
{
    public string _CountryCode;
    public string _CountryName;
    //
    public clsCountry(string strCode, string strName)
    {
        this._CountryCode = strCode;
        this._CountryName = strName;
    }
    //
    public string CountryCode
    {
        get {return _CountryCode;}
        set {_CountryCode = value;}
    }
    //
    public string CountryName
    {
        get { return _CountryName; }
        set { _CountryName = value; }
    }
}

Next, let us create a list of objects based on our class clsCountry and store them in a List <T> object. Here is the code for the List <T>

List<clsCountry> lstCountry = new List<clsCountry>();
lstCountry.Add(new clsCountry("USA", "United States"));
lstCountry.Add(new clsCountry("UK", "United Kingdom"));
lstCountry.Add(new clsCountry("IND", "India"));

Next, we shall bind the List <T> object lstCountry to a DropDownList control. Here the code to bind the data.

drpCountry.DataSource = lstCountry;
drpCountry.DataValueField = "CountryCode";
drpCountry.DataTextField = "CountryName";
drpCountry.DataBind();

Notice that the DataValueField and DataTextField property of the DropDownList control are mapped to the Properties of the class CountryCode and CountryName, hence make sure to create properties for every member of the class so that they can be used while binding the data to controls.

Finally, we shall use LINQ to filter data from the lstCountry object and bind the filtered list to the dropdown control drpCountry. Here is the code to filter the List <T> using LINQ

var filteredCountries = from c in lstCountry
                        where c.CountryName.StartsWith("U")
                        select c;

drpCountry.DataSource = filteredCountries;
drpCountry.DataValueField = "CountryCode";
drpCountry.DataTextField = "CountryName";
drpCountry.DataBind();

Now the dropdown control will have only 2 items

United States
United Kingdom



Here we are using c.CountryName.StartsWith("U") which works like

CountryName LIKE 'U%' 

We can use c.CountryName.Contains("U"), method to make the filter work like

CountryName LIKE '%U%'

i.e, it will filter out all objects which have the character U anywhere in the CountryName property of the object. 


That’s it we have filtered a List <T> and bound the contents of the filtered List <T> to a DropDownList control.