Click here to Skip to main content
15,892,965 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I am shailendra singh. Can any one help me.

I want to add value on dropdownlist Item by function but I want show on top select key word in dropdownlist, by function.

My following Function.
C#
public void FillReportType()
    {
        con.Open();
        drpregtype.Items.Insert(0, new ListItem("--Select---", "----"));
        drpregtype.SelectedIndex = 0;
        da = new SqlDataAdapter("Select ResultType from tblresultType order by id ", con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        drpregtype.DataSource = dt;
        drpregtype.DataValueField = "ResultType";
        //drpregtype.Items.Add.Add(new ListItem("--", "Select"));
        //drpregtype.Items.Insert(0, new ListItem("--Select---", "----"));
        //drpregtype.SelectedIndex = 0;
         drpregtype.DataBind();
        con.Close();
    }

Thanks for Advance.
Posted
Updated 10-Jan-12 20:47pm
v2

Hello Shailendra,

just modifying your code :
C#
public void FillReportType()
    {
        con.Open();
       
        drpregtype.SelectedIndex = 0;
        da = new SqlDataAdapter("Select ResultType from tblresultType order by id ", con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        drpregtype.DataSource = dt;
        drpregtype.DataValueField = "ResultType";
        //drpregtype.Items.Add.Add(new ListItem("--", "Select"));
        //drpregtype.Items.Insert(0, new ListItem("--Select---", "----"));
        //drpregtype.SelectedIndex = 0;
         drpregtype.DataBind();
        drpregtype.Items.Insert(0, new ListItem("--Select---", "0"));
        con.Close();
    }


Hope this will give you solution, that you want.
Don't forget to mark as answer if it helps. :)
 
Share this answer
 
Comments
Tech Code Freak 11-Jan-12 4:57am    
My 5!
Hi,

you have two options:

1. Add the "Select" entry to your datasource (as first item) and then bind your dropdown to that datasource

or 2. Add your items manually to your dropdownlist without binding it to a datasource.

You cannot add an item and expect it to be shown und bind a datasource at the same time.

In addition to that you should get rid of the sql in your view.

Hope this helps
 
Share this answer
 
Comments
Tech Code Freak 11-Jan-12 4:57am    
My 5!
i agree with above solutions

make listitem of name ---select---
and make it as selected

ListItem l1 = new ListItem("----Select----", "none");
ListItem l2 = new ListItem("abc", "abc");
ListItem l3 = new ListItem("xyz", "xyz");
DropDownList1.Items.Add(l1);
DropDownList1.Items.Add(l2);
DropDownList1.Items.Add(l3);
l1.Selected = true;


all the best
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900