0

在我的网页中,我有 2 个列表框,即 ListBox1、ListBox2。用户从 ListBox1 中选择项目列表并将其移动到 ListBox2。我做到了这一点,但是在我单击“保存”按钮后,它不会将 ListBox2 选定项保存在 SQL 表中,也不会引发任何错误!!怎么存放呢?

    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();
        }
    }
4

1 回答 1

2

您需要cmd.ExecuteNonQuery()在将参数添加到 sql 过程后调用。这将实际运行您的 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();
    }
于 2012-07-16T11:37:42.747 回答