Вопрос

I am using a SqlDataReader to read values to database and then storing the values in appropriate textboxes. The code is working fine if there is no null value in the row but if there is one, it stops reading all the values after it has encountered null and displays blanks in all textboxes.

This is the code I am using :

SqlConnection con = new SqlConnection(ConfigurationManager.
ConnectionStrings["CS"].ConnectionString.ToString());

con.Open();

cmd.CommandText = "SELECT dbo.asp2.CustomerName, dbo.asp2.Email,
dbo.asp2.CP, dbo.asp2.CPN, dbo.asp2.ProductName, dbo.asp2.Warranty,
dbo.asp2.ProductSerial, dbo.asp2.ProductNumber, dbo.asp2.Description,
dbo.asp2.IssueDate, dbo.asp2.Status, dbo.asp2.Remarks, 
dbo.asp2.EngineerName from dbo.asp2 where ID='" + textBox1.Text + "'";

cmd.Connection = con;

rdr = cmd.ExecuteReader();

while (rdr.Read())
{
    textBox3.Text = rdr.GetString(0);
    textBox4.Text = rdr.GetString(1);
    textBox5.Text = rdr.GetString(2);
    textBox6.Text = rdr.GetString(3);
    textBox7.Text = rdr.GetString(4);
    textBox8.Text = rdr.GetString(5);
    textBox9.Text = rdr.GetString(6);
    textBox10.Text = rdr.GetString(7);
    textBox11.Text = rdr.GetString(8);
    textBox2.Text = rdr.GetDateTime(9).ToString();
    textBox12.Text = rdr.GetString(10);
    textBox13.Text = rdr.GetString(11);
    comboBox1.Text = rdr.GetString(12);  
}
con.Close(); 

I can't seem to figure out the problem here. Could you point it out? What I need it to do is, set the textboxes empty where there is a null value and if there is a value in table then set that value to textbox.

P.S all the values I am retrieving are stored as nvarchar in database except for IssueDate which is in smalldatetime.

Это было полезно?

Решение

I was facing the same problem (reader stopped after encountering null), what I did was :

I replaced this :

textBox3.Text = rdr.GetString(0);

with this :

textBox3.Text = rdr["ColumnName"].ToString();

Другие советы

Try this...

while (rdr.Read()) {

if (rdr.IsDBNull(0)) { textBox3.Text = rdr.GetString(0); } else { textBox3.Text = ""; }

---- For Datetime

if (rdr.IsDBNull(9)) { textBox2.Text = rdr.GetDateTime(9).ToString(); } else { textBox2.Text = ""; }

}

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top