March
March

Reputation: 635

How to set Multiple SelectedItem on Listbox?

The sample code like this:

<asp:Listbox ID="ddlCat" runat="server" SelectionMode="Multiple" />

ddlCat.Items.Insert(0, new ListItem("Item1", "1"));

ddlCat.Items.Insert(1, new ListItem("Item2", "2"));

ddlCat.Items.Insert(2, new ListItem("Item3", "3"));

ddlCat.Items.Insert(3, new ListItem("Item4", "4"));

I want set 2 default selectedItem on Item1 and Item3, how to do this?

Use those code, only the latest will be selected

ddlCat.SelectedValue = "1";

ddlCat.SelectedValue = "3";

Thanks a lot!!

Upvotes: 2

Views: 5301

Answers (2)

Gokul SN
Gokul SN

Reputation: 11

{if (e.Row.RowType == DataControlRowType.DataRow && gridView.EditIndex == e.Row.RowIndex)
                {
                    ListBox ddl_Makeid = (ListBox)e.Row.FindControl("lst_hopid");
                    DataSet ds = new DataSet();
                    con.Open();
                    string cmdstr = "SELECT HeadsOfPricingId,HeadsOfPricing FROM tblHeadsOfPricing";
                    SqlCommand cmd = new SqlCommand(cmdstr, con);
                    SqlDataAdapter adp = new SqlDataAdapter(cmd);
                    adp.Fill(ds);
                    ddl_Makeid.DataSource = ds.Tables[0];
                    ddl_Makeid.DataTextField = "HeadsOfPricing";
                    ddl_Makeid.DataValueField = "HeadsOfPricingId";
                    DataRowView drv = e.Row.DataItem as DataRowView;
                    ddl_Makeid.DataBind();
                    con.Close();

                    Label lbl_texbox = (Label)e.Row.FindControl("lbl_hopId_edit");
                    string stsplit = lbl_texbox.Text;
                    char[] splichar = { ',' };
                    string[] strarray = stsplit.Split(splichar);

                    //ListBox listbox = (ListBox)e.Row.FindControl("lst_hopid");
                    ListBox listboxtest = new ListBox();
                    for (int x = 0; x < strarray.Length; x++)
                    {
                        if (strarray[x] != null && strarray[x] !="")
                        {
                            //ddl_Makeid.SelectedValue += strarray[x];
                            ddl_Makeid.Items.FindByValue(strarray[x]).Selected = true;
                            //listboxtest = (ListBox)e.Row.Cells[x].FindControl("Lst_New_hopid");
                        }
                    }


                }}

Upvotes: 1

March
March

Reputation: 635

I found the solution

ddlCat.Items.FindByValue("1").Selected = true;
ddlCat.Items.FindByValue("3").Selected = true;

Upvotes: 6

Related Questions