Datareader binding

It's surely simple but I can't figure out how I can deal with this basic stuff.

I have a web page with a poll. The choice items are coming from a SQL database, they can be just like Yes or No.

I bind the choices to a Radiobutton list.

On top of the choice items, I also have a Label webcontrol to write the question.

Because sadly Label don't have any Datasource property, I am struggling with this issue.

If I do this code (after opening my datareader)

If dtr.Read then

Poll_Question= dtr("Question")

End If

'-- Now bind to the radiobutton list
MyPoll.Datasource =dtr
MyPoll.Databind

Guess what's happen there ;-) I lost the first record because of the test which read the dtr first record.

Of course if I remove the test I have an error Attempt to read when no data is there.

I tried also to bind the radiobuttonlist first and only after bind the Label. No still the same error.

So for the moment the only way I found is to read twice the data !

 

If dtr.Read then

Poll_Question= dtr("Question")

End If

dtr.close

dtr = cmdSelect.ExecuteReader()

'-- Now bind to the radiobutton list
MyPoll.Datasource =dtr
MyPoll.Databind
dtr.close

Any idea welcome ;-)

5 Comments

  • If you're using the 1.1 framework, the obvious solution is to use DataReader.HasRows for your test.

  • If you are using stored procedures (which you should), then you could have the Question be an OUTPUT parameter. That way you don't have the question unnecessarily repeated in your resultset.



    If you don't choose to go that path, then you could manually create the Items instead of setting the DataSource.



    if (dtr.Read())

    {

    Poll_Question.Text = dtr["Question"].ToString();

    MyPoll.Items.Add(...);

    while (dtr.Read())

    {

    MyPoll.Items.Add(...);

    }

    }

    dtr.Close();

  • If you are using version 1.1 of the .NET framework, you can replace:



    if (dtr.Read())



    with



    if (dtr.HasRows)



    HTH.

  • Ugh... just like Dave Rothgery said... I suppose I should read all the comments before posting my own. ;)

  • I dont think determining whether rows exist or not helps the issue since the problem is that he is trying to get the question out of the datareader and then still trying to bind the data to radio list. You can't do both as discovered. David's suggestion about using an OUTPUT param is probably the best option for this situation.

Comments have been disabled for this content.