日期:2014-05-17  浏览次数:20507 次

DropDownList二级联动问题
我页面上有两个DropDownList控件,,两个控件的数据都是从数据库里读取出来的,,DropDownList2是DropDownList1控件触发来显示的,,但我把两个控件上选择的值传到服务器上的时候DropDownList2读入进去只是第一项,,我先其他项也是第一项读进数据库。。请问这是什么原因。。代码如下。。。
Sub Page_Load(sender As Object, e As EventArgs)
if not ispostback then
dpbind()
end if
   
end sub
sub dpbind()
 Dim sqlstr, aa As String
conn.open()
sqlstr="select * from dg1"
dim cmd as new OleDbCommand(sqlstr,conn) 
dim sdr as OleDbDataReader = cmd.ExecuteReader()
DropDownList1.Items.Add(New ListItem("请选择大类",""))
DropDownList2.Items.Add(new ListItem("请选择小类", ""))
 While sdr.Read()
  DropDownList1.Items.Add(New ListItem(sdr("datag").ToString(),sdr("dataid").ToString()))
 End While
  sdr.Close()
  conn.Close()

end sub

Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
  dim sqlstr as string
  if DropDownList1.SelectedValue <> "" then
Dim cmd As New OleDbCommand("select * from dg2 where dgid =" & DropDownList1.SelectedValue & "", conn)
  conn.Open()
  dim dr as OleDbDataReader = cmd.ExecuteReader()
  DropDownList2.DataSource = dr
  DropDownList2.DataTextField = "datag2"
  DropDownList2.DataValueField = "dgid"
  DropDownList2.DataBind()

  conn.Close()
else
RegisterStartupScript("aa","<script>alert('请选择大类');" + "</" + "script>")
end if 
End Sub 

Sub Enter_Click(Sender As Object, E As EventArgs)
dim aa, bb as string
aa = DropDownList1.SelectedItem.Text
bb = DropDownList2.SelectedItem.Text
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.Mappath("data/khgl.mdb"))
  Dim sql, times As String
  sql = "insert into namelist(name,age,sex,phone,email,address,dg1,dg2,type,subtime) values('" & TextBox1.text & "','" & TextBox2.text & "','" & RadioButtonList.selecteditem.text & "','" & TextBox9.text & "','" & TextBox4.text & "','" & TextBox3.text & "','" & aa & "','" & bb & "','" & TextBox6.text & "','" & now() & "')"
  Dim cmd As New OleDbCommand(sql, conn)
  conn.Open()
  cmd.ExecuteNonQuery()
  conn.Close()
TextBox1.text = ""
TextBox2.text = ""
TextBox3.text = ""
TextBox4.text = ""

TextBox6.text = ""
TextBox9.text = ""
  RegisterStartupScript("aa","<script>alert('客户资料添加成功!');" + "</" + "script>")
End Sub

------解决方案--------------------
原因如下
你选DropDownList1是一个服务器端事件,并且是立刻回传把DropDownList2给动态填充的,而DropDownList2的选择是客户端事件,因此读出来的是填充的时候默认的第一项是被选值
用Request.form来获取DropDownlist2的取值就好了