LIstBox实现下拉列表

项目背景:给一个古老的项目加个小功能,结果用的2.0的组件

1、初始化下拉列表

 DataTable dt = new DataTable();
            dt.Columns.Add("id");
            dt.Columns.Add("name");
            DataRow dr1 = dt.NewRow();
            dr1["id"] = "01";
            dr1["name"] = "哈哈";
            dt.Rows.Add(dr1);

            dr1 = dt.NewRow();
            dr1["id"] = "02";
            dr1["name"] = "嘿嘿";
            dt.Rows.Add(dr1);

            dr1 = dt.NewRow();
            dr1["id"] = "31";
            dr1["name"] = "呵呵";
            dt.Rows.Add(dr1);

            dr1 = dt.NewRow();
            dr1["id"] = "33";
            dr1["name"] = "嘿哈";
            dt.Rows.Add(dr1);

            dr1 = dt.NewRow();
            dr1["id"] = csTypeId;
            dr1["name"] = "哈嘿";
            dt.Rows.Add(dr1);

            listBox.DataSource = dt;
            listBox.DisplayMember = "name";
            listBox.ValueMember = "id";

 

2、显示位置

private void pbOrderTypeSelect_Click(object sender, EventArgs e)
{
listBox.Left = panel1.Left + txtCHOrderTypeID.Left;
listBox.Width = txtCHOrderTypeID.Width;
listBox.Top = panel1.Top + txtCHOrderTypeID.Top + txtCHOrderTypeID.Height;
listBox.Visible = true;
listBox.BringToFront();
}

3、设置事件

 

 

 private void lbCHOrderType_MouseLeave(object sender, EventArgs e)
        {
            string un = string.Empty;
            chorderTypeIdList.Clear();
            DataRow dr;
            for (Int32 i = 0; i <= listBox.SelectedItems.Count - 1; i++)
            {
                dr = ((DataRowView)listBox.SelectedItems[i]).Row;
                //chorderTypeStr+=$"{dr["id"].ToString()},";
                string id = $"{dr["id"].ToString()}";
                chorderTypeIdList.Add(id);
                un = un + (dr["name"].ToString() + ",");
            }
            if (un.Length > 1)
            {
                un = un.Remove(un.Length - 1, 1);
            }
            this.txtCHOrderTypeID.Text = un;
            this.listBox.Visible = false;
        }

 

posted @ 2022-11-30 18:31  博客YS  阅读(229)  评论(0编辑  收藏  举报