views:

48

answers:

2

I am working on a Web Forms application and I have some HTML code that I need in 2-3 more places.
I've created .ascx control like so which represents the repeated code:

    protected override void Render(HtmlTextWriter writer)
    {
        StringBuilder str = new StringBuilder();

        while (connRef.Read())
        {
            str.Append(connRef["some_database_field"]);
        }

        writer.Write(str.ToString());

        base.Render(writer);
    }

connRef is a reference to DataReader object that I pass where I need this piece of code to render.
In other control, I use following code:

        MSSqlConn s = new MSSqlConn();
        StringBuilder str = new StringBuilder();

        s.OpenConn("select * from notes order by note_date desc;");

        notes.note c = (notes.note)Page.LoadControl(@"/controls/notes/note.ascx");
        c.ID = "note";
        c.connRef = s;

        while (s.Read())
        {
            str.Append(Html.RenderControl(c));
        }
        s.CloseConn();

        Response.Write(str.ToString());

MSSqlConn is my class for database connection.
RenderControl renders any control as a HTML string.
s in second code snippet returns only one record instead of two. For some reason, s closes if I pass the reference to another control (c.connRef = s).

Maybe I am missing something, I don't know.

I am sorry if I hadn't explain it well.

+2  A: 

Your problem is that you're calling the Read() method twice. This is what your code is basically doing:

        while (s.Read())
        {
             while (connRef.Read())
             {
                 str.Append(connRef["some_database_field"]);
             }

        }

Every call to the Read() method advances the data reader by one record. You need to take out one of the while loops.

You should also note that if you're passing this data reader to multiple user controls, you will need to reset it to start from the beginning for each new user control.

womp
Your right. I concentrated on the functionality that I forgot that I actually put Read inside of another Read.
lopkiju
A: 

Is there a question here? You don't seem to use the questionmark anywhere :D.

Al Katawazi
It seems that I have forget posting the question. :D Sorry about that. :)
lopkiju