1

I have a database that stores invoice information. Each invoice can have up to 5 jobs relation, each job has a unique id number.

I've performed a select statement selecting all jobs relevant to a single invoice.

I have tried many ways to read the selected job id and store them in a jobArray. I would prefer to have it selecting using a for loop but most of the ways I've tried use textBoxes (which I replaced with my array)

This is my most recent code;

     SqlCeCommand cmdCountJobs = new SqlCeCommand("SELECT COUNT(Job_ID)AS INVCOUNT FROM Invoice WHERE Invoice_Number = " + maxInvoice + " ", cn);
        cmdCountJobs.Connection = cn;
        reader = cmdCountJobs.ExecuteReader();
        while (reader.Read())
        {
            countValue = Convert.ToInt32(reader["INVCOUNT"].ToString());
        }         
        SqlCeCommand cmdJobSearch = new SqlCeCommand("SELECT Job_ID as ID FROM Invoice WHERE Invoice_Number = " + maxInvoice + " ", cn);
        cmdJobSearch.Connection = cn;
        reader = cmdJobSearch.ExecuteReader(); 
        SqlCeDataAdapter da = new SqlCeDataAdapter(cmdJobSearch);
        jobArray[0] = (reader.Read()) ? reader["ID"].ToString() : "";
        jobArray[1] = (reader.Read()) ? reader["ID"].ToString() : "";
        jobArray[2] = (reader.Read()) ? reader["ID"].ToString() : "";
        jobArray[3] = (reader.Read()) ? reader["ID"].ToString() : "";
        jobArray[4] = (reader.Read()) ? reader["ID"].ToString() : "";   
        }

Could you help me with this?

4

1 回答 1

4

为什么要使用数组?您可以使用 aList(Of Int)使用普通循环来存储 ID 号。
鉴于列表的性质,您不需要事先知道设置数组大小的作业数量,因此您可以拥有只有 4 个作业或 6 个作业的发票,但您的代码逻辑不需要检查这个。

    List<int> jobs = new List<int>();
    SqlCeCommand cmdJobSearch = new SqlCeCommand("SELECT Job_ID as ID FROM Invoice " + 
                                "WHERE Invoice_Number = @ivc", cn);
    cmdJobSearch.Connection = cn;
    cmdJobSearch.Parameters.AddWithValue("@ivc", maxInvoice);
    reader = cmdJobSearch.ExecuteReader(); 
    while(reader.Read())
         jobs.Add(Convert.ToInt32(reader["ID"]));

另请注意,我已更改您的查询以避免字符串连接。可能情况并非如此,但使用参数化查询来避免Sql Injection是一个好习惯

当然,如果您需要在代码的其余部分的某处使用数组,您可以像数组一样轻松引用列表

   TextBox1.Text = jobs[0].ToString();

或将列表转换回数组

   int[] ids = jobs.ToArray();
于 2013-05-03T13:29:30.767 回答