如何通过单击按钮将列表框中的多个项目添加到数据库中?

时间:2016-02-18 05:23:13

标签: c#

我想在一个提交按钮上从listbox同时向数据库添加两个或更多选定项目。我可以逐个添加项目,但不能一次添加所有项目。请帮帮我。

我把它放在' for'循环,但当循环第二次执行时,它向我显示"输入字符串格式不正确的异常"

2 个答案:

答案 0 :(得分:0)

using (var command = <your data provider command>)
{
    command.CommandType = CommandType.Text;
    // preferably - parameterize your command
    command.Parameters.Add(....); 
    . . . . . . . .
    //
    foreach (var item in lst.SelectedItems)
    {
        var sql = "Insert into tbl (a,b,c) values (. . use your list values here OR parameter names. .)";
        command.CommandText = sql;
        // if parameterizing 
        command.Parameters[name/index].Value = (....); 
        // ---
        command.ExecuteNonquery();

    }
}

可选 - 如果需要ALL-OR-NOTHING - 使用交易。

坦率地说,我的回答和问题一样好

答案 1 :(得分:0)

如果使用选中列表框,则可以将代码放在for循环中。这将在单击按钮上添加两个或更多数据

string checkedMonths = "";
    public void GetCheckedMonths()                                              //To get all checked Months
    {
        string c = "";
        for (int i = 0; i < checkedListBoxMonths.Items.Count; i++)
        {
            if (checkedListBoxMonths.GetItemChecked(i))
            {
                c = (string)checkedListBoxMonths.Items[i].ToString();
                checkedMonths = checkedMonths +", "+ c;                         //TO add selected moths with , in between them
            }
        }
    }

根据您的需要修改上述代码。在这里,我将两个或多个值作为单个字符串插入到列的单个单元格中。在for循环中根据需要修改......

相关问题