Pomster
Pomster

Reputation: 15197

How to bind data from a database to a listbox using a disconnected database

I have a listbox and would like to fill it with data from a database, the two must be linked so if i select a value from the listbox i can work with the entry in the database.

I'm using a disconnected database witch connects though a connection string:

conn = new SqlConnection(Properties.Settings.Default.DBConnectionString)

I have read up on dataset's and think i need to create one and use it as my listbox data source, Then to have the data displayed looking neat i need to set the display name.

Could someone show me how to create a dataset that's connected to my table in my database and then show me how to bind it.

Database is called TagCloudDB and table is called Tag and just listbox1.

This is the code i have so far, but it just fills the listbox with System.Data.DataRowView.

using (var conn = new SqlConnection(Properties.Settings.Default.DBConnectionString))
            {
                conn.Open();

                SqlDataAdapter daTags
                = new SqlDataAdapter("Select * From Tag", conn);

                DataSet dsTags = new DataSet("TagCloud");

                daTags.FillSchema(dsTags, SchemaType.Source, "Tag");
                daTags.Fill(dsTags, "Tag");

                daTags.MissingSchemaAction = MissingSchemaAction.AddWithKey;
                daTags.Fill(dsTags, "Tag");

                DataTable tblTag;
                tblTag = dsTags.Tables["Tag"];

                dplTags.DataSource = dsTags;
                dplTags.DataMember = "Tag";
                dplTags.DataBind();
            }

I did some thing similar in collage with VB and they have a ValueMember and Displaymember, Whats the equivalent in C#

Upvotes: 0

Views: 12061

Answers (1)

iefpw
iefpw

Reputation: 7042

SqlConnection _connection = new Connection(connectionString)
SqlDataAdapter _adapter = new SqlDataAdapter(_connection, "select * from tag")
DataTable _table = new DataTable()
_adapter.Fill(_table)

_connection.Close();

foreach(DataRow _row in _table.Rows)
{
 listbox.AddItem(new Item(_row["column1"], _row["column2"])
}

You don't need to mess with datatables. It automatically binds with the sql query.

Upvotes: 1

Related Questions