0

I want to store value from datatbase table to array.but when I do,exception"object eferance not set instance of object " through please review my code.

.cod Behinde

   public DataSet showoption1()
    {
        SqlCommand cmd = new SqlCommand("select * from assessmenttest",con);

        SqlDataAdapter adptr = new SqlDataAdapter(cmd);

        DataSet ds = new DataSet();
        adptr.Fill(ds,"test");

        int [] arr=new int[10];
        DataTable table=ds.Tables[0];
        for(int i=0;i<table.Rows.Count;i++  )
        {
test.Agree[i] =Convert.ToInt32(ds.Tables[0].Rows[i]["option1"]);

    }

Business logic layer class code:

public class test{

public static int[] agree;

}

2
  • possibly test or test.agree not initialized...but why you using array? Commented Jun 11, 2012 at 11:42
  • Are you sure that Rows[i] contains the 'option1'? You might want to try a foreach statement instead on the items in a row to vcrify that you are getting what you expect. Commented Jun 11, 2012 at 11:42

3 Answers 3

2

test.agree is null.

You need to put a new array in the field.

Sign up to request clarification or add additional context in comments.

Comments

1

Where exactly are you getting the error, on which array? By the looks of it, it has to be on the agree[] one, which you never instantiate.

try

public static int[] agree =new int[10];

but I think you might want to make agree a list since you don't know how many you need

public static List<int> agree = new List<int>;

then usage

agree.Add(Convert.ToInt32(ds.Tables[0].Rows[i]["option1"]);

and you can access it the same as an array

MessageBox.Show(agree[1].ToString());

Comments

0

Instantiate before adding values :

 SqlCommand cmd = new SqlCommand("select * from assessmenttest", con);

        SqlDataAdapter adptr = new SqlDataAdapter(cmd);

        DataSet ds = new DataSet();
        adptr.Fill(ds, "test");

        int[] arr = new int[10];
        DataTable table = ds.Tables[0];
        test.agree = new int[table.Rows.Count];
        for (int i = 0; i < table.Rows.Count; i++)
        {

            test.agree[i] = Convert.ToInt32(ds.Tables[0].Rows[i]["option1"]);
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.