-1

我可以从数据库中检索数据并且它现在可以工作,但仅在第一行(描述代码都是正确的并且基于数据库)。

在第二行,描述不是基于数据库的,而是显示第一行的描述,即使第一行和第二行的代码不同。我该如何解决?

这是一些代码:

private void UpdateDatas()
{
  int codeValue = 0;

  OleDbDataReader dReader;
  OleDbConnection conn = new OleDbConnection(connectionString);
  conn.Open();
  OleDbCommand cmd = new OleDbCommand(
    "SELECT [Description], [Price] FROM [Data] WHERE [Code]=@Code", conn);

  cmd.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);
  cmd.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);

  if (int.TryParse(this.textBoxCodeContainer[0][0].Text, out codeValue))
  {
    cmd.Parameters["Code"].Value = codeValue;
  }
  else if (int.TryParse(this.textBoxCodeContainer[0][1].Text, out codeValue))
  {
    cmd.Parameters["Code"].Value = codeValue;
  }
  else
  {
    MessageBox.Show("Error");
  }

  dReader = cmd.ExecuteReader();

  while (dReader.Read())
  {
    if (textBoxCodeContainer[0][0].TextLength != 0)
    {
      this.textBoxDescContainer[0][0].Text = dReader["Description"].ToString();
      this.textBoxSubTotalContainer[0][0].Text = dReader["Price"].ToString();
    }

    if (textBoxCodeContainer[0][1].TextLength != 0)
    {
      this.textBoxDescContainer[0][1].Text = dReader["Description"].ToString();
      this.textBoxSubTotalContainer[0][1].Text = dReader["Price"].ToString();
    }
  }

  dReader.Close();
  conn.Close();
 }

这是图像: 第一行的代码是

这是数据库的图像: 在此处输入图像描述

4

1 回答 1

1

那是因为您在循环中为两个文本框处理了两次第一次记录。试试这个作为一个快速修复:

int index = 0;
while (dReader.Read())
{
  if (textBoxCodeContainer[0][index].TextLength != 0)
  {
    this.textBoxDescContainer[0][index].Text = dReader["Description"].ToString();
    this.textBoxSubTotalContainer[0][index].Text = dReader["Price"].ToString();
  }

  index += 1;
}

第二个问题是您在查询中为一个参数(代码)添加了两个值,因此选择的结果将只包含一行。您应该使用“IN”SQL 关键字。第二个快速修复将涉及您的查询:

var query = "SELECT [Description], [Price] FROM [Data] WHERE [Code] IN (";

 if (int.TryParse(this.textBoxCodeContainer[0][0].Text, out codeValue))
 {
 query = query + codeValue.ToString();
 }
 if (int.TryParse(this.textBoxCodeContainer[0][1].Text, out codeValue))
 {
 query = query + "," + codeValue.ToString();
 }

 query = query + ")";

 OleDbCommand cmd = new OleDbCommand(query, conn);
 dReader = cmd.ExecuteReader();

如何使用“IN”子句对查询进行参数化是另一个问题——这只是一个快速解决方案以使其工作。

于 2013-08-16T07:37:27.113 回答