Question

Problem: SqlReader of Read() not working

User Action:

  • enter their ID in a textbox and click a button

Program Action:

  • Select their name from database by given ID value
  • Then Print their name with HI! Message in RichTextBox or in Textbox

Error List:

  • No Error

Database:

  • Schema - dbo
  • Name - Sheet@Attendance

Here is my code:

private void swipe_button_Click(object sender, EventArgs e)
{
        String ID_givenbyUSER = IDtxtBox.Text;                      
        SqlConnection sqlConn = null;
        sqlConn = new SqlConnection("Data Source=HOME-PC\\SQLEXPRESS;Initial Catalog=ABC_SchoolDB;Integrated Security=True");
        sqlConn.Open();
        SqlCommand cmd = new SqlCommand("select Student_Name from dbo.Sheet@Attendance where Serial_Id=" + " ' " + ID_givenbyUSER + " ' ", sqlConn);

        SqlDataReader sqlReader = cmd.ExecuteReader();

        richTxtBox.Clear();
        richTxtBox.AppendText("Hi buddy "); //This line works

        while (sqlReader.Read())
        {
           richTxtBox.AppendText("Hi buddy "); //But,Its not work
           pwdbox.Text = (sqlReader["Student_Name"].ToString()); //Its not work too
        }            

        if (sqlConn != null)
        {
            sqlConn.Close();
            sqlConn = null;
        } 
    }
}
Was it helpful?

Solution

I think your problem is here:

SqlCommand cmd = new SqlCommand("select Student_Name from dbo.Sheet@Attendance where Serial_Id=" + " ' " + ID_givenbyUSER + " ' ", sqlConn);

try this instead:

SqlCommand cmd = new SqlCommand("select Student_Name from dbo.Sheet@Attendance where Serial_Id='" + ID_givenbyUSER + "'", sqlConn);

Notice the part where you concatenate the single-quotes? It had spaces around them so your query would look like:

Where Serial_Id= ' Name ' 

The space in front of the user supplied value was probably causing your query to not return any rows.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top