Click here to Skip to main content
15,887,444 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello guys,

I wanna count number of rows (for a login page which of course should exactly be 1). I am using following code which is not working:
C#
SqlCommand myCom = new SqlCommand();
    myCom.CommandText = "SELECT * FROM StudentInfo WHERE StudentID = '" + txtID.Text+"'";
    myCom.Connection = myCon;

    SqlDataReader myReader;// = SqlDataReader();

    myReader = myCom.ExecuteReader();

    int res = 0;
    while(myReader.Read())
    {   ++res;    }

    if (res == 1) {
        myReader.Read();
        lbl6.Text = "<b>Connection is:  </b>" + myCon.State;
        lbl6.Text += "<br><b>Success:  </b>Search made.";
        txtClass.Text = myReader["Class"].ToString();
        txtID.Text = myReader["StudentID"].ToString();
        txtName.Text = myReader["StudentName"].ToString();
    }
}
Posted
Updated 4-Oct-10 7:00am
v2

This [^] thread provides some alternate solutions.
 
Share this answer
 
v2
Change your code to this if you want the labels/texboxes to contain data from the first row and res to have a count of rows at the end of the loop:

XML
while(myReader.Read())
{   ++res;    
    if (res == 1) {
        lbl6.Text = "<b>Connection is:  </b>" + myCon.State;
        lbl6.Text += "<br><b>Success:  </b>Search made.";
        txtClass.Text = myReader["Class"].ToString();
        txtID.Text = myReader["StudentID"].ToString();
        txtName.Text = myReader["StudentName"].ToString();
    }
}

//At this point res will contain the record count 
//the labels & textboxes will contain the information from the first data row
 
Share this answer
 
v2
Comments
AmbiguousName 4-Oct-10 14:53pm    
thanx....but why does not myReader.Read() work in my sample?
[no name] 4-Oct-10 15:02pm    
each time you call .read it moves to the next row in the data.

In your original code, the second call to .Read in your If block is trying to look at the second row in your data (if any). I would imagine if you check the return value from that call, it is returning false since you usually only have one data row.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900