C# add item to Dataset and bound listbox

chris (2004-11-23 17:21:39)
32281 views
0 replies

Once again I'll post an example of how databinding can simplify Windows Forms GUI development in C#.NET. In this case an XML string is parsed into a DataSet and a table within that DataSet is then allocated as the DataSource for a ListBox control. The aim then is to add a row to the DataTable so that the ListBox will automatically update from the DataSource. For simplicity I'm using the same example application as I used in the previous post on this channel.

Here are some code segments to show how this is achieved:

this bit you'll probably do in the class constructor - just set up the dataset and the listbox binding rules:
_dataset = new DataSet();
_dataset.ReadXml(new StringReader(resultXML));   // resultXML is a string of xml

_listBox1.ValueMember = "id";
_listBox1.DisplayMember = "name";
_listBox1.DataSource = _dataset.Tables["address"];

Now here's how you might add a row to the table data:
/* get a reference to the listbox's source datatable */
DataTable _dataTable = (DataTable)_listBox1.DataSource;

/* create a new DataRow instance */
DataRow _row = _dataTable.NewRow();

/* assign data fields to the DataRow */
_row["id"] = "1";
_row["name"] = "fred";
_row["destination"] = "123123123";
_row["email"] = "fred@spiration.co.uk";
_row["default"] = "yes";

/* add the new row to the DataTable */
_dataTable.Rows.Add(_row);

/* 
specify a sort rule for the defaultview otherwise
the new item will just appear at the bottom of the list
*/

_dataTable.DefaultView.Sort = "name";

That's all there is to it. The great simplicity here is that you only have to create a DataRow object and add it into the DataTable. There's no lisbox or item array manipulation required here. Even the sorting is managed for you.

Hope that's useful

christo
Digg it! Submit to Slashdot Add to Blinklist Del.icio.us Add to Newsvine Add to Technorati Add it to Google Bookmarks
comment