none
how to use DataTable to populate a ListBox? RRS feed

  • Frage

  • I am trying to retrieve data from SQL Server to a DataTable object:

    //It doesn't really relevant to the question, so you can skip reading this function

    public static DataTable FillByMail(string Email) { const string SQL_SP = "dbo.usp_MySP "; DataTable results = new DataTable(); try { SqlConnection con = new SqlConnection(ConnectionString); SqlDataAdapter da = new SqlDataAdapter(SQL_SP, con); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.Add("@email", SqlDbType.VarChar, 320).Value = Email; da.Fill(results); } catch { } return results; }

    The Stored Procedure I am calling is returning multiple rows of 4 columns:

    1. ProjectID (int)
    2. Project (varbinary)
    3. CreationDate (datetime)
    4. ProjectName (varchar)

    I am trying to populate a ListBox named "OnlineProjects" using the returned DataTable. I plan to have the "ProjectName" as the Name and a tuple of "ProjectID", "Project" and "CreationDate" as the value. But the problem is I don't know how to retrieve that data from the DataTable and how to use the retrieved data to populate the ListBox. How can it be done? please note that the DataTable can change over time so if it possible for the ListBox to change with it (Like in .DataSource) it would be great.

    Thank you in advance! 

    • Verschoben CoolDadTx Mittwoch, 20. November 2019 19:25 Winforms related
    Mittwoch, 20. November 2019 17:58

Antworten

  • No need for ValueMember, here is a mock up

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                Shown += Form1_Shown;
            }
    
            private void Form1_Shown(object sender, EventArgs e)
            {
                listBox1.DataSource = GetDataTable();
                listBox1.DisplayMember = "ProjectName";
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                var row = ((DataRowView) listBox1.SelectedItem).Row;
                
                MessageBox.Show($"{row.Field<int>("ProjectID")} - {row.Field<DateTime>("CreationDate").ToString("d")}");
    
            }
    
            public DataTable GetDataTable()
            {
                var dt = new DataTable();
                dt.Columns.Add(new DataColumn() {ColumnName = "ProjectID", DataType = typeof(int), AutoIncrement = true, AutoIncrementSeed = 1});
                dt.Columns.Add(new DataColumn() {ColumnName = "ProjectName", DataType = typeof(string)});
                dt.Columns.Add(new DataColumn() {ColumnName = "CreationDate", DataType = typeof(DateTime)});
    
                dt.Rows.Add(null, "Project 1", DateTime.Now.AddDays(1));
                dt.Rows.Add(null, "Project 2", DateTime.Now.AddDays(2));
                dt.Rows.Add(null, "Project 3", DateTime.Now.AddDays(3));
    
                return dt;
            }
        }
    }
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Als Antwort markiert avivgood Freitag, 22. November 2019 04:49
    Mittwoch, 20. November 2019 21:13
    Moderator

Alle Antworten

  • Usually the DataSource is set to the DataTable and the property DisplayMember is set to the field name which is to be displayed in the ListBox.

    So OnlineProjects.DataSource is set to the DataTable from FillByMain and the DisplayMember = "ProjectMame"


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Mittwoch, 20. November 2019 18:57
    Moderator
  • and what about the ValueMemeber? and how do i get the valueMember of a selected object later on?
    • Bearbeitet avivgood Mittwoch, 20. November 2019 19:59
    Mittwoch, 20. November 2019 19:48
  • No need for ValueMember, here is a mock up

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                Shown += Form1_Shown;
            }
    
            private void Form1_Shown(object sender, EventArgs e)
            {
                listBox1.DataSource = GetDataTable();
                listBox1.DisplayMember = "ProjectName";
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                var row = ((DataRowView) listBox1.SelectedItem).Row;
                
                MessageBox.Show($"{row.Field<int>("ProjectID")} - {row.Field<DateTime>("CreationDate").ToString("d")}");
    
            }
    
            public DataTable GetDataTable()
            {
                var dt = new DataTable();
                dt.Columns.Add(new DataColumn() {ColumnName = "ProjectID", DataType = typeof(int), AutoIncrement = true, AutoIncrementSeed = 1});
                dt.Columns.Add(new DataColumn() {ColumnName = "ProjectName", DataType = typeof(string)});
                dt.Columns.Add(new DataColumn() {ColumnName = "CreationDate", DataType = typeof(DateTime)});
    
                dt.Rows.Add(null, "Project 1", DateTime.Now.AddDays(1));
                dt.Rows.Add(null, "Project 2", DateTime.Now.AddDays(2));
                dt.Rows.Add(null, "Project 3", DateTime.Now.AddDays(3));
    
                return dt;
            }
        }
    }
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Als Antwort markiert avivgood Freitag, 22. November 2019 04:49
    Mittwoch, 20. November 2019 21:13
    Moderator
  • Hi avivgood ,
    You can use method List.Add() to store the data and set data as listBox1.DataSource.
    Then set name and value via the listBox.DisplayMember and listBox.ValueMember property.
    Here is the code you can refer to.

    private void Form1_Load(object sender, EventArgs e)
    {
        List<OnlineProjects> list = new List<OnlineProjects>();
        foreach (DataRow dataRow in dt.Rows)
        {
            list.Add(new OnlineProjects { value = new Value { ProjectID = dataRow["ProjectID "].ToString(), CreationDate = dataRow["CreationDate "].ToString(), Project = dataRow["Project "].ToString() }, ProjectName = dataRow["Id"].ToString()});
        }
    
        listBox1.DataSource = list;
        listBox1.DisplayMember = "ProjectName";
        listBox1.ValueMember = "Value";
                
    }
    public class OnlineProjects
    {
        public String ProjectName { get; set; }
        public Value value { get; set; }
    }
    
    public class Value
    {
        public string ProjectID { get; set; }
        public String CreationDate { get; set; }
        public String Project { get; set; }
    
    }

    Best Regards,
    Daniel Zhang 


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Donnerstag, 21. November 2019 05:44