好的,所以我有一个功能,可以根据数字在数据库中搜索记录,然后在数据网格中显示,这曾经工作正常,但出于某种原因,当我复制代码时,它现在会带来一个返回DB中的每一列(使用正确的数据)。例如,第1行只显示数据网格中的一行,但只显示第一列,然后第二行将包含前两列,依此类推....
无论如何,这是我的代码
dataGridView1.DataSource = null;
dataGridView1.Rows.Clear();
dataGridView1.Refresh();
string strprovider = @"BLANKED OUT INFO HERE";
string strsql = "Select * from OCR where OCR like '" + textBox4.Text + "%'";
OleDbConnection newConn = new OleDbConnection(strprovider);
OleDbCommand dbCmd = new OleDbCommand(strsql, newConn);
newConn.Open();
dbCmd.CommandType = CommandType.Text;
OleDbDataReader dr = dbCmd.ExecuteReader();
if (textBox4.Text == "")
{
MessageBox.Show("Please Enter a Valid OCR Number", "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else
{
if (dr.HasRows)
{
// ....
}
else
{
MessageBox.Show("No Record Found", "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
int columncount = dr.FieldCount;
string[] rowdata = new string[columncount];
while (dr.Read())
{
for (int k = 0; k < columncount; k++)
{
switch (dr.GetFieldType(k).ToString())
{
case "System.Int32":
rowdata[k] = dr.GetInt32(k).ToString();
break;
case "System.DateTime":
rowdata[k] = dr.GetDateTime(k).ToString();
break;
case "System.String":
rowdata[k] = dr.GetString(k);
break;
}
dataGridView1.Rows.Add(rowdata);
}
}
}
}
答案 0 :(得分:1)
尝试在for循环后添加行:
while (dr.Read())
{
for (int k = 0; k < columncount; k++)
{
switch (dr.GetFieldType(k).ToString())
{
case "System.Int32":
rowdata[k] = dr.GetInt32(k).ToString();
break;
case "System.DateTime":
rowdata[k] = dr.GetDateTime(k).ToString();
break;
case "System.String":
rowdata[k] = dr.GetString(k);
break;
}
//dataGridView1.Rows.Add(rowdata); <= This shouldn't be here
}
//Add row after loop completes all columns
dataGridView1.Rows.Add(rowdata);
}