C# プログラム用の SQL クエリを作成しましたが、クエリを実行しようとすると、このエラーが発生します。
System.IndexOutOfRangeException:
クエリの順序を変更して、それが唯一のものであるかどうかを確認しようとしましたが、これらの 3 つの列 ( 、、 )while (DRorder.Read())
のうち少なくとも 2 つを変換しようとするコードが にある場合にのみ、そのエラーが発生することに気付きました。ADRES
LEV
TAAL
// the code that gives the error
SqlCommand getlist = new SqlCommand("select * from BESW where BEST = @best", Connectie.connMEVO);
getlist.Parameters.Add("@best", SqlDbType.VarChar).Value = data.corrigeerbestnr;
DRorder = getlist.ExecuteReader();
while (DRorder.Read())
{
dateTimePicker1.Value = Convert.ToDateTime(DRorder["BESTEL"]);
dateTimePicker2.Value = Convert.ToDateTime(DRorder["PLAN"]);
comboBox2.Text = DRorder["ADRES"].ToString();
comboBox1.Text = DRorder["LEV"].ToString();
textBox8.Text = DRorder["TAAL"].ToString();
}
ただし、クエリを3つのほぼ同一のクエリに分割すると、エラーが発生する可能性のある3つの列のそれぞれが問題なく動作します。
// this is the code that im currently using without error
SqlCommand getlist = new SqlCommand("select BESTEL, [PLAN], ADRES from BESW where BEST = @best", Connectie.connMEVO);
getlist.Parameters.Add("@best", SqlDbType.VarChar).Value = data.corrigeerbestnr;
DRorder = getlist.ExecuteReader();
while (DRorder.Read())
{
dateTimePicker1.Value = Convert.ToDateTime(DRorder["BESTEL"]);
dateTimePicker2.Value = Convert.ToDateTime(DRorder["PLAN"]);
comboBox2.Text = DRorder["ADRES"].ToString();
}
SqlCommand getlist2 = new SqlCommand("select LEV from BESW where BEST = @best", Connectie.connMEVO);
getlist2.Parameters.Add("@best", SqlDbType.VarChar).Value = data.corrigeerbestnr;
DRorder = getlist2.ExecuteReader();
while (DRorder.Read())
{
comboBox1.Text = DRorder["LEV"].ToString();
}
SqlCommand getlist3 = new SqlCommand("select TAAL from BESW where BEST = @best", Connectie.connMEVO);
getlist3.Parameters.Add("@best", SqlDbType.VarChar).Value = data.corrigeerbestnr;
DRorder = getlist3.ExecuteReader();
while (DRorder.Read())
{
textBox8.Text = DRorder["TAAL"].ToString();
}
プログラム内の他のすべてのクエリが機能するため、なぜこれが行われるのかわかりません。テーブル全体を読み取るクエリもあり、それらのフィールドがwhile
ループに含まれていても問題はありません。
ここで私の質問は、これらのコード ブロックの 1 つが機能し、もう 1 つがエラーを出すのはなぜですか? そして、おそらくこれに対する解決策を知っている場合は、それを聞きたいと思います。すべてを1つのクエリにまとめた方がよいと思うからです。
Dispose
これらのコード ブロックにクエリを入れるのを忘れていたことはわかっています。
問題に関する追加情報: 単一のクエリ コードを実行すると、エラーが発生する列は次のとおりですが、列の順序を変更すると、これら 3 つ ( 、、 )LEV
のうち 2 番目の列で問題が発生します。ADRES
LEV
TAAL
編集:「新しい」コード (DB には 28 列あります)
// the code that gives the error
SqlCommand getlist = new SqlCommand("select * from BESW where BEST = @best", Connectie.connMEVO);
getlist.Parameters.Add("@best", SqlDbType.VarChar).Value = data.corrigeerbestnr;
DRorder = getlist.ExecuteReader();
while (DRorder.Read())
{
if (!DRorder.IsDBNull(10)) { dateTimePicker1.Value = Convert.ToDateTime(DRorder[10]); }
if (!DRorder.IsDBNull(11)) { dateTimePicker2.Value = Convert.ToDateTime(DRorder[11]); }
if (!DRorder.IsDBNull(7)) { comboBox1.Text = DRorder[7].ToString(); }
if (!DRorder.IsDBNull(8)) { comboBox2.Text = DRorder[8].ToString(); }
if (!DRorder.IsDBNull(25)) { textBox8.Text = DRorder[25].ToString(); }
}