Вопрос

I have issue with the last string in my code.

This is my code:

private void comboLname_SelectedIndexChanged(object sender, EventArgs e)
{
            string conn = "Data Source=srv-db-02;Initial Catalog=rmsmasterdbtest;Persist Security Info=True;User ID=test;Password=*****";
            string Query = "select * from RMSCRMTest.dbo.sales where LastName= '" + comboLname.Text + "' ;";


            SqlConnection Myconn = new SqlConnection(conn);
            SqlCommand cmdDataBase = new SqlCommand(Query, Myconn);
            SqlDataReader Reader;
            try
            {
                Myconn.Open();
                Reader = cmdDataBase.ExecuteReader();
                while (Reader.Read())
                {
                    string ID = Reader.GetInt32(Reader.GetOrdinal("ID")).ToString();
                    string AccountNuber = Reader.GetString(Reader.GetOrdinal("AccountNumber")).ToString();
                    string Time = Reader.GetDateTime(Reader.GetOrdinal("Time")).ToString();
                    string Deposit = Reader.GetDecimal(Reader.GetOrdinal("Deposit")).ToString();
                    string slastname = Reader.GetString(Reader.GetOrdinal("lastname"));
                    string sstatus = Reader.GetString(Reader.GetOrdinal("status"));
                    txtid.Text = ID;
                    txtacnum.Text = AccountNuber;
                    txttime.Text = Time;
                    txtdeposit.Text = Deposit;
                    txtlname.Text = slastname;
                    txtstatus.Text = status;

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Myconn.Close();
            }
}

This issue shows since I added another column to my table and created string to the column string

sstatus = Reader.GetString(Reader.GetOrdinal("status"));

The error I get is

data is null this method or property cannot be called on null values

The other strings working just fine.

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

Решение

You need to check the nullable fields using the SqlDataReader.IsDBNull method:

int statusIndex = Reader.GetOrdinal("status");
string sstatus = Reader.IsDBNull(statusIndex) ? null : Reader.GetString(statusIndex);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top