将ListBox2项存储在SQL表中

时间:2012-07-16 11:35:10

标签: c# asp.net .net

在我的网页中,我有2个列表框,即ListBox1,ListBox2。用户从ListBox1中选择项目列表并将其移动到ListBox2。我完成了这个,但是在我点击之后'SAVE'按钮,它不是保存SQL表中的ListBox2选定项目而且它不会抛出任何错误!如何存放?

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
         lblPage1ID.Text=Server.UrlDecode(Request.QueryString["Parameter"].ToString());
         ListBoxWorksPackages();
        }
    }

    protected void ListBoxWorksPackages()
    {
        ListBox1.Items.Add("General Contractor");
        ListBox1.Items.Add("Architecture");
        ListBox1.Items.Add("Civil");
        ListBox1.Items.Add("Mechanical");
        ListBox1.Items.Add("Electrical");
    }

    protected void btnMoveRight1_Click(object sender, EventArgs e)
    {
        for (int i = ListBox1.Items.Count - 1; i >= 0; i--)
        {
            if (ListBox1.Items[i].Selected == true)
            {
                ListBox2.Items.Add(ListBox1.Items[i]);
                ListItem li = ListBox1.Items[i];
                ListBox1.Items.Remove(li);
            }
        }
    }

    protected void btnMoveLeft1_Click(object sender, EventArgs e)
    {
        for (int i = ListBox2.Items.Count - 1; i >= 0; i--)
        {
            if (ListBox2.Items[i].Selected == true)
            {
                ListBox1.Items.Add(ListBox2.Items[i]);
                ListItem li = ListBox2.Items[i];
                ListBox2.Items.Remove(li);
            }
        }
    }

    protected void BtnSave1_Click(object sender, EventArgs e)
    {
        SqlConnection SqlCon = new SqlConnection(GetConnectionString());

        string Packagevalues = string.Empty;
        foreach (ListItem item in ListBox2.Items)
        {
            if (item.Selected == true)
            {
               Packagevalues += "," + item.Text; 
            }
        }

        string query = "INSERT INTO Contractor_Info2 (Vendor_ID,WorksPackage) VALUES"
                           + "(@Vendor_ID,@WorksPackage )";

        try
        {
            SqlCommand cmd = new SqlCommand(query, SqlCon);
            cmd.CommandType = CommandType.Text;

            SqlCon.Open();

            cmd.Parameters.AddWithValue("@Vendor_ID", lblPage1ID.Text);
            cmd.Parameters.AddWithValue("@WorksPackage", Packagevalues);
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            SqlCon.Close();
        }
    }

1 个答案:

答案 0 :(得分:2)

在将参数添加到sql过程后,需要调用cmd.ExecuteNonQuery()。这就是实际运行sql语句的内容。

    try
    {
        SqlCommand cmd = new SqlCommand(query, SqlCon);
        cmd.CommandType = CommandType.Text;

        SqlCon.Open();

        cmd.Parameters.AddWithValue("@Vendor_ID", lblPage1ID.Text);
        cmd.Parameters.AddWithValue("@WorksPackage", Packagevalues);
        // add this
        cmd.ExecuteNonQuery();
    }