C#使用Datareader在DataGridView上添加Item

时间:2015-02-27 23:23:32

标签: c# winforms datagridview datareader

我有一个问题,我想在datagridview中使用datareader添加一个项目,我只能添加一次,如果我再添加一个,那就错了。 这是我的代码:

connect = new OleDbConnection(coo);
connect.Open();

command.Connection = connect;
DataTable dt = new DataTable();
OleDbDataAdapter ODA = new OleDbDataAdapter
("SELECT * FROM Items where itemno = '" + textBox1.Text + "'", connect);
ODA.Fill(dt);

command.CommandText = "SELECT * FROM Items";
OleDbDataReader reader = command.ExecuteReader();
object[] obj = new object[256];

while (reader.Read())
{
    reader.GetValues(obj);
    if ((textBox1.Text == obj[0].ToString()))
    {
        if (dataGridView1.DataSource == null)
            dataGridView1.DataSource = dt;
        else
            ((DataTable)dataGridView1.DataSource).Merge(dt);

        int sum1 = 0;
        for (int i = 0; i < dataGridView1.RowCount; i++)
        {
            sum1 += Convert.ToInt32(dataGridView1.Rows[i].Cells[3].Value);
        }
        textBox2.Text = sum1.ToString();
        break;
    }
    else if (textBox1.Text==null)
    {
        break;
    }
}
reader.Close();
connect.Close();

错误显示为

错误:

"Input string was not in a correct format"

sum1 += Convert.ToInt32(dataGridView1.Rows[i].Cells[3].Value); ...

我想要的只是我想在datagridview添加的项目有它们的价格,并将它们全部添加到datagridview中,即文本框中的总数。 请帮帮我们..

0 个答案:

没有答案