如何在Listbox上设置Multiple SelectedItem?

时间:2011-02-17 07:52:26

标签: c# asp.net

示例代码如下:

<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"));

我想在Item1和Item3上设置2默认selectedItem,怎么做?

使用这些代码,只会选择最新的代码

ddlCat.SelectedValue = "1";

ddlCat.SelectedValue = "3";

非常感谢!!

2 个答案:

答案 0 :(得分:5)

我找到了解决方案

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

答案 1 :(得分:1)

{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");
                        }
                    }


                }}