Getting data from MS Access database and display it in a listbox

后端 未结 7 853
伪装坚强ぢ
伪装坚强ぢ 2020-12-11 06:37

How do I read data in ms access database and display it in a listbox. I have the codes here but i got errors.

 private void button3_Click(object sender, Even         


        
7条回答
  •  忘掉有多难
    2020-12-11 07:15

    Thy using a While loop

    while(reader.Read())
    {
       listbox1.Items.Add(reader["FirstName"]);
    }
    

    This moves through all the rows you selected. reader.Read() returns false if there are no more rows.

    Also: if you Want to retrive valmue from a column I suggest you do it with the index ón the reader instance. Like my example.

    var value = reader["ColumnName"];
    

    This increases readability comparing to

    var value = reader.GetString(0);
    

    UPDATE

    If you want to only display the fist value - I suggest you use cmd.ExecuteScalar() and the adapt you sql to only return the value you need:

    using(OleDbCommand cmd = new OleDbCommand("SELECT firstname from TableAcct", conn))
    {
       conn.Open();
       var firstName = cmd.ExecuteScalar();
    }
    

    Be aware the this will give you the first "FirstName" in the table. And since there is no "order by firstname" or "where someKey = 1" - this might not rturn that you expected.

提交回复
热议问题