Search code examples
c#asp.netdatatabledatarow

object reference not set exception while getting datarow in asp


Object reference not set to an instance of an object exception occur while getting DataRow from DataTable. Can anyone give solution for this.

The code i am trying is shown below:

OleDbDataAdapter da = new OleDbDataAdapter("select * from input_alignments", cn);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable table = ds.Tables["input_alignments"];
foreach (DataRow row in table.Rows)//here exception occur
{
sb.Append(row["word1"].ToString();
}

What could be the reason for the exception?


Solution

  • Since your query returns only one resultset, you can simply have your data loaded like this:

    OleDbDataAdapter da = new OleDbDataAdapter("select * from input_alignments", cn);
    DataSet ds = new DataSet();
    da.Fill(ds);
    DataTable table = ds.Tables[0];         // use integer index instead of string one
    foreach (DataRow row in table.Rows)
    {
        sb.Append(row["word1"].ToString();
    }
    

    Also, make sure that sb is properly initialized.