Team -

This has to be way more simple that I am getting. Been searching google for hours with no luck.

Simply stated, I am trying to delete a datalist row which is bound to a mssql database. Simple right!

I am missing where it is putting the key or something because I get getting the error "Object reference not set to an instance of object". I can't figure out how to give it the object!

Page code has the datakey:

<asp:DataList ID="DataList1" runat="server" DataKeyField="cartid" 
        DataSourceID="SqlDataSource1" Width="698px">

Code behind has the code from msdn:

Dim aTable As DataTable
        aTable = CType(DataList1.DataSource, DataTable)
        'reference from here

But still getting the error. I am guessing the key isn't getting passed.

I am using (VB, with Visual Studio 2010, .net 3.5)

Thanks for helping!


I don't know VB so I'm tying in C#.

try using DataGrid control, It's easier.

//In Source
<asp:DataGrid ID="myd" runat="server" DataKeyField="StudentID" onDeleteCommand="delete">
   <asp:ButtonColumn ButtonType="PushButton" Text="Delete"/>

//In Code Behind Page Model
    SqlConnection sqlcon = new SqlConnection("Server=DEEPZ; uid=sa; pwd= ; database=student");
     protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            BindGrid(); //user defined 
    public void delete(object sender, DataGridCommandEventArgs e)
        myd.Columns[0].HeaderText = "Delete";

        string del = "delete from Student where StudentID=@StudentID";
        SqlCommand cmddel = new SqlCommand(del, sqlcon);

        cmddel.Parameters.Add(new SqlParameter("@StudentID", SqlDbType.Int));
        cmddel.Parameters["@StudentID"].Value = myd.DataKeys[(int)e.Item.ItemIndex];

            Response.Write("<font color=blue> Record(s) Deleted! </font>");

        catch (SqlException)
            Response.Write("<font color=red> Deleting Failed! </font>");


    public void BindGrid()
        SqlDataAdapter sqladap = new SqlDataAdapter("select * from Student",sqlcon);
        DataSet dset = new DataSet();
        myd.DataSource = dset.Tables["Student"].DefaultView;