C#下拉列表值不插入

时间:2012-06-25 06:57:09

标签: c#

我已经编写了一个代码来加载数据到下拉列表,因为我写了它已加载,但在尝试插入下拉列表的值时,(我的意思是selectedItem.text)它不会插入,而是已插入thtat selectedIndex = 0。请纠正我。

//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 -Select-dsad AGEAcwBkAGY =

2 -Select-da AGEAZA ==

1 个答案:

答案 0 :(得分:0)

每次我们使用DropDownlist时,最佳方法都是选择值, 尝试使用: 将DataSource设置为reader并执行DataBind()

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