2012-06-25 72 views
0

我寫了一個代碼來加載數據下拉列表,因爲我寫它被加載,但試圖插入下拉列表中的值(我的意思是selectedItem.text)它將不會插入,而是如果已單獨插入selectedIndex = 0。請糾正我。C#下拉列表值不插入

//Load the name to Drop down list 
     public void name() 
     { 
      DropDownList1.Items.Clear(); 
      ListItem i = new ListItem(); 
      i.Text = "-Select-"; 
      DropDownList1.Items.Add(i); 
      DropDownList1.SelectedIndex = 0; 
      Conhr.Open(); 
      string s; 
      s = "select EmployeeName from tbl_EmploeeDetails where SiteName='" + Label5.Text + "' "; 
      SqlCommand cd = new SqlCommand(s, Conhr); 
      SqlDataReader dr; 
      dr = cd.ExecuteReader(); 
      while (dr.Read()) 
      { 
       ListItem m= new ListItem(); 
       m.Text = dr["EmployeeName"].ToString().Trim(); 
       DropDownList1.Items.Add(m); 
      } 
      dr.Close(); 
      Conhr.Close(); 
     } 


//trying to insert the data for drop down list 



    protected void Button1_Click(object sender, EventArgs e) 
     { 
         con.Open(); 
         string a; 
         a = "insert into tbl_KKSUser(EName,Uname,Password)values(@en,@un,@pas)"; 
         SqlCommand cm = new SqlCommand(a, con); 
         SqlParameter paramName; 
         paramName = new SqlParameter("@en", SqlDbType.VarChar, 25); 
         paramName.Value = DropDownList1.SelectedItem.Text; 
         cm.Parameters.Add(paramName); 
         cm.ExecuteNonQuery(); 
         con.close 
     } 

答案將是這樣的數據基礎

1 - 選擇 - DSAD AGEAcwBkAGY =

2 - 選擇 - 噠AGEAZA ==

+1

你是否在'If(!IsPostBack)'子句中綁定了這個'name()'? – V4Vendetta

+0

@ V4Vendetta,我相信這是答案 – Habib

回答

0

每次我們與DROPDOWNLIST工作最佳方法是selectedvalue, 嘗試使用: 將DataSource設置爲閱讀器並執行DataBind()

conn.Open(); 
    SqlDataReader MyDataSet = cmd.ExecuteReader();  
    ddlClassList.DataSource = MyDataSet; 
    ddlClassList.DataTextField = "Field1"; 
    ddlClassList.DataValueField = "Field2"; 
    ddlClassList.DataBind(); 
    MyDataSet.Close(); 
    conn.Close();