Im converting this simple program from vb to c# it updates, displays, create and delete items from a little access database. Bellow is the PopulateListBox() function in VB it goes through every row in the data set and see if it is deleted, not deleted or has errors. I am getting 2 errors here both on the lines
lstAlbums.Items.Add(item);
and
lstAlbums.Items.Add(delitem);
now i realise that the strings are unassigned so i added
string item = “”;
string delitem = “”;
then when i start the program it fills every second item in th list box with a blank row.
How do i overcome this situation? thank you in advance anyone how can help me.
private void PopulateListBox()
{
string item;
string delitem;
//clear the list box
lstAlbums.Items.Clear();
//access each row in the data set table
foreach (DataRow row in myDataSet.Tables["albums"].Rows)
{
//list the nondeleted rows
if (!((row.RowState & DataRowState.Deleted) == DataRowState.Deleted))
item = row["albumCode"] + ", " + row["AlbumTitle"] + ", " + row["ArtistCode"];
//list rows with update errors
if (row.HasErrors)
item = "(**" + row.RowError + "**)";
lstAlbums.Items.Add(item);
//list deleted rows
if ((row.RowState & DataRowState.Deleted) == DataRowState.Deleted)
delitem = row["albumCode", DataRowVersion.Original] + ", "
+ row["AlbumTitle", DataRowVersion.Original] + ", "
+ row["ArtistCode", DataRowVersion.Original] + "***DELETED***";
lstAlbums.Items.Add(delitem);
}
You’re missing the opening and closing braces
{and}in yourifstatement, so the statement immediately following theifstatement executes if the condition matches, and the statement after that always executes.In VB.NET your
ifstatement resembles this:To translate that to C# and properly execute the 2 lines of code you should use braces:
Your current translation actually looks like this:
In other words the 2nd statement always executes. It’s a good practice to always enclose multiple statements within the braces to avoid such unintended circumstances.
Change your code to this: