DataReader错误 - “行/列没有数据” - 数据存在时?

时间:2012-10-07 22:23:36

标签: c# sql-server-ce

我需要一些帮助来理解我的错误。我想从表中读取数据,但是我收到错误,例如“行/列没有数据”。我不明白,因为我实际上有行和列。的WinForms。谢谢!

    //this is how i insert data into table, works fine 
    public void b1_Click(object sender, EventArgs e)
    {
        SqlCeCommand command = new SqlCeCommand("INSERT INTO tbl1(Name, LastName) VALUES (@Name, @LastName)", conn);
        command.Parameters.AddWithValue("@Name", l1.Text);
        command.ExecuteNonQuery();
    }

    //this is how i try to read data from the same table
    public void b2_Click(object sender, EventArgs e)
    { 
       SqlCeConnection conn = new SqlCeConnection(@"Data Source=C:test.sdf");
       conn.Open();
       SqlCeCommand command = new SqlCeCommand("SELECT * FROM  tbl1", conn);
       SqlCeDataReader reader = command.ExecuteReader();

       //error here
       string Name = reader.GetString(0);
       label.Text = Name;
    }

2 个答案:

答案 0 :(得分:1)

问题在于您的搜索结果。

SqlCeDataReader reader = command.ExecuteReader();

while (reader.Read())
{
   string Name = reader.GetString(0);
}

因此,您使用Read方法迭代结果。或者,如果您只有一个结果,那么您也可以使用ExecuteScalar

string Name = reader.ExecuteScalar().ToString();

答案 1 :(得分:1)

按此顺序

    SqlCeCommand command = new SqlCeCommand("INSERT INTO tbl1(Name, LastName) VALUES (@Name, @LastName)", conn);
    command.Parameters.AddWithValue("@Name", l1.Text);
    command.ExecuteNonQuery();

您没有设置第二个参数@LastName,因此它应该失败。如果您之前没有表中的记录,则无需选择任何内容。

那,以及你没有打电话reader.Read()

的事实