z
 
:: Home     :: MS Dynamics CRM     :: .Net 1.1     :: .Net 2.0     :: Sharepoint Portal     :: Ajax

  login:        
  passwords:  
 

Resources

Finding Correct Content Managemet System
This list covers the full lifecycle of a content management system, from initially creating the content, through to delivering it to end users...

Workflow Managemet Systems
Workflow management is a crucial component in organizing a variety of business processes so that they benefit the business as a whole and increase profitability...

Using the Power of Content Management Systems
With page editors that resemble a word processor program, adding content with a CMS interface is simple and fun. Most CMS software also allows you to change the location of your content pages and links easily, while the back end processes takes care of updating the links throughout your site...

Content Management Systems (CMS): What They Are And Why We Love Them
In the past, individuals who took interest in having and operating their own websites were burdened with the task of learning HTML, DHTML, and other web-based technologies such as JavaScript and CSS. The only alternative to this was, unfortunately, to pocket the expenses and costs required to pay a web developer to build and maintain it for them...

Outsourcing
Post your project for outsourcing and get bids from qualified programmers, designers, interpreters, copywriters.


 

Code Walkthroughs

Datagrid Formatting the Data
We are able to format the content of the datagrid cell by one of two simple methods, dependant upon whether the column is a bound column or whether it is a template column. In our example we shall format the column to have to digits after the decimal point , followed by a...

Datagrid Highlight a Row With Click Through
It is relatively easy to add alternating colours to the rows in your datagrid. However, when we move the mouse over the rows we may want to highlight this row, and possibly to add the option of a click through based on the row selected...

Add a Delete Button to a Datagrid
To add a delete button to a datagrid follows a similar process to adding an edit button. In the datagrid header...

Add an Edit Button to a Datagrid
The datagrid has a predefined editColumn for handling the editing of a datagrid. Adding this simple column definition to a datagrid adds a powerful feature. When a row is not in edit mode the column item shows the word...

Making a Datagrid Row Editable
Two of the most popular methods of editing a datagrid in asp.net are to either select the row and take the user off to a different presentation of the data, or to change the formatting of the row presented in the database with appropriate edit text boxes, checkboxes and...

Adding Tooltips to Datagrid Rows
Adding tooltips to datagrid rows is easy, assuming that you have already created the code for adding row highlighting. In this article I shall assume that you have already read the article entitled Datagrid Highlight a Row With Click Through...

Binding a Datagrid to an Access Database
This list covers the full lifecycle of a content management system, from initially creating the content, through to delivering it to end users...

Adding Data to a DropDownList
The aim of this article is to answer the question 'How do I add items to a DropDownList?' Initially as part of the declaration for the DropDownList we can also define a number of items, much in the same way as in classic ASP...

Getting Current Date Time
In classic ASP we had now() which would return the current date and time. For asp.net this no longer exists. So what should we use...

Test if File Exists
Sometimes, in order to reduce our chance of error, when working with the filesystem in ASP.NET, we need to determine wether a file exists before performing an action on it. The following short piece of code will enable us to test whether a file exists...

Using Javascript with ASP.NET Form Elements
Adding simple pieces of Javascript to an Asp.net page can be acheived by adding to the attributes of the particular imagebutton or linkbutton. if its normal ASP.Net Button then you can...

Regular Expressions
In the table below we list the characters used in .Net regular expressions, together with their meaning, But first...

Authentication in Asp.net
Forms authentication in ASP.Net is far more easier and safe than Asp 3. It is possible to place a web.config file in any directory of a web site.Therefore, we are able to make most of a web site public, whilst providing authentication on, say, one directory...

Discussion Forums

General ASP.NET

.Net Programming

cSharp Home

Sql Server Home

Javascript / Client Side Development

IT Jobs

Ajax Programming

Ruby on Rails Development

Perl Programming

C Programming Language

C++ Programming

Python Programming Language

Laptop Suggestions?

TCL Scripting

Fortran Programming

Scheme Programming

16. ListBox

FAQ Home
   16.1 How to make the listbox scroll down to show it's last entry when the page loads?
   16.2 How to check if an item already exists in a listbox?
   16.3 How to populate a listbox with the Column Names in a Table?
   16.4 How to clear all the items in a listbox?
   16.5 How to add items dynamically to a ListBox using an ArrayList?
   16.6 How to move items between ListBoxes?
   16.7 How to select a specific Item in a ListBox in code?
   16.8 How can you use a ListBox control to display items with Price above a specific value in one color and the ones below that value in a different color?
   16.9 How to select all the Items from a listbox when the user selects a radio button?
   16.10 How to use a single DataReader associated with two different tables to databind two different listbox controls?

16.1 How to make the listbox scroll down to show it's last entry when the page loads?



<p>
<asp:ListBox id="ListBox1" runat="server"></asp:ListBox>
</p>
<p>
<asp:Button id="buttonAdd" runat="server" Text="Add"></asp:Button>
</p>


In button Click Event

VB.NET


ListBox1.Items.Add(DateTime.Now.ToString("MMM dd, yyyy") + " " + DateTime.Now.ToString("t"))
Dim scrollScript As String
scrollScript &= "<script language='javascript'>"
scrollScript &= "document.forms[0].ListBox1.selectedIndex " & _
" = document.forms[0].ListBox1.options.length-1;"
scrollScript &= "<" & "/" & "script>"
Page.RegisterStartupScript("", scrollScript)


C#


ListBox1.Items.Add(DateTime.Now.ToString("MMM dd, yyyy") + " " + DateTime.Now.ToString("t"));
string scrollScript="" ;
scrollScript += "<script language='javascript'>";
scrollScript += "document.forms[0].ListBox1.selectedIndex= document.forms[0].ListBox1.options.length-1;";
scrollScript += "<" + "/" + "script>";
Page.RegisterStartupScript("", scrollScript);



16.2 How to check if an item already exists in a listbox?


VB.NET


Dim lstitem As ListItem = ListBox1.Items.FindByValue("<valuecheckedfor>")
If Not lstitem Is Nothing Then
Response.Write("Item Exists")
Else
Response.Write("Item Does not exist")
End If


C#


ListItem lstitem = ListBox1.Items.FindByValue("<valuecheckedfor>");
if ( lstitem !=null)
{
     Response.Write ("Does exist");
}
else
{
     Response.Write ("Does not exist");
}


You can also use FindByText instead of FindByValue.


16.3 How to populate a listbox with the Column Names in a Table?


VB.NET


'Populate the dataset
Dim dc As DataColumn
For Each dc In ds.Tables(0).Columns
     ListBox1.Items.Add(dc.ColumnName)
Next


C#


//Populate the Dataset
foreach (DataColumn dc in ds.Tables[0].Columns)
{
     ListBox1.Items.Add(dc.ColumnName);
}



16.4 How to clear all the items in a listbox?


VB.NET


ListBox1.Items.Clear


C#


ListBox1.Items.Clear();



16.5 How to add items dynamically to a ListBox using an ArrayList?



<asp:ListBox id="ListBox1" runat="server" AutoPostBack="True"></asp:ListBox>


VB.NET


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
     'Put user code to initialize the page here
     If Not IsPostBack Then
          Dim arrList As New ArrayList
          arrList.Add("One")
          arrList.Add("Two")
          arrList.Add("Three")
          arrList.Add("Four")
          ListBox1.DataSource = arrList
          ListBox1.DataBind()
     End If
End Sub

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
     Response.Write(ListBox1.SelectedItem.Text)
End Sub


C#


private void Page_Load(object sender, System.EventArgs e)
{
     // Put user code to initialize the page here
     if (!Page.IsPostBack )
     {
          ArrayList arrList = new ArrayList();
          arrList.Add("One");
          arrList.Add("Two");
          arrList.Add("Three");
          arrList.Add("Four");
          ListBox1.DataSource = arrList;
          ListBox1.DataBind();
     }
}

private void ListBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
     Response.Write (ListBox1.SelectedItem.Text );
}



16.6 How to move items between ListBoxes?



<asp:ListBox id="ListBox1" runat="server">
     <asp:ListItem Value="Faqs">Faqs</asp:ListItem>
     <asp:ListItem Value="Tips">Tips</asp:ListItem>
     <asp:ListItem Value="Tricks">Tricks</asp:ListItem>
     <asp:ListItem Value="Advanced">Advanced</asp:ListItem>
</asp:ListBox>
<asp:Button id="btnToRight" style="Z-INDEX: 101; LEFT: 112px; POSITION: absolute; TOP: 24px"
     runat="server" Text=">"></asp:Button>
<asp:ListBox id="ListBox2" style="Z-INDEX: 102; LEFT: 152px; POSITION: absolute; TOP: 16px" runat="server"></asp:ListBox>
<asp:RequiredFieldValidator id="RequiredFieldValidator1" style="Z-INDEX: 103; LEFT: 24px; POSITION: absolute; TOP: 120px"
     runat="server" ErrorMessage="Please Select Item" ControlToValidate="ListBox1"></asp:RequiredFieldValidator>


VB.NET


Private Sub btnToRight_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnToRight.Click
     If ListBox1.Items.Count = 0 Then
          Response.Write("No item to move")
     End If
     Dim itemremoved As String = ListBox1.SelectedItem.Text
     ListBox1.Items.Remove(itemremoved)
     ListBox2.Items.Add(itemremoved)
End Sub


C#


private void btnToRight_Click(object sender, System.EventArgs e)
{
     if (ListBox1.Items.Count == 0 )
     {
          Response.Write("No item to move");
     }
string itemremoved = ListBox1.SelectedItem.Text;
ListBox1.Items.Remove(itemremoved);
ListBox2.Items.Add(itemremoved);
}



16.7 How to select a specific Item in a ListBox in code?


VB.NET


ListBox1.Items.FindByValue(<Value>).Selected = true
'ListBox1.Items.FindByText(<Text>).Selected = true


C#


ListBox1.Items.FindByValue(<Value>).Selected = true;
//ListBox1.Items.FindByText(<Text>).Selected = true;



16.8 How can you use a ListBox control to display items with Price above a specific value in one color and the ones below that value in a different color?


The ListBox Web server control prevents us from assigning the style property to each item in the ListBox. This bug is confirmed by Microsoft Knowledge Base Article - 309338
So, instead use a HTML ListBox with runat=server


<SELECT id="listbox1" size="14" runat="server" >
</SELECT>


VB.NET


Dim myconnection As SqlConnection
Dim myda As SqlDataAdapter
Dim ds As DataSet
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
     myconnection=NewSqlConnection("Server=localhost;uid=sa;password=;database=northwind;")
     myda = New SqlDataAdapter("Select * from Products ", myconnection)
     ds = New DataSet()
     myda.Fill(ds, "AllTables")
     dim i as Integer
     For i = 0 To ds.Tables(0).Rows.Count - 1
          listBox1.Items.Add(New ListItem(ds.Tables(0).Rows(i)("UnitPrice"), ds.Tables(0).Rows(i)("ProductID")))
          If ds.Tables(0).Rows(i)("UnitPrice") <= 25 Then
               listBox1.Items(i).Attributes.Add("style", "color:red")
          Else
               listBox1.Items(i).Attributes.Add("style", "color:green")
          End If
     Next
End Sub


C#


SqlConnection mycn;
SqlDataAdapter myda;
DataSet ds;
String strConn;
private void Page_Load(object sender, System.EventArgs e)
{
     if (!IsPostBack)
     {
          strConn="DataSource=localhost;uid=sa;pwd=;Initial Catalog=northwind";
          mycn = new SqlConnection(strConn);
          myda = new SqlDataAdapter ("Select * FROM Products ", mycn);
          ds = new DataSet();
          myda.Fill (ds,"Table");
                    
          for(int i = 0 ;i < ds.Tables[0].Rows.Count - 1;i++)
          {
               listBox1.Items.Add (new ListItem(ds.Tables[0].Rows[i]["UnitPrice"].ToString(),
               ds.Tables[0].Rows[i]["ProductID"].ToString()));
               if(Convert.ToDouble(ds.Tables[0].Rows[i]["UnitPrice"].ToString()) <= 25 )
               {
                    listBox1.Items[i].Attributes.Add("style", "color:red");
               }
               else
               {