Kamran Ahmed

DropDownList in ASP.Net




A DropDownList is also commonly known as combo box. It can contain multiple data members, but unlike a normal list box the users can choose only one value from this control. Though the functionality of this DropDownList is much like a Single Row Select List Box, a DropDownList can save a lot of GUI space as it is rendered on a Single line and is expanded only when the user clicks on the Control.
This DropDownList is provided as a Server Control in ASP .Net like many other controls. This DropDownList can be used to add data manually or even for dynamic binding with data base.
DropDownList1.DataSource = objDataset.Tables[0];
DropDownList1.DataTextField = "DisplayValueFieldFromDB";
DropDownList1.DataValueField = "DataValueFieldFromDB";
DropDownList1.DataBind();

The above code will load the DropDownList  with the Display Value as DisplayValueField From DB and Data Value as DataValueField From DB.

Reading the Data from a DropDownList in ASP .Net:

Reading the data from a DropDownList can be achieved in a very easy manner. The Items collection, which is a member of the DropDownList class holds all the details about the members. The values can be retrieved as DropDownList.Items[index] - replace the index with a number, which can go up to the maximum number of data members. This will return the value.
If one wants to find the selected value, then the DropDownList.SelectedItem.Value can be used. The SelectedItem is a member of the class.

Others:

For removing the items, the function DropDownList. Items .Remove() can be used. To delete all the items from the DropDownList in ASP .Net, the DropDownList.Items.Clear() function can be used.
Use Same type of code with ListBox ,RadioButtonList, CheckBoxList


Reading data from ListBox & CheckBoxList:-
Label1.Text = "";
foreach (ListItem objTempListItem in CheckBoxList1.Items)
{
if (objTempListItem.Selected == true)
      {
            Label1.Text += objTempListItem.Text + "--" + objTempListItem.Value + "<BR>";
       }
}

For DataGrid & DataList use this code

objDatagrid.DataSource= objDataSet.Tables[0];
objDatagrid.DataBind();


No comments:

Post a Comment