验证DropDownList的方法

验证DropDownList的方法
2007-10-26 10:52

源代码:

protected void Page_Load(object sender, EventArgs e)
            {       
                SqlConnection conn = Database.connection();
                conn.Open();
                string strType = "Select * From Type";
                SqlDataAdapter sdr1 = new SqlDataAdapter(strType,conn);
                DataSet ds = new DataSet();
                sdr1.Fill(ds,"Type");
                DataRow Dr = ds.Tables["Type"].NewRow();
                Dr[0] = "0";
                Dr[1] = "请选择一个类别";      
                ds.Tables["Type"].Rows.InsertAt(Dr, 0);
      
                this.DropDownList1.DataSource = ds.Tables["Type"].DefaultView;
                this.DropDownList1.DataValueField = ds.Tables["Type"].Columns[0].ToString();
                this.DropDownList1.DataTextField = ds.Tables["Type"].Columns[1].ToString();
                this.DropDownList1.DataBind();
                conn.Close();
            }

意欲:从数据库中读取Type值,将其绑定到DropDownList,在提交表单时,将DropDownList的Value值插入另一数据库,该Value值在这数据库中为外键。在实际的调试中,改变DropDownList,并没有改变Value的值,始终是按类别ID为1插入。新的要求要该项必选,默认为“请选择一个类别”,将该值加入DataSet后再绑定DropDownList,同时用RequiredFieldValidator,InitialValue="请选择一个类别"验证。在没选类别以默认“请选择一个类别”提交,验证得不到触发,插入中还是错误,信息为:

INSERT 语句与 FOREIGN KEY 约束"FK_Photo_Type"冲突。该冲突发生于数据库"52llb",表"dbo.Type", column 'Type_Id'。
语句已终止。

解决方案:
<asp:comparevalidator id="checkpwd" runat="server" Display="Dynamic" ControlToValidate="DropDownList1" Type="String"            ValueToCompare="0" Operator="NotEqual" ErrorMessage="图片必须有一个编目" ></asp:comparevalidator>

ControlToValidate = 要验证的dropdownlist
Type = 要验证的字符类型 (我的这里是验证字符串)
ValueToCompare = 要验证的字符串的值  
Operator="NotEqual" 不等于

现在我要验证的就是dropdownlist选择的值不等于“请选择一个类别”,否则提示:图片必须有一个编目这个方法唯一的不好就是只能验证DropDownList.SelectedValue 不能对SelectedItem.Text 进行验证!

备注:星期天,在阅读ASP.Net2.0书籍中发现,DropDownList在新增加的两个属性中,其中一个为AppendDataBoundItems,将其属性值设为“True”,可使动态绑定的数据项追加到静态声明的列表项上。从而取代以上代码中的红色代码部分

给想要验证DropDownList的同胞们分享!

原文地址:https://www.cnblogs.com/jxcia_Lai/p/1733548.html