【问题标题】:C# Select item from list and then get item from SQL Server CE databaseC# 从列表中选择项目,然后从 SQL Server CE 数据库中获取项目
【发布时间】:2013-09-15 17:21:35
【问题描述】:

我正在做一些事情,需要从列表视图中进行选择,然后根据第 1 列(或 ii)从 SQL Server 数据库中选择项目,然后将其重写到本地数据表以处理成文本文件。到目前为止,这是我所拥有的:

var con = new SqlCeConnection(ConfigurationManager.ConnectionStrings[Connection.ConnectionStrings.CurrentConnection].ConnectionString);

foreach (ListViewItem item in LSTAsset.SelectedItems)
{
    for (int ii = 0; ii < LSTAsset.SelectedItems.Count; ii++)
    {

        string select = LSTAsset.SelectedItems[ii].Text;

        if (con != null && con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        var cmd = new SqlCeCommand("Select assetname, serial from asset where        assetname like '%" + select + "%'", con);
        SqlCeDataAdapter dataadapt = new SqlCeDataAdapter(cmd);
        //DataTable datatable = new DataTable();

        if (ii == 0)
        {
            dataadapt.Fill(steve.iTable);
        }

        if (ii < 0)
        {
            dataadapt.Update(steve.iTable);
        }
    }
}

Now my issue being, it seems to double the selected items when more than one item is selected.假设您选择了 2 个项目,它现在通过代码运行 4 次,并在数据表中为您提供 4 行。为什么代码加倍?它稍后会破坏输出文件,因为它会在表中写入 2 倍所需的行。

【问题讨论】:

    标签: c# .net sql sql-server-ce


    【解决方案1】:

    您似乎不必要地循环了两次 (SelectedItems.Count)。

    尝试移除内循环或外循环,例如:

    foreach (ListViewItem item in LSTAsset.SelectedItems)
    

    原因是因为下一条语句通过for 循环而不是foreach 执行相同的操作,并且您将连接到数据库n times * 2,其中n 是选定项数数。

    【讨论】:

    • 哦,是的,我现在明白了,我没想到 for (int i) 也在循环。愚蠢的错误。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    相关资源
    最近更新 更多