문제

채워진 약 10 개의 드롭 다운 목록 컨트롤이 있습니다. 각각의 몇 가지 필드를 복사/붙여 넣기 및 수정하는 대신 프로그래밍 방식으로 만들고 싶습니다. 이 작업을 수행 할 수 있습니까?

여기에 그들 중 하나가 어떻게 생겼는지입니다. 프로그래밍 방식으로 10 개의 드롭 다운리스트 컨트롤과 해당 SQLDATASOURCE 컨트롤을 추가하고 싶습니다.

   <asp:SqlDataSource ID = "ddlDAGender" runat=server
    ConnectionString="<%$ ConnectionStrings:test1ConnectionString %>" 
    SelectCommand = "select GenderID,Gender from mylookupGender"
    >
    </asp:SqlDataSource>


 <asp:Label ID="Label3" runat="server" Text="Gender"></asp:Label>

        <asp:DropDownList ID="ddlGender" runat="server" 
                DataSourceid="ddlDAGender"
                DataTextField="Gender" DataValueField="GenderID"

    >

 </asp:DropDownList>
도움이 되었습니까?

해결책

항상 컨트롤을 동적으로 만들 수 있습니다. 이 경우 모든 드롭 다운 목록이 다르면 개별 ID 및 데이터 소스를 여전히 지정해야하므로 아무것도 저장하고 있는지 확실하지 않습니다.

코드의 모습은 다음과 같습니다.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindDropDownLists();
    }
}

protected void Page_Init(object sender, EventArgs e)
{ 

        SqlDataSource sqlDS = new SqlDataSource();
        sqlDS.ConnectionString = ConfigurationManager.ConnectionStrings[0].ToString();
        sqlDS.SelectCommand = "select GenderID,Gender from mylookupGender";
        form1.Controls.Add(sqlDS);

        DropDownList ddl = new DropDownList();
        ddl.ID = "dddlGender";
        ddl.DataSource = sqlDS;
        ddl.DataTextField = "Gender";
        ddl.DataValueField = "GenderID";
        form1.Controls.Add(ddl);

        // ... Repeat above code 9 times or put in a for loop if they're all the same...
}

private void BindDropDownLists()
{
    foreach (Control ctl in form1.Controls)
    {
        if (ctl is DropDownList)
        {
            (ctl as DropDownList).DataBind();
        }
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top