[Asp.Net]动态生成控件

本文介绍了一种根据数据库查询结果动态生成表单控件的方法,包括标签和文本框,并根据查询结果设置文本框的默认值、最大长度及背景颜色等属性。

 很久以前写过一段代码:编码的时候生成规格,规格是根据中的ID 数据库对应规格,需要显示动态的文本框。

  protected void dynamic_create_control()
    {
        string connectionString = "Data Source=SyteLine;Initial Catalog=SHATDB;Persist Security Info=True;User ID=SA;Password=SVTEP";
        string SQLsettxt = "select Description,ID,Need,length from ItemCodeTypeDesc where TypeID=" + DropDownList2.Text + "Order by Priority ASC";
        string SQLnum = "select count(ID) from ItemCodeTypeDesc where TypeID=" + DropDownList2.Text;


        SqlConnection myConn = new SqlConnection(connectionString);
        myConn.Open();
        SqlCommand myCommnum = new SqlCommand(SQLnum, myConn);
        imun = Convert.ToInt32(myCommnum.ExecuteScalar());
        SqlCommand myComm = new SqlCommand(SQLsettxt, myConn);
        SqlDataReader myDR = myComm.ExecuteReader();
        int i = 0;
        if (i < imun)
        {
            while (myDR.Read())
            {

                Label mylabel = new Label();
                mylabel.ID = "lab" + (i + 1).ToString();

                mylabel.Text = myDR[0].ToString() + ":";
                mylabel.Width = 100;
                mylabel.Height = 24;
   

                Panel1.Controls.AddAt(i, mylabel);

                TextBox tb = new TextBox();
                tb.ID = "txt" + (i + 1).ToString();
                if (myDR[0].ToString() == "外径")
                {
                    tb.Text = "@";
                }
                else 
                {
                    tb.Text = "";
                }

                if (myDR["length"].ToString() == "")
                {
                    tb.MaxLength = 50;
                }
                tb.MaxLength = Convert.ToInt32(myDR["length"].ToString());


                string Need;
                Need = myDR["Need"].ToString();
                if (Need == "True")
                {
                    tb.BackColor = System.Drawing.Color.Yellow;

                }
                else
                {
                    tb.BackColor = System.Drawing.Color.White;
                }

                tb.Height = 15;
                tb.Width = 100;
                Panel2.Controls.AddAt(i, tb);

                i++;

            }

        }
        myDR.Close();
        myConn.Close();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

厦门德仔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值