Home > DeveloperSection > Forums > How to embed asp.net with SQL Server reading data and changing textbox field?
Barbara Jones

Total Post:13

Points:91
Posted on    January-29-2015 10:17 PM

 ASP.Net C#  .NET  SQL Server 
Ratings:


 1 Reply(s)
 476  View(s)
Rate this:

I am creating a sql project. I used a SqlDatareader and textbox, but when I run it I got an error

InvalidOperationException

My code is this, thanks for your help.

    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)

    {

        if (DropDownList1.SelectedIndex == 0)

        {

                string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

                using (SqlConnection con = new SqlConnection(CS))

                {

                    con.Open();

                    SqlCommand cmd = new SqlCommand

                        ("USE [PRODUCTS] SELECT QUALITIES FROM dbo.COMPUTERS WHERE ID = 0", con);

                    SqlDataReader reader;

                    reader = cmd.ExecuteReader();

                    TextBox1.Text = reader["QUALITIES"].ToString();

                }

            }

        }



Tom Cruser
Tom Cruser

Total Post:28

Points:196
Posted on    January-29-2015 10:38 PM

You are not accounting for the case where your data reader has no rows.

Try this:

while(reader.Read())

{

    TextBox1.Text = reader["QUALITIES"].ToString();

}

Also note that the "Qualities" field in your database could potentially be null. You will want to protect against this as well.


Don't want to miss updates? Please click the below button!

Follow MindStick