如何通过ID显示或获取Access数据库的所有名称

我的数据库上有10个联系人,但ID却没有从1到10排列,就像1 2 3 5 6 8...。我在单击lll1时像lll1 ++一样增加了按钮的设置,并取lll1值为ID,因此可以通过单击按钮来显示联系人,但是例如当到达4或7时(1 2 3 5 6 8 ....) 表单停止并显示“值不能为空”错误,如果没有值,可以跳过数字 另外,当数据库ID像10次接触后完成时(当我按下按钮并且lll1增加到11并且数据库没有接触11时),它显示相同的错误值不能为null,请帮助我,这对我很重要谢谢

private void button6_Click(object sender,EventArgs e)
{
     OleDbConnection cn = new OleDbConnection();
     cn.ConnectionString = @"Provider=microsoft.ACE.OLEDB.12.0;Data Source=Database9.accdb";
     OleDbCommand cmd = new OleDbCommand();
     cn.Open();
     cmd.Connection = cn;
     cmd.CommandText = "Select * from Contacts where ID=" + lll1.Text;
     OleDbdataReader reader = cmd.ExecuteReader();

     string sql = "select Attachments.FileData from Contacts where ID =" + lll1.Text;
     OleDbCommand vcom = new OleDbCommand(sql,cn);
     byte[] ImageByte = (byte[])vcom.ExecuteScalar(); //contains 20 extra bytes
     MemoryStream MemStream = new MemoryStream(ImageByte.Skip(20).ToArray()); //Read bytes starting at position 20
     Image image = Image.FromStream(MemStream); 
     pictureBox1.Image = image;
     while (reader.Read())
     {
         fl1.Text = reader.GetString(reader.GetOrdinal("First Name"));
     }
     cn.Close
}
public int o { get; set; }
private void button5_Click(object sender,EventArgs e)
{          
    o++;
    lll1.Text = o.ToString();
    button6_Click(sender,e);
}

  `   string sql = "select Attachments.FileData from Contacts where ID =" + 
       lll1.Text;
         if (DBNull.Value.Equals("Attachments.FileData"))
                {
            MessageBox.Show("no value");
                }
         else
                {
            OleDbCommand vcom = new OleDbCommand(sql,cn);
            byte[] ImageByte = (byte[])vcom.ExecuteScalar(); //contains 20 
            extra bytes
            MemoryStream MemStream = new 
            MemoryStream(ImageByte.Skip(20).ToArray()); //Read byte starting at position 20
            Image image = Image.FromStream(MemStream); 
            pictureBox1.Image = image;
            }`
chiichi 回答:如何通过ID显示或获取Access数据库的所有名称

您需要检查ExecuteScalar是否返回NULL。

            var result = vcom.ExecuteScalar(); //contains 20 extra bytes
            if (result != null && result != DBNull.Value)
            {
                byte[] imageByte = result as byte[];

                if (imageByte.Length > 20)
                {
                    using (MemoryStream memStream = new
                        MemoryStream(imageByte.Skip(20).ToArray())) //Read byte starting at position 20
                    {
                        Image image = Image.FromStream(memStream);
                        pictureBox1.Image = image;
                    }
                }
            }
            else
            {
                MessageBox.Show("No image");
            }

查看其余的代码,请考虑使用在上下文中有意义的对象/控件名称,例如避免使用lll1,button5,buton6等。

了解ExecuteScalar here

还要考虑使用参数化的SQL查询,请阅读here

最后,将连接对象cn封装在using语句中。

本文链接:https://www.f2er.com/3166275.html

大家都在问