大家好,这个代码给了我数组超出了数组错误的界限,并指向这里“if(!objReader.IsDBNull(i))”。此脚本旨在以txt格式打印。任何帮助将不胜感激:)
namespace test
{
public partial class frmSales : Form
{
public frmSales()
{
InitializeComponent();
}
private void dtpFrom_ValueChanged(object sender, EventArgs e)
{
}
private void btnExtract_Click(object sender, EventArgs e)
{
SqlConnection objConn = new SqlConnection("Data Source=asdasd;Initial Catalog=Medprac;Persist Security Info=True;User ID=sa;Password=");
objConn.Open();
SqlCommand objCmd = new SqlCommand("SELECT CONVERT(char(80), inv.[InvDate],3) AS InvDate,inv.[InvoiceNo],inv.[TaxAmount] + inv.[SubTotal] AS Amount, '' AS Payment FROM [Invoice] inv LEFT JOIN [PatientDetails] tab ON inv.[MedicalRecordID] = tab.[MedicalRecordID] WHERE (inv.[InvDate] >= CONVERT(datetime, '" + dtpFrom.Text + "', 105 )) AND (inv.[InvDate] <= CONVERT(datetime, '" + dtpTo.Text + "', 105))", objConn);
SqlDataReader objReader;
objReader = objCmd.ExecuteReader();
System.IO.FileStream fs = new System.IO.FileStream("C:\\CMSExportedData\\Sales-" + DateTime.Now.ToString("dd-MM-yyyy") + ".txt", System.IO.FileMode.Create);
System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.Default);
int count = 0;
while (objReader.Read())
{
for (int i = 0; i < 5; i++)
{
if (!objReader.IsDBNull(i))
{
string s;
s = objReader.GetDataTypeName(i);
//MessageBox.Show(s);
if (objReader.GetDataTypeName(i) == "char")
{
sw.Write(objReader.GetString(i));
}
else if (objReader.GetDataTypeName(i) == "money")
{
sw.Write(objReader.GetSqlMoney(i).ToString());
}
else if (objReader.GetDataTypeName(i) == "nvarchar")
{
sw.Write(objReader.GetString(i));
}
}
if (i < 4)
{
sw.Write("\t");
}
}
count = count + 1;
sw.WriteLine();
}
sw.Flush();
fs.Close();
objReader.Close();
objConn.Close();
MessageBox.Show(count + " records exported successfully.");
this.Close();
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void dtpTo_ValueChanged(object sender, EventArgs e)
{
}
private void frmSales_Load(object sender, EventArgs e)
{
}
}
}
答案 0 :(得分:1)
你的select语句查询4列,但你的for循环覆盖列0,1,2,3,4:这是五列,所以i = 4
超出界限。
尝试for (int i = 0; i < 4; i++)
答案 1 :(得分:1)
您的SqlCommand具有以下SQL语句
SELECT
CONVERT(char(80), inv.[InvDate],3) AS InvDate,
inv.[InvoiceNo],
inv.[TaxAmount] + inv.[SubTotal] AS Amount,
'' AS Payment
FROM
...
返回4个值(索引0到 3 )但你的for循环从索引0变为 4