且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从下拉列表中将选定的值传递给数据库?

更新时间:2023-02-11 20:26:44

假设你的 DetailsView DataSourceID 属性设置为SqlDataSource1,您不需要处理 ItemInserting 代码隐藏中的事件。 <%#Bind(...)%> 语句会自动将所选值传递给数据源控件上的参数。




编辑:尝试将填充列表的代码移动到 Init 事件中控制。这将为您提供与声明标记中的项目相同的结果:

Assuming your DetailsView has its DataSourceID property set to "SqlDataSource1", you don't need to handle the ItemInserting event in the code-behind. The <%# Bind("...") %> statements will automatically pass the selected values to the parameters on the data-source control.


Try moving the code which populates the lists to the Init event of the control. This will give you the same result as declaring the items in the markup:
<InsertItemTemplate>
    <asp:DropDownList ID="DropDownListDay" runat="server" 
        Width="50px" SelectedValue='<%# Bind("BirthDateDay") %>' 
        OnInit="DayList_Init"
    />
    <asp:DropDownList ID="DropDownListMonth" runat="server" 
        Width="50px" SelectedValue='<%# Bind("BirthDateMonth") %>'
        OnInit="MonthList_Init"
    />
    <asp:DropDownList ID="DropDownListYear" runat="server" 
        Width="70px" SelectedValue='<%# Bind("BirthDateYear") %>'
        OnInit="YearList_Init"
    />
</InsertItemTemplate>




protected void DayList_Init(object sender, EventArgs e)
{
    var list = (DropDownList)sender;
    for (int i = 1; i < 32; i++)
    {
        list.Items.Add(new ListItem(i.ToString());
    }
}

protected void MonthList_Init(object sender, EventArgs e)
{
    var list = (DropDownList)sender;
    for (int i = 1; i < 13; i++)
    {
        list.Items.Add(new ListItem(i.ToString());
    }
}

protected void YearList_Init(object sender, EventArgs e)
{
    var list = (DropDownList)sender;
    for (int i = 1300; i < 1396; i++)
    {
        list.Items.Add(new ListItem(i.ToString());
    }
}