views:

75

answers:

5
    ...
    ...
    ...

            try
            {
                string Tags_collect;

                SqlDataReader Data1 = cmd.ExecuteReader(); 
                Data1.Read();
                lbl_q_title.Text = Data1["subject"].ToString();

               Data1.NextResult();


               while (Data1.Read())
               {
                   Tags_collect = Data1.GetString(0);
                   Tags_collect= Tags_collect+ Tags_collect;
               }

               lbl_tags.Text = Tags_collect;
    .....
    ....

   ....

not sure why i get this error what do i miss?

+7  A: 

The first time you assign to Tags_collect is inside the while (Data1.Read()) loop, which is not guaranteed to ever execute.

Fix this by initializing the variable when it's declared:

string Tags_collect = string.Empty;

Better yet, use a StringBuilder instead of relying on repeated concatenations:

StringBuilder tags = new StringBuilder();
// ...
while (Data1.Read())
{
    string tag = Data1.GetString(0);
    sb.Append(tag);
    sb.Append(",");  // Separator
}
lbl_tags.Text = tags.ToString();

Concatenating a string to itself in a loop is very inefficient because strings are immutable, so each concatenation creates a brand-new instance. Using a StringBuilder prevents this by using a single buffer.

Aaronaught
+1 Note to @Bob, everything after "better yet" can be ignored until you feel like tackling performance/memory usage issues. It's important info, but not related to your "unassigned variable" problem.
dss539
+1  A: 

The compiler has to take into account the possibility that Data1.Read() in the while loop condition may never return true. If that happens then Tags_collect is never initialized, hence the error.

Stewart
+2  A: 

Because if Data1.Read() returns false at the beginning Tags_collect is not assigned.

brickner
+1  A: 

Hi,

you need to set your reader in a while loop like this small sample:

SqlDataReader reader = command.ExecuteReader();

    // Call Read before accessing data.
    while (reader.Read())
    {
        Console.WriteLine(String.Format("{0}, {1}",
            reader[0], reader[1]));
    }
MUG4N
+1  A: 
jalpesh