OnButtonClick在特定位置重复指定的代码

时间:2013-08-26 00:19:42

标签: c# asp.net webforms

标题解释得很好,但是为了冗余。我试图点击按钮,在页面上生成代码(当然是定义的代码)。

protected void AddButton_Click(object sender, EventArgs e)
    {

    }

我希望它生成的代码将添加2个下拉列表,它将自动增加1它生成的下拉列表ID,还需要根据SQL查询在数据库中创建一个表。

<asp:DropDownList ID="DropDownList" runat="server" AppendDataBoundItems="True" DataSourceID="box_1" DataTextField="box_1" ToolTip="Checkbox #1" AutoPostBack="True" OnSelectedIndexChanged="DropDownList_SelectedIndexChanged">
            <asp:ListItem Text="--Select One--" Value="" />

        </asp:DropDownList>

修改

protected void AddButton_Click(object sender, EventArgs e)
    {
        int a = 0;
        string x = dropdowncounter.Value;

        a = Convert.ToInt16(x);
        a = a + 1;
        dropdowncounter.Value = a.ToString();
        DropDownList DropDownList1 = new DropDownList(){
            // Set the DropDownList's Text and ID properties.
            Text = "DropDownList", 
            ID = "DropDownList" + a.ToString(),
            DataSourceID = "Box_1",
            DataTextField = "box_1",
            ToolTip = "Check Box Added!"
        };
        //addoptions1 = DropDownList1;
        //addoptions.Controls.Add(myDropDownList);
        //// Add a spacer in the form of an HTML <br /> element.
        //addoptions.Controls.Add(new LiteralControl("<br />"));



    }

这就是我到目前为止所做的事情,我觉得我很接近我需要的功能(虽然我没有看到任何新的Drop Down盒子。)。有什么帮助吗?

2 个答案:

答案 0 :(得分:0)

protected void AddButton_Click(object sender, EventArgs e)
{
    int count = DropDownList.Items.Count + 1;
    DropDownList.Items.Add(count.ToString(),count.ToString());
}

这是你想要的吗?

答案 1 :(得分:0)

这是你需要的吗?

 SqlConnection con = new SqlConnection(s);
 SqlCommand cmd = new SqlCommand("select FieldName from TableName", con);
 SqlDataAdapter sda = new SqlDataAdapter(cmd);
 DataSet ds = new DataSet();
 sda.Fill(ds);
 DropDownList1.DataSource = ds;
 DropDownList1.DataTextField = "FieldName";                          
 DropDownList1.DataValueField = "FieldName";
 DropDownList1.DataBind();