Egemen HALICI
Egemen HALICI

Reputation: 33

fill array from dataset

I try to fill array from dataset. Firstly I am creating a class

public class BasvuruMaster
{
     public string Tarih { get; set; }
     public string Icerik { get; set; }
     public string RefNo { get; set; }
}

Secondly I am creating connection

I can connect to my database but I cannot fill my array.

public BasvuruMaster[] BasvuruListele(string TCK)
{
  string stm = "SELECT TARIH,ICERIK ,REFNO FROM TABLE WHERE TCK=@TCK";
  MySqlDataAdapter da = new MySqlDataAdapter(stm, cnn);
  da.SelectCommand.Parameters.AddWithValue("@TCK", TCK);
  DataSet ds = new DataSet();
  da.Fill(ds);
  BasvuruMaster[] BasVurList = new BasvuruMaster[ds.Tables[0].Rows.Count];
    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
    {
      if (ds.Tables.Count > 0)
      {
        BasVurList[i].Tarih = ds.Tables[0].Rows[i + 1].ItemArray[0].ToString();
        BasVurList[i].Icerik = ds.Tables[0].Rows[i+1].ItemArray[1].ToString();
        BasVurList[i].RefNo = ds.Tables[0].Rows[i+1].ItemArray[2].ToString();
      }
    } 
  return BasVurList;
}

What am I supposed to do?

The error message is

An exception of type 'System.NullReferenceException' occurred in WebApplication1.dll but was not handled in user code

Upvotes: 1

Views: 1506

Answers (1)

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98848

I try to explain a little bit deeply.

From Arrays (C# Programming Guide)

The default values of numeric array elements are set to zero, and reference elements are set to null.

Since you have an array of BasvuruMaster (which is a class which is a reference type) all your elements are initalized to null. And since you try to acccess Tarih, Icerik and RefNo properties of a null value, that's why you get NullReferenceException.

You can initialize all your BasvuruMaster elements inside your for loop.

BasvuruMaster[] BasVurList = new BasvuruMaster[ds.Tables[0].Rows.Count];
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
      if (ds.Tables.Count > 0)
      {
        BasVurList[i] = new BasvuruMaster(); <-- HERE
        BasVurList[i].Tarih = ds.Tables[0].Rows[i].ItemArray[0].ToString();
        BasVurList[i].Icerik = ds.Tables[0].Rows[i].ItemArray[1].ToString();
        BasVurList[i].RefNo = ds.Tables[0].Rows[i].ItemArray[2].ToString();
      }
} 

With that line, you initialize your element with new BasvuruMaster() and it's properties initialized their default values. (since they are string, both Tarih, Icerik and RefNo will be null by default)

As Ralf pointed, I think your ds.Tables[0].Rows[i+1] should be ds.Tables[0].Rows[i] since you still try to increment after the last value, you will get index out of range exception.

Upvotes: 2

Related Questions