ASP中的必填字段验证器.NET在Codebehind中设置时无法捕获下拉列表中的初始值

本文关键字:下拉列表 Codebehind 字段 验证 ASP NET 设置 | 更新日期: 2023-09-27 18:06:51

我刚刚开始从数据库中的表填充我的DropDownList的项目。自从我删除了硬编码的项目,并开始使用自动填充的项目,我的RequiredFieldValidator似乎没有注意到,当我按下提交时,InitalValue仍然被选中。

在我从表中拉出项目后,我将初始值"Select Genre"放置。

这是我的下拉列表和我的验证器:

<strong>Genre:</strong>
<asp:DropDownList ID="ddlGenres" runat="server"></asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvGenres" runat="server" ControlToValidate="ddlGenres" InitialValue="Select Genre" ErrorMessage="You must pick a genre." ForeColor="Red"></asp:RequiredFieldValidator>

下面是我用来填充下拉列表的代码:

//Code Outside of my method
static string connString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
private void populateddlGenres()
    {
        try
        {
            SqlCommand cmdGenre = new SqlCommand();
            cmdGenre.CommandText = "Select * From Genre";
            cmdGenre.Connection = conn;
            conn.Open();
            DataTable dt = new DataTable();
            dt.Load(cmdGenre.ExecuteReader());
            conn.Close();
            ddlGenres.DataSource = dt;
            ddlGenres.DataTextField = "GenreText";
            ddlGenres.DataValueField = "GenreValue";
            ddlGenres.DataBind();
        }
        catch (Exception ex)
        {
            // Handle the error
        }
        ddlGenres.Items.Insert(0, new ListItem("Select Genre", "0"));
    }

ASP中的必填字段验证器.NET在Codebehind中设置时无法捕获下拉列表中的初始值

将文本字段放在InitialValue上。

InitialValue="0"将解决