Populating objectListView's cells with SQL Server data

Ben Tam 216 Reputation points
2021-09-08T14:12:17.043+00:00

Dear All,

How can I populate objectListView's cells with SQL Server data?

TIA

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,239 questions
0 comments No comments
{count} votes

Accepted answer
  1. Castorix31 81,721 Reputation points
    2021-09-08T16:12:05.707+00:00

    You can use a DataListView, inherited from ObjectListView

    I have no SQL Server to test, but I did a test with an Access database
    You can adapt it by changing the connexion string

    // using System.Data.OleDb;  
    string sFile = "E:\\Employees.accdb";  
    string sSql = "SELECT FirstName, LastName, Location FROM employees";  
    //string sSql = "SELECT * FROM employees";  
    OleDbCommand myCommand = new OleDbCommand();  
    OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + sFile + ";Persist Security Info=False;Jet OLEDB:Database Password='toto';");  
    OleDbDataAdapter dataadapter = new OleDbDataAdapter(sSql, myConnection);  
    DataSet ds = new DataSet();  
    myConnection.Open();  
    dataadapter.Fill(ds, "employees_table");  
    myConnection.Close();  
    dataListView1.DataSource = ds;  
    dataListView1.DataMember = "employees_table";  
    dataListView1.AutoResizeColumns();  
    dataListView1.ShowGroups = false;  
    

    130324-datalistview.jpg


2 additional answers

Sort by: Most helpful
  1. Ben Tam 216 Reputation points
    2021-09-12T03:10:42.477+00:00

    Hi @Castorix31

    The connection string for Access is
    "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + sFile + ";Persist Security Info=False;Jet OLEDB:Database Password='toto';"

    Could you tell me the connection string for SQL Server 2016?

    Thanks!


  2. Ben Tam 216 Reputation points
    2021-09-15T14:09:41.273+00:00

    Hi @Castorix31 ,

    Thanks for your reply.

    I have tried it. However the red lines moves to Student_dataListView. I wonder if this is not the true dataListView.
    At a time, when I draw a dataListView, it appears grey in the middle. There are 2 extra links when I click at the top-right triangle. I redraw many times but it can't be reproduced.

    132453-sqlconn.gif
    132434-student-form.gif