Tuesday, May 1, 2012

How to add different column values as Tooltip for DropDownList in ASP.NET

 

Sometimes we may have to show different field from the database as tool tip for the DropDownList in ASP.NET.

Below is a sample code to display the tooltip for DropDownList. Here I have used different field from the database to show as tooltip.

protected void btnLoad_Click(object sender, EventArgs e)
        {
            string strCon = System.Configuration.ConfigurationManager.ConnectionStrings["sqlConnection"].ToString();
 
            SqlConnection conn = new SqlConnection(strCon);
            conn.Open();
            SqlDataAdapter da = null;
            DataSet dsCountry = new DataSet();
            try
            {
                string strCountrySQL = "select id, name, Address from dbo.Customer";
                da = new SqlDataAdapter(strCountrySQL, conn);
                da.Fill(dsCountry);
                DropDownList1.DataSource = dsCountry;
                DropDownList1.DataTextField = "name";
                DropDownList1.DataValueField = "id";
                DropDownList1.DataBind();
 
                int ItemCount = DropDownList1.Items.Count;
                for (int i = 0; i < ItemCount; i++)
                {
                    DropDownList1.Items[i].Attributes.Add("Title", dsCountry.Tables[0].Rows[i]["Address"].ToString());
                }
                DropDownList1.Items.Insert(0, new ListItem("--Select--", "--Select--"));
                DropDownList1.SelectedItem.Selected = false;
                DropDownList1.Items.FindByText("--Select--").Selected = true;
            }
            catch (Exception ex)
            {
                lblMsg.Text = "Error!! <br>+" + ex.Message.ToString();
            }
            finally
            {
                dsCountry.Dispose();
                da.Dispose();
                conn.Close();
                conn.Dispose();
            }

Below is the screen print of the tooltip,

ToolTip

No comments: