Mattwaldo Mattwaldo -4 years ago 172
ASP.NET (C#) Question

Object reference not set to an instance of an object. Error when parse the int. C#

I am experience this issue when I am converting the int to a string. I dont understand why i keep getting this error anyway i change it. I am obviously trying to get an SQL table date to go into a String Array. Any help would be much appreciated. The error is with this line:

bob[count] = item.ToString();


thanks in advance.

string str = "select Position, Description, Number from SSR_Calling_List_Pending where (ID_CODE like @isearch)";

SqlCommand com = new SqlCommand(str, conn);
com.Parameters.Add("@isearch", SqlDbType.NVarChar).Value = idCode();

conn.Open();
com.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = com;
DataTable ds = new DataTable();
da.Fill(ds);
conn.Close();

string[] bob = null;
int count = 0;

foreach (DataRow rows in ds.Rows)
{
foreach (var item in rows.ItemArray)
{
count += 1;
bob[count] = item.ToString();
}
}
return bob;

Answer Source

You should initiate the String[] with size like

string[] bob=new string[5];

or Use Generics or Collections

    List<string> bob=new List<string>();
 foreach (DataRow rows in ds.Rows)
    {
        foreach (var item in rows.ItemArray)
        {
            count += 1;
            //bob[count] = item.ToString();
            bob.Add(item.ToString());
        }
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download