简体   繁体   中英

C# Select item from list and then get item from SQL Server CE database

I am working on something that requires a selection to be made from a list view and then selects the item from a SQL Server database based on column 1 (or ii) and then rewrites it to a local datatable to be processed into a text file. Here's what I have so far:

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. Say you selected 2 items, it now runs though the code 4 times and gives you 4 rows in the datatable. Why is it doubling the code? It ruins the output file later as it writes 2x the needed rows in the table.

It looks like you are looping unnecessary twice ( SelectedItems.Count ).

Try removing the inner or outer loop, for example:

foreach (ListViewItem item in LSTAsset.SelectedItems)

The reason why is because the next statement is doing the same thing via a for loop rather than a foreach and you will connect to the database n times * 2, where n is the selected item count.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM