Home > Enterprise >  Button not firing the third time - ASP.NET code behind C#
Button not firing the third time - ASP.NET code behind C#

Time:09-05

I have written a code for button click that should retrieve data from the database and display the data row wise as required. It is working Fine for the first two clicks and it is not firing for the third time... I really don't understand why Please any help.

thank you in advance

The button code

protected void NextButton_Click(object sender, EventArgs e)
    {
        c  ; //integer created to iterate through rows of datatable
        qno  ; //just counts the rows begining from 1 and displays on page
        SqlCommand lque = new SqlCommand("select * from questions where course='"   cour   "' and [group]='"   gr   "' and semester='"   sem   "'", con);
        IDataReader rque = lque.ExecuteReader();
        if (rque.Read())
        {
            DataTable dt = new DataTable();
            dt.Load(rque);
            QuestionNo.Text = Convert.ToString(qno);
            Question.Text = dt.Rows[c].Field<string>(4);// only displaying the required columns.
            RadioButton1.Text = dt.Rows[c].Field<string>(5);
            RadioButton2.Text = dt.Rows[c].Field<string>(6);
            RadioButton3.Text = dt.Rows[c].Field<string>(7);
            RadioButton4.Text = dt.Rows[c].Field<string>(8);
        }
    }

source code for the button

<asp:Button ID="NextButton" runat="server" Text="Next" Width="111px" OnClick="NextButton_Click" />

i also checked the data is loaded without any errors into the datatable by passing the datatable as a source to the gridview, it shows all the rows in gridview but in the labels the first 2 rows only displaying. I also chekced the counting varible is only increasing 2 times.enter image description here

a few rows from the table that i am retrieving

CodePudding user response:

Your variables(c for example) will be reset to 0 on every request(button-click). Http is stateless. So you need to persist this value somewhere else(i.e. Session, ViewState, Hiddenfield, etc).

For example with Session, which you should only use if this site has not too much traffic:

private int CurrentRowIndex
{
    get
    {
        if (Session["CurrentRowIndex"] == null)
            Session["CurrentRowIndex"] = 0;
        return (int)Session["CurrentRowIndex"];
    }
    set => Session["CurrentRowIndex"] = value;
} 

protected void NextButton_Click(object sender, EventArgs e)
{
    int currentRowIndex =   CurrentRowIndex;
    // maybe you need this also for your other variables
    // ...
}

You should also not read all rows if you only want one, you should modify your sql query. If you use MS SQL-Server you could use ROW_NUMBER function to select only the required row from DB.

  • Related