Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"data is null" when using SqlDataReader [duplicate]

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.

like image 807
Motimash Avatar asked Oct 23 '25 04:10

Motimash


1 Answers

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);

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!